refactor(workload): extract Instance entirely; Container is canonical
Build / build (push) Successful in 10m41s

End-to-end extraction of the Instance concept. After this commit:

  * internal/store/instances.go — DELETED
  * internal/store/models.go — Instance struct gone, ProxyRoute moved here
  * containers table is the single source of truth for project/stack/site
    container state. instances table is dropped via DROP TABLE migration
    (idempotent; re-runnable on every boot).
  * Legacy tinyforge.project / tinyforge.stage / tinyforge.instance-id
    Docker labels are no longer emitted; only tinyforge.workload.{id,kind},
    tinyforge.role, and tinyforge.managed are stamped on new containers.

Backend rewrites:
  - internal/deployer:        executeDeploy + blueGreenDeploy + rollback +
                              promote use store.Container natively. New
                              removeContainer() replaces removeInstance().
                              enforceMaxInstances reads via
                              ListContainersByStageID.
  - internal/reconciler:      legacy tinyforge.instance-id dispatch removed;
                              upsertByWorkloadLabel now finds existing rows
                              by docker container ID first and falls back to
                              the deterministic workloadID:role key.
  - internal/stale/scanner:   Scan + new FindStaleContainers walk the
                              containers table; emit StaleContainer JSON.
  - internal/stats/collector: ListContainers replaces ListAllInstances.
  - internal/webhook/handler: workload-secret lookup tried first; falls back
                              to project / static_site secret column.
  - internal/api: instances.go, stale.go, stats.go, stats_history.go,
                  projects.go, settings.go, docker.go, dns.go all read /
                  write through Container.

Docker layer:
  - ManagedContainer exposes WorkloadID/Kind/Role from the canonical labels.
  - ListContainers filters by tinyforge.managed=true.
  - Network creation uses LabelManaged instead of LabelProject.

Frontend:
  - Instance type is now a Container alias; .status → .state,
    .last_alive_at → .last_seen_at.
  - InstanceCard takes stageId as a prop (no longer derived from Instance).
  - StaleContainer JSON shape rewritten: { container, workload_name, role,
    days_stale }. StaleContainerCard + /containers/stale page updated.
  - ProjectCard / homepage / SystemHealthCard filter by .state.

The migration loop now tolerates "no such table" alongside "duplicate
column" / "already exists" so obsolete ALTER TABLE entries targeting the
dropped instances table no-op cleanly on first boot.

Tests: store + deployer + reconciler + webhook + staticsite + notify all
still pass. Frontend svelte-check: zero errors.
This commit is contained in:
2026-05-09 14:43:12 +03:00
parent d516462750
commit d8ab22876f
32 changed files with 649 additions and 957 deletions
+16 -19
View File
@@ -310,12 +310,15 @@ func (s *Store) runMigrations() error {
for _, m := range migrations {
if _, err := s.db.Exec(m); err != nil {
// "duplicate column" / "already exists" are expected when a
// migration has already been applied. Anything else (typo, FK
// conflict, real schema bug) must surface, otherwise the store
// silently runs against the wrong shape.
// migration has already been applied. "no such table" is
// expected for obsolete ALTER TABLE migrations targeting tables
// the workload refactor dropped (e.g. instances). Anything
// else must surface — silently running against the wrong shape
// is worse than a startup failure.
msg := err.Error()
if !strings.Contains(msg, "duplicate column") &&
!strings.Contains(msg, "already exists") {
!strings.Contains(msg, "already exists") &&
!strings.Contains(msg, "no such table") {
return fmt.Errorf("apply migration %q: %w", m, err)
}
}
@@ -323,8 +326,8 @@ func (s *Store) runMigrations() error {
// Create indexes on foreign key columns for query performance.
indexes := []string{
`CREATE INDEX IF NOT EXISTS idx_instances_stage_id ON instances(stage_id)`,
`CREATE INDEX IF NOT EXISTS idx_instances_project_id ON instances(project_id)`,
// instances table dropped 2026-05-09 (workload refactor) — no indexes
// needed; containers replaces it with idx_containers_workload below.
`CREATE INDEX IF NOT EXISTS idx_deploys_project_id ON deploys(project_id)`,
`CREATE INDEX IF NOT EXISTS idx_deploys_stage_id ON deploys(stage_id)`,
`CREATE INDEX IF NOT EXISTS idx_deploy_logs_deploy_id ON deploy_logs(deploy_id)`,
@@ -344,6 +347,10 @@ func (s *Store) runMigrations() error {
`CREATE INDEX IF NOT EXISTS idx_container_stats_container_ts ON container_stats_samples(container_id, ts)`,
`CREATE INDEX IF NOT EXISTS idx_container_stats_ts ON container_stats_samples(ts)`,
`CREATE INDEX IF NOT EXISTS idx_system_stats_ts ON system_stats_samples(ts)`,
// Drop the legacy instances table — containers is the canonical index
// after the workload refactor (2026-05-09). Idempotent: SQLite's
// DROP TABLE IF EXISTS is a no-op on databases that already shed it.
`DROP TABLE IF EXISTS instances`,
// Workload refactor indexes (2026-05-09).
`CREATE INDEX IF NOT EXISTS idx_workloads_kind ON workloads(kind)`,
`CREATE INDEX IF NOT EXISTS idx_workloads_app_id ON workloads(app_id) WHERE app_id != ''`,
@@ -449,19 +456,9 @@ CREATE TABLE IF NOT EXISTS settings (
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS instances (
id TEXT PRIMARY KEY,
stage_id TEXT NOT NULL REFERENCES stages(id) ON DELETE CASCADE,
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
container_id TEXT NOT NULL DEFAULT '',
image_tag TEXT NOT NULL,
subdomain TEXT NOT NULL DEFAULT '',
npm_proxy_id INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'stopped',
port INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- The instances table was removed in the workload refactor (2026-05-09).
-- Container state lives in the containers table; see runMigrations for the
-- current schema. The DROP TABLE migration runs unconditionally on boot.
CREATE TABLE IF NOT EXISTS deploys (
id TEXT PRIMARY KEY,