Files
tiny-forge/internal/store/workloads.go
T
alexei.dolgolyov 739b67856a
Build / build (push) Successful in 10m39s
feat(cutover): hard legacy cutover — drop projects/stacks/sites/deploys
The clean-break delete that closes the workload-first refactor arc.
Net diff: ~30 backend files deleted, ~20 modified, ~12k LOC removed
on the Go side; entire /projects /stacks /sites /deploy frontend
trees gone; ~6.7k LOC removed on the Svelte/TypeScript side.

Backend
- API handlers gone: internal/api/{projects,stages,stage_env,stacks,
  static_sites,deploys,instances,volume_browser}.go
- Store CRUD + tests gone: internal/store/{projects,stages,stage_env,
  stacks,static_sites,static_site_secrets,deploys,poll_state,volumes,
  workload_sync}.go (+ _test.go siblings)
- Legacy deployer pipeline gone: internal/deployer/{bluegreen,promote,
  rollback,subdomain,resolver_test}.go; deployer.go trimmed to just the
  dispatch surface used by the plugin pipeline
- internal/staticsite/{manager,healthcheck}.go and
  internal/stack/manager.go gone (the rest of those packages stay as
  helpers imported by the static + compose plugins)
- internal/registry/poller.go gone (legacy registry poller)
- internal/volume.ResolvePath gone; ResolveWorkloadPath stays
- internal/webhook: handleWebhook (project) + handleSiteWebhook (site)
  gone; only POST /api/webhook/triggers/{secret} remains
- workload-side webhook URL handlers (getWorkloadWebhook +
  regenerateWorkloadWebhook + EnsureWorkloadWebhookSecret +
  SetWorkloadWebhookSecret + GetWorkloadByWebhookSecret) gone — they
  minted URLs that would 404 against the new trigger-only ingress
- cmd/server/main.go: dropped staticsite.Manager, stack.Manager,
  staticsite.HealthChecker, registry poller, SetSiteSyncTriggerer,
  SetStaticSiteManager, SetStackManager, wireStaticBackend
- store/store.go: idempotent DROP TABLE IF EXISTS for every legacy
  table (projects, stages, stage_env, volumes, deploys, deploy_logs,
  poll_states, stacks, stack_revisions, stack_deploys, static_sites,
  static_site_secrets); FK order children-then-parents
- store/models.go: dropped Project, Stage, Deploy, DeployLog, StageEnv,
  Volume, StaticSite, StaticSiteSecret, Stack, StackRevision,
  StackDeploy types; kept WorkloadKind constants as documented strings
- internal/store/helpers.go (new): BoolToInt, rowScanner,
  GenerateWebhookSecret extracted from deleted CRUD files
- internal/api/secrets.go (new): forwards to store.GenerateWebhookSecret
  so api + store paths share one secret-generation impl (no
  panic-vs-UUID-fallback divergence)
- internal/reconciler/reconciler.go: dropped legacy stack-by-compose
  + static-site label paths; only canonical tinyforge.workload.id
  dispatch remains
- providers (gitea_content/github_provider/gitlab_provider) gained
  path-traversal rejection on every tree entry
- internal/webhook ParsedImage / ParseImageRef demoted to package-
  private (no external callers)

Frontend
- /projects /stacks /sites /deploy routes deleted (entire trees)
- ProjectCard / InstanceCard / StaleContainerCard components deleted
- api.ts: dropped every project/stage/stack/site/deploy/instance
  helper + types (Project, Stage, Stack, StaticSite, Deploy,
  Instance, Volume, etc.); kept Workload, Container, App, Settings,
  Registry, EventTrigger, LogScanRule, webhook envelopes
- WorkloadWebhook type + getWorkloadWebhook/regenerateWorkloadWebhook
  api functions gone (mirror of the backend deletion above)
- web/src/routes/+layout.svelte: dropped /projects /sites /stacks
  /deploy nav entries, trimmed quick-nav keymap
- web/src/routes/+page.svelte: dashboard rewrite — reads
  listWorkloads + listContainers only; 4-card stat grid
  (workloads/running/failed/stale) + recent workloads strip
- navCounts.ts, SystemHealthCard.svelte, ContainerLogs.svelte,
  ContainerStats.svelte, StatusBadge.svelte, TagCombobox.svelte,
  proxies/+page.svelte, containers/+page.svelte all rewired to the
  workload-first surface
- AbortController plumbing on dashboard, nav-counts, stale page,
  SystemHealthCard so navigation doesn't leave dangling fetches
- i18n: dropped projects.*, projectDetail.*, envEditor.*,
  volumeEditor.*, volumeBrowser.*, quickDeploy.*, sites.*, stacks.*,
  instance.*, confirm.* namespaces; en/ru parity preserved (1042
  keys each)

Hardening from go-reviewer + security-reviewer + typescript-reviewer
subagent passes (0 CRITICAL across all three; 1 HIGH + ~12 MEDIUM
addressed inline before commit):

- Sec H1: dead-end workload webhook URL handlers (would mint URLs
  that 404 the new trigger-only ingress) deleted across backend +
  frontend
- Go M1: IsTerminalDeployStatus dropped (no production callers)
- Go M2: ParsedImage/ParseImageRef lowercased (in-package only)
- Go M6: generateWebhookSecret unified — api shim forwards to
  store.GenerateWebhookSecret
- Doc/comment freshness: stage_id (no longer FK), ProxyRoute legacy
  field names, workloadIDRow rationale, webhook_deliveries.target_type
  enum, WebhookDeliveryLog component header

Doc
- WORKLOAD_REFACTOR_TODO: cutover marked DONE; all three Priority 1
  items are now shipped. Next focus is Priority 3 polish (apps.* i18n
  + codemap entries) and Priority 4 tests.

Behavioral notes for operators upgrading from a pre-cutover build
- Existing rows in the dropped tables disappear on first boot.
- Legacy webhook URLs at /api/webhook/{secret} and
  /api/webhook/sites/{secret} return 404; CI configs must repoint to
  /api/webhook/triggers/{secret} (the trigger-split boot backfill
  lifted any embedded workload secret onto a Trigger row, so the
  secret value itself carries over).
- Frontend routes /projects /stacks /sites /deploy are gone; nav
  links replaced with /apps and /triggers.
2026-05-16 06:00:21 +03:00

237 lines
7.1 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; 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
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
}