Files
tiny-forge/internal/store/workloads.go
T
alexei.dolgolyov cba2149aa9 refactor(workload): finalize containers index + post-review hardening
Wraps up the workload refactor with the fixes that came out of the multi-agent
code review (see docs/plans/workload-refactor.md "What actually shipped").

Backend:
- store.ReconcileContainer: separate write path so the 30s reconciler tick no
  longer overwrites deployer-owned fields (subdomain, proxy_route_id,
  npm_proxy_id, image_tag).
- Container.stage_id column + index; ListProxyRoutes / ListContainersByStageID
  join via stage_id (survives stage rename), with legacy fallback to
  (project_id, role=stage_name).
- Reconciler: workload-existence check (rejects forged tinyforge.workload.id
  labels), skips inventing project-kind rows, child-context cancel before
  wg.Wait() on shutdown.
- Transactional CRUD across projects / stacks / static_sites: parent UPDATE
  and workload sync land in one transaction so secret rotations are durable.
- Webhook routing reads exclusively through workloads.webhook_secret; legacy
  GetProjectByWebhookSecret / GetStaticSiteByWebhookSecret fallback removed.
- store.GetStackByComposeProjectName + indexed lookup (no more full-table
  stack scan per compose container per tick).
- store.ListMissingSweepRows: filtered query for the missing-sweep.
- /api/instances/* handlers verify (workload_id, role) match URL
  (project_id, stage_name) before mutating — closes the cross-project
  hijack the security review flagged.
- extra_json no longer referenced from Go (column kept on disk for now).

Frontend:
- WorkloadContainers.svelte: generic detail-page panel reusable by stack and
  site detail pages.
- Containers page polish: client-side kind/state filters over an unfiltered
  fetch, URL-synced filters, race-safe loads via sequence number, EN+RU i18n,
  sidebar counter via navCounts.containers.

Misc:
- scripts/dev-server.sh: tolerate empty netstat grep result.
- .gitignore: ignore docker-watcher binaries, .claude/worktrees/, .facts-sync.json.
2026-05-09 15:44:41 +03:00

190 lines
5.7 KiB
Go

package store
import (
"database/sql"
"errors"
"fmt"
"github.com/google/uuid"
)
const workloadColumns = `id, kind, ref_id, name, app_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.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; the caller is responsible for matching this to a project/stack/site.
func (s *Store) CreateWorkload(w Workload) (Workload, error) {
if w.ID == "" {
w.ID = uuid.New().String()
}
w.CreatedAt = Now()
w.UpdatedAt = w.CreatedAt
_, err := s.db.Exec(
`INSERT INTO workloads (`+workloadColumns+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
w.ID, w.Kind, w.RefID, w.Name, w.AppID,
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
}
// GetWorkloadByWebhookSecret looks up a workload by its inbound webhook URL secret.
// Returns ErrNotFound when no match — used by the webhook router.
func (s *Store) GetWorkloadByWebhookSecret(secret string) (Workload, error) {
if secret == "" {
return Workload{}, fmt.Errorf("empty secret: %w", ErrNotFound)
}
w, err := scanWorkload(s.db.QueryRow(
`SELECT `+workloadColumns+` FROM workloads WHERE webhook_secret = ?`, secret,
))
if errors.Is(err, sql.ErrNoRows) {
return Workload{}, ErrNotFound
}
if err != nil {
return Workload{}, fmt.Errorf("query workload by webhook secret: %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,
// notification config, webhook config). Kind and RefID are immutable post-create.
func (s *Store) UpdateWorkload(w Workload) error {
w.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE workloads SET name=?, app_id=?,
notification_url=?, notification_secret=?,
webhook_secret=?, webhook_signing_secret=?, webhook_require_signature=?,
updated_at=?
WHERE id=?`,
w.Name, w.AppID,
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
}
// 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
}