233 lines
9.7 KiB
Go
233 lines
9.7 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"sea-vhost/internal/scope"
|
|
"time"
|
|
)
|
|
|
|
type AdminBatch struct {
|
|
ID uint64 `json:"id"`
|
|
AdministratorID uint64 `json:"administratorId"`
|
|
Operation string `json:"operation"`
|
|
State string `json:"state"`
|
|
Total int `json:"total"`
|
|
Succeeded int `json:"succeeded"`
|
|
Failed int `json:"failed"`
|
|
Uncertain int `json:"uncertain"`
|
|
Pending int `json:"pending"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
FinishedAt *time.Time `json:"finishedAt,omitempty"`
|
|
SecretsExpireAt *time.Time `json:"secretsExpireAt,omitempty"`
|
|
SecretRef string `json:"-"`
|
|
Items []AdminBatchItem `json:"items,omitempty"`
|
|
}
|
|
type AdminBatchItem struct {
|
|
ID uint64 `json:"id"`
|
|
BatchID uint64 `json:"batchId"`
|
|
Row int `json:"row"`
|
|
Label string `json:"label"`
|
|
State string `json:"state"`
|
|
ResourceID *uint64 `json:"resourceId,omitempty"`
|
|
Detail string `json:"detail"`
|
|
InputCipher []byte `json:"-"`
|
|
ResultCipher []byte `json:"-"`
|
|
}
|
|
|
|
var ErrBatchKeyConflict = errors.New("请求标识已用于其他批次,请刷新后重新预览")
|
|
var ErrBatchQueueFull = errors.New("待处理批次过多,请等待现有任务完成")
|
|
|
|
func (s *Store) ExistingAdminBatch(ctx context.Context, key, digest string) (uint64, error) {
|
|
var id uint64
|
|
var expected string
|
|
err := s.db.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &expected)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return 0, nil
|
|
}
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if expected != digest {
|
|
return 0, ErrBatchKeyConflict
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func (s *Store) CreateAdminBatch(ctx context.Context, administrator uint64, key, digest, operation, ref string, items []AdminBatchItem) (uint64, error) {
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer tx.Rollback()
|
|
var adminID uint64
|
|
if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE id=? AND role='admin' AND status='active' FOR UPDATE", administrator).Scan(&adminID); err != nil {
|
|
return 0, ErrNotFound
|
|
}
|
|
var id uint64
|
|
var existing string
|
|
err = tx.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &existing)
|
|
if err == nil {
|
|
if digest != existing {
|
|
return 0, ErrBatchKeyConflict
|
|
}
|
|
return id, nil
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return 0, err
|
|
}
|
|
var queued int
|
|
if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running')").Scan(&queued); err != nil {
|
|
return 0, err
|
|
}
|
|
if queued >= 20 {
|
|
return 0, ErrBatchQueueFull
|
|
}
|
|
var apiKey any
|
|
if id := scope.IntegrationKey(ctx); id > 0 {
|
|
var activeID uint64
|
|
if err = tx.QueryRowContext(ctx, "SELECT id FROM integration_keys WHERE id=? AND administrator_id=? AND revoked_at IS NULL AND expires_at>UTC_TIMESTAMP() FOR UPDATE", id, administrator).Scan(&activeID); err != nil {
|
|
return 0, ErrNotFound
|
|
}
|
|
apiKey = id
|
|
}
|
|
result, err := tx.ExecContext(ctx, "INSERT INTO admin_batches(request_key,input_digest,administrator_id,operation,total_count,secret_ref,integration_key_id) VALUES(?,?,?,?,?,?,?)", key, digest, administrator, operation, len(items), ref, apiKey)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
inserted, err := result.LastInsertId()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
id = uint64(inserted)
|
|
for _, item := range items {
|
|
if _, err = tx.ExecContext(ctx, "INSERT INTO admin_batch_items(batch_id,item_number,label,state,input_cipher,detail,resource_id) VALUES(?,?,?,?,?,?,?)", id, item.Row, item.Label, item.State, item.InputCipher, item.Detail, item.ResourceID); err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return 0, err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
const batchSummarySQL = `SELECT b.id,b.administrator_id,b.operation,b.state,b.total_count,b.created_at,b.finished_at,b.secrets_expire_at,b.secret_ref,COALESCE(SUM(i.state='succeeded'),0),COALESCE(SUM(i.state IN ('failed','cancelled')),0),COALESCE(SUM(i.state='uncertain'),0),COALESCE(SUM(i.state IN ('pending','running')),0) FROM admin_batches b LEFT JOIN admin_batch_items i ON i.batch_id=b.id`
|
|
|
|
func scanAdminBatch(row rowScanner) (AdminBatch, error) {
|
|
var b AdminBatch
|
|
err := row.Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.State, &b.Total, &b.CreatedAt, &b.FinishedAt, &b.SecretsExpireAt, &b.SecretRef, &b.Succeeded, &b.Failed, &b.Uncertain, &b.Pending)
|
|
return b, err
|
|
}
|
|
func (s *Store) AdminBatches(ctx context.Context) ([]AdminBatch, error) {
|
|
rows, err := s.db.QueryContext(ctx, batchSummarySQL+" GROUP BY b.id ORDER BY b.id DESC LIMIT 100")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []AdminBatch{}
|
|
for rows.Next() {
|
|
b, e := scanAdminBatch(rows)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
out = append(out, b)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (s *Store) AdminBatch(ctx context.Context, id uint64, includeSecrets bool) (AdminBatch, error) {
|
|
b, err := scanAdminBatch(s.db.QueryRowContext(ctx, batchSummarySQL+" WHERE b.id=? GROUP BY b.id", id))
|
|
if err != nil {
|
|
return b, err
|
|
}
|
|
columns := "id,batch_id,item_number,label,state,resource_id,detail"
|
|
if includeSecrets {
|
|
columns += ",input_cipher,result_cipher"
|
|
}
|
|
rows, err := s.db.QueryContext(ctx, "SELECT "+columns+" FROM admin_batch_items WHERE batch_id=? ORDER BY item_number", id)
|
|
if err != nil {
|
|
return b, err
|
|
}
|
|
defer rows.Close()
|
|
b.Items = []AdminBatchItem{}
|
|
for rows.Next() {
|
|
var item AdminBatchItem
|
|
args := []any{&item.ID, &item.BatchID, &item.Row, &item.Label, &item.State, &item.ResourceID, &item.Detail}
|
|
if includeSecrets {
|
|
args = append(args, &item.InputCipher, &item.ResultCipher)
|
|
}
|
|
if err = rows.Scan(args...); err != nil {
|
|
return b, err
|
|
}
|
|
b.Items = append(b.Items, item)
|
|
}
|
|
return b, rows.Err()
|
|
}
|
|
|
|
// One advisory lock owns the queue across API processes. Restarted work is
|
|
// marked uncertain rather than issuing a second potentially destructive call.
|
|
func (s *Store) LockBatchWorker(ctx context.Context) (func(), error) {
|
|
conn, err := s.db.Conn(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var locked int
|
|
if err = conn.QueryRowContext(ctx, "SELECT GET_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)),0)").Scan(&locked); err != nil || locked != 1 {
|
|
conn.Close()
|
|
if err == nil {
|
|
err = errors.New("batch worker already active")
|
|
}
|
|
return nil, err
|
|
}
|
|
return func() {
|
|
release, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
_, _ = conn.ExecContext(release, "DO RELEASE_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)))")
|
|
conn.Close()
|
|
}, nil
|
|
}
|
|
func (s *Store) RecoverAdminBatches(ctx context.Context) error {
|
|
if _, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='uncertain',detail='服务重启前该项正在执行,请按资源 ID 核验,禁止自动重复执行',finished_at=UTC_TIMESTAMP() WHERE state='running'"); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.db.ExecContext(ctx, "UPDATE admin_batches SET state='queued' WHERE state='running'")
|
|
return err
|
|
}
|
|
func (s *Store) NextAdminBatchItem(ctx context.Context) (AdminBatch, AdminBatchItem, error) {
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return AdminBatch{}, AdminBatchItem{}, err
|
|
}
|
|
defer tx.Rollback()
|
|
var b AdminBatch
|
|
var item AdminBatchItem
|
|
err = tx.QueryRowContext(ctx, `SELECT b.id,b.administrator_id,b.operation,b.secret_ref,i.id,i.item_number,i.label,i.input_cipher FROM admin_batches b JOIN admin_batch_items i ON i.batch_id=b.id WHERE b.state IN ('queued','running') AND i.state='pending' ORDER BY b.id,i.item_number LIMIT 1 FOR UPDATE`).Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.SecretRef, &item.ID, &item.Row, &item.Label, &item.InputCipher)
|
|
if err != nil {
|
|
return b, item, err
|
|
}
|
|
item.BatchID = b.ID
|
|
if _, err = tx.ExecContext(ctx, "UPDATE admin_batch_items SET state='running',started_at=UTC_TIMESTAMP() WHERE id=? AND state='pending'", item.ID); err != nil {
|
|
return b, item, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, "UPDATE admin_batches SET state='running' WHERE id=?", b.ID); err != nil {
|
|
return b, item, err
|
|
}
|
|
return b, item, tx.Commit()
|
|
}
|
|
func (s *Store) FinishAdminBatchItem(ctx context.Context, id uint64, state, detail string, result []byte, resourceID uint64) error {
|
|
_, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state=?,detail=?,result_cipher=?,resource_id=COALESCE(NULLIF(?,0),resource_id),finished_at=UTC_TIMESTAMP() WHERE id=? AND state='running'", state, detail, result, resourceID, id)
|
|
return err
|
|
}
|
|
func (s *Store) RefreshAdminBatches(ctx context.Context) error {
|
|
_, err := s.db.ExecContext(ctx, `UPDATE admin_batches b SET b.state=CASE WHEN EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('failed','uncertain','cancelled')) THEN 'partial' ELSE 'completed' END,b.finished_at=COALESCE(b.finished_at,UTC_TIMESTAMP()),b.secrets_expire_at=COALESCE(b.secrets_expire_at,DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 HOUR)) WHERE b.state IN ('queued','running') AND NOT EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('pending','running'))`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = s.db.ExecContext(ctx, `UPDATE admin_batch_items i JOIN admin_batches b ON b.id=i.batch_id SET i.input_cipher=NULL,i.result_cipher=NULL WHERE b.secrets_expire_at<=UTC_TIMESTAMP() AND (i.input_cipher IS NOT NULL OR i.result_cipher IS NOT NULL)`)
|
|
return err
|
|
}
|
|
func (s *Store) CancelAdminBatch(ctx context.Context, id uint64) error {
|
|
_, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='cancelled',detail='管理员取消未执行项',finished_at=UTC_TIMESTAMP() WHERE batch_id=? AND state='pending'", id)
|
|
return err
|
|
}
|