Files
tiny-forge/internal/store/workloads.go
T
alexei.dolgolyov db235c1412 feat(workload): write-through workload sync + boot-time backfill
CRUD on Project / Stack / StaticSite now keeps a paired Workload
row in sync. Secret setters (webhook secret, signing secret,
require-signature toggle, notification secret) all re-sync after
mutating the source-of-truth row so the workload row always
reflects the canonical state.

Delete cascades: DeleteProject/Stack/StaticSite now drop the
matching workload row plus any container index entries owned by
it, so global views don't show ghost rows.

Boot-time BackfillWorkloads scans every project/stack/site and
ensures each has a workload row. Idempotent — safe to run on
every restart, recovers from a deleted/missing workload row.

Behavior unchanged for existing call sites; the workloads table
just starts being populated. Deployer / reconciler / consumer
switchover land in the next commit.
2026-05-09 13:28:20 +03:00

187 lines
5.6 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()
}
if w.AppID == "" {
w.AppID = ""
}
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, _ := result.RowsAffected()
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, _ := result.RowsAffected()
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
}