Files
tiny-forge/internal/store/workloads.go
T
alexei.dolgolyov e3c7b13d58
Build / build (push) Successful in 10m36s
chore(workload): close the workload-first arc — apps i18n + codemap + tests
Closes the workload-first refactor by landing the Priority 3 polish
items and the Priority 4 test gap. Net: ~2,400 lines added,
~350 lines modified across 13 files.

Priority 3 — polish
- apps.* i18n namespace: 276 new keys across apps.list.* (27),
  apps.new.* (91, sibling of existing apps.new.triggers.*), and
  apps.detail.* (158, sibling of existing apps.detail.bindings.*).
  EN+RU at 1314 keys each, perfectly in sync. /apps, /apps/new,
  /apps/[id] now render entirely from i18n.
- New codemap docs/CODEMAPS/workload-plugin.md (238 lines):
  Source × Trigger contract, dispatch seam, webhook fan-out path,
  recipes for adding a new Source or Trigger kind. Plus
  docs/CODEMAPS/INDEX.md gateway.

Priority 4 — tests
- internal/api/workloads_test.go (new, ~30 subtests): /api/workloads
  CRUD + deploy + delete + env + volumes + chain + promote-from +
  triggers list/inline-bind + auth gating + standalone /api/triggers
  CRUD (create / dup-409 / kind filter / delete). Uses real
  POST handlers via httptest.NewServer + a fake plugin source
  registered under "testfakesource".
- internal/deployer/dispatch_test.go (new, 11 tests):
  DispatchPlugin / DispatchTeardown / DispatchReconcile happy +
  unknown-kind + propagated-error each; PluginDeps wiring; a real
  2s-bounded RWMutex deadlock probe on PluginDeps vs SetDNSProvider.
- internal/workload/plugin/source/compose/compose_test.go (new,
  ~26 subtests): composeProjectName sanitization,
  writeYAML / writeYAMLIfChanged hash short-circuit, Validate happy
  + bad inputs, Kind / SchemaSample.

Coverage delta on the workload-plugin path:
- internal/api: 1.1% → 16.0%
- internal/deployer: 0% → 54.1%
- internal/workload/plugin/source/compose: 0% → 38.5%
- Trigger plugins already at 87-95% from the trigger-split work.

Production fix surfaced by the tests
- store.CreateWorkload now self-references RefID = ID when caller
  leaves RefID empty (the typical plugin-native path). The api
  layer's broken backfill loop (called UpdateWorkload, which
  deliberately omits ref_id) is gone. Multiple sibling plugin
  workloads can now coexist under the UNIQUE(kind, ref_id) constraint.

Review fixes addressed before commit
- CRITICAL: deadlock-detect test gained a real 2s time.After (was
  selecting on context.Background().Done() which never fires).
- HIGH: happy-path test now hard-asserts RefID = ID (was a t.Logf
  that would silently pass after a production fix).
- HIGH: standalone /api/triggers CRUD coverage added (was bypassed
  by the workload-side bind flow).
- HIGH: seedWorkload bypass deleted; tests now go through the
  real POST /api/workloads handler.
- MEDIUM: withTempDir restore is a no-op (t.Setenv auto-restores);
  dead `old := os.Getenv(...)` capture removed.
- MEDIUM: list-workloads test now asserts ID membership, not just
  count.

Doc
- WORKLOAD_REFACTOR_TODO: all three Priority 1 items, Priority 3
  polish, and Priority 4 tests marked DONE. The workload-first arc
  is closed.
2026-05-16 06:42:43 +03:00

244 lines
7.4 KiB
Go

package store
import (
"database/sql"
"errors"
"fmt"
"github.com/google/uuid"
)
const workloadColumns = `id, kind, ref_id, name, app_id,
source_kind, source_config, trigger_kind, trigger_config,
public_faces, parent_workload_id,
notification_url, notification_secret,
webhook_secret, webhook_signing_secret, webhook_require_signature,
created_at, updated_at`
func scanWorkload(scanner interface{ Scan(...any) error }) (Workload, error) {
var w Workload
err := scanner.Scan(
&w.ID, &w.Kind, &w.RefID, &w.Name, &w.AppID,
&w.SourceKind, &w.SourceConfig, &w.TriggerKind, &w.TriggerConfig,
&w.PublicFaces, &w.ParentWorkloadID,
&w.NotificationURL, &w.NotificationSecret,
&w.WebhookSecret, &w.WebhookSigningSecret, &w.WebhookRequireSignature,
&w.CreatedAt, &w.UpdatedAt,
)
return w, err
}
// CreateWorkload inserts a new workload row. The (Kind, RefID) pair
// must be unique; for plugin-native rows (Kind="plugin") the caller
// typically leaves RefID empty and we self-reference it to the row's
// own ID so the UNIQUE(kind, ref_id) constraint holds for many sibling
// plugin workloads. Legacy bridge code that wired ref_id to a
// project/stack/site row was deleted in the hard cutover.
func (s *Store) CreateWorkload(w Workload) (Workload, error) {
if w.ID == "" {
w.ID = uuid.New().String()
}
if w.RefID == "" {
w.RefID = w.ID
}
w.CreatedAt = Now()
w.UpdatedAt = w.CreatedAt
if w.SourceConfig == "" {
w.SourceConfig = "{}"
}
if w.TriggerConfig == "" {
w.TriggerConfig = "{}"
}
if w.PublicFaces == "" {
w.PublicFaces = "[]"
}
_, err := s.db.Exec(
`INSERT INTO workloads (`+workloadColumns+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
w.ID, w.Kind, w.RefID, w.Name, w.AppID,
w.SourceKind, w.SourceConfig, w.TriggerKind, w.TriggerConfig,
w.PublicFaces, w.ParentWorkloadID,
w.NotificationURL, w.NotificationSecret,
w.WebhookSecret, w.WebhookSigningSecret, BoolToInt(w.WebhookRequireSignature),
w.CreatedAt, w.UpdatedAt,
)
if err != nil {
return Workload{}, fmt.Errorf("insert workload: %w", err)
}
return w, nil
}
// GetWorkloadByID returns a single workload by its ID.
func (s *Store) GetWorkloadByID(id string) (Workload, error) {
w, err := scanWorkload(s.db.QueryRow(
`SELECT `+workloadColumns+` FROM workloads WHERE id = ?`, id,
))
if errors.Is(err, sql.ErrNoRows) {
return Workload{}, fmt.Errorf("workload %s: %w", id, ErrNotFound)
}
if err != nil {
return Workload{}, fmt.Errorf("query workload: %w", err)
}
return w, nil
}
// GetWorkloadByRef returns the workload paired with a given (kind, ref_id).
// Returns ErrNotFound if the project/stack/site has no workload row yet
// (which means the boot-time backfill hasn't run, or the kind/ref pair is wrong).
func (s *Store) GetWorkloadByRef(kind WorkloadKind, refID string) (Workload, error) {
w, err := scanWorkload(s.db.QueryRow(
`SELECT `+workloadColumns+` FROM workloads WHERE kind = ? AND ref_id = ?`,
string(kind), refID,
))
if errors.Is(err, sql.ErrNoRows) {
return Workload{}, fmt.Errorf("workload (%s,%s): %w", kind, refID, ErrNotFound)
}
if err != nil {
return Workload{}, fmt.Errorf("query workload by ref: %w", err)
}
return w, nil
}
// ListWorkloads returns all workloads, optionally filtered by kind. Pass
// empty string to get every workload regardless of kind.
func (s *Store) ListWorkloads(kind WorkloadKind) ([]Workload, error) {
var rows *sql.Rows
var err error
if kind == "" {
rows, err = s.db.Query(
`SELECT ` + workloadColumns + ` FROM workloads ORDER BY name`,
)
} else {
rows, err = s.db.Query(
`SELECT `+workloadColumns+` FROM workloads WHERE kind = ? ORDER BY name`,
string(kind),
)
}
if err != nil {
return nil, fmt.Errorf("query workloads: %w", err)
}
defer rows.Close()
out := []Workload{}
for rows.Next() {
w, err := scanWorkload(rows)
if err != nil {
return nil, fmt.Errorf("scan workload: %w", err)
}
out = append(out, w)
}
return out, rows.Err()
}
// UpdateWorkload updates the mutable fields of a workload (name, app_id,
// source/trigger config, public faces, parent chain, notification + webhook
// config). Kind and RefID are immutable post-create.
func (s *Store) UpdateWorkload(w Workload) error {
w.UpdatedAt = Now()
if w.SourceConfig == "" {
w.SourceConfig = "{}"
}
if w.TriggerConfig == "" {
w.TriggerConfig = "{}"
}
if w.PublicFaces == "" {
w.PublicFaces = "[]"
}
result, err := s.db.Exec(
`UPDATE workloads SET name=?, app_id=?,
source_kind=?, source_config=?, trigger_kind=?, trigger_config=?,
public_faces=?, parent_workload_id=?,
notification_url=?, notification_secret=?,
webhook_secret=?, webhook_signing_secret=?, webhook_require_signature=?,
updated_at=?
WHERE id=?`,
w.Name, w.AppID,
w.SourceKind, w.SourceConfig, w.TriggerKind, w.TriggerConfig,
w.PublicFaces, w.ParentWorkloadID,
w.NotificationURL, w.NotificationSecret,
w.WebhookSecret, w.WebhookSigningSecret, BoolToInt(w.WebhookRequireSignature),
w.UpdatedAt, w.ID,
)
if err != nil {
return fmt.Errorf("update workload: %w", err)
}
n, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if n == 0 {
return fmt.Errorf("workload %s: %w", w.ID, ErrNotFound)
}
return nil
}
// DeleteWorkload removes a workload row. Cascading deletes for the matching
// project/stack/site row stay with the kind-specific Delete functions; this
// only removes the workload entry.
func (s *Store) DeleteWorkload(id string) error {
result, err := s.db.Exec(`DELETE FROM workloads WHERE id = ?`, id)
if err != nil {
return fmt.Errorf("delete workload: %w", err)
}
n, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if n == 0 {
return fmt.Errorf("workload %s: %w", id, ErrNotFound)
}
return nil
}
// ListChildrenByParent returns every workload whose parent_workload_id
// equals the given id. Used to render the stages chain ("dev → staging
// → prod") on /apps/[id] without forcing a separate stages table.
//
// Returns rows ordered by name for a stable UI.
func (s *Store) ListChildrenByParent(parentID string) ([]Workload, error) {
if parentID == "" {
return []Workload{}, nil
}
rows, err := s.db.Query(
`SELECT `+workloadColumns+` FROM workloads WHERE parent_workload_id = ? ORDER BY name`,
parentID,
)
if err != nil {
return nil, fmt.Errorf("query workload children: %w", err)
}
defer rows.Close()
out := []Workload{}
for rows.Next() {
w, err := scanWorkload(rows)
if err != nil {
return nil, fmt.Errorf("scan child workload: %w", err)
}
out = append(out, w)
}
return out, rows.Err()
}
// Workload-level webhook secret accessors (Get/Set/Ensure) were dropped
// in the hard legacy cutover: the inbound `/api/webhook/workloads/...`
// route is gone. The trigger-split refactor's boot backfill still reads
// the `workloads.webhook_secret` column directly via SQL to lift any
// pre-cutover embedded secret onto its standalone Trigger row, then the
// column is effectively dead.
// DeleteWorkloadByRef removes the workload paired with a given (kind, ref_id).
// Idempotent — returns nil if no row exists, since the kind-specific Delete
// callers don't always know whether a workload row was created.
func (s *Store) DeleteWorkloadByRef(kind WorkloadKind, refID string) error {
_, err := s.db.Exec(
`DELETE FROM workloads WHERE kind = ? AND ref_id = ?`,
string(kind), refID,
)
if err != nil {
return fmt.Errorf("delete workload by ref: %w", err)
}
return nil
}