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
+12 -11
View File
@@ -15,11 +15,12 @@
interface Props {
instance: Instance;
projectId: string;
stageId: string;
domain?: string;
onchange?: () => void;
}
const { instance, projectId, domain = '', onchange }: Props = $props();
const { instance, projectId, stageId, domain = '', onchange }: Props = $props();
let loading = $state(false);
let error = $state('');
@@ -41,16 +42,16 @@
try {
switch (action) {
case 'stop':
await api.stopInstance(projectId, instance.stage_id, instance.id);
await api.stopInstance(projectId, stageId, instance.id);
break;
case 'start':
await api.startInstance(projectId, instance.stage_id, instance.id);
await api.startInstance(projectId, stageId, instance.id);
break;
case 'restart':
await api.restartInstance(projectId, instance.stage_id, instance.id);
await api.restartInstance(projectId, stageId, instance.id);
break;
case 'remove':
await api.removeInstance(projectId, instance.stage_id, instance.id);
await api.removeInstance(projectId, stageId, instance.id);
break;
}
onchange?.();
@@ -73,7 +74,7 @@
<span class="truncate font-mono text-sm font-medium text-[var(--text-primary)]">
{instance.image_tag}
</span>
<StatusBadge status={instance.status} size="sm" />
<StatusBadge status={instance.state} size="sm" />
</div>
{#if subdomainUrl}
@@ -96,7 +97,7 @@
<!-- Action buttons -->
<div class="ml-3 flex items-center gap-1">
{#if instance.status === 'running'}
{#if instance.state === 'running'}
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-amber-50 hover:text-amber-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
@@ -115,7 +116,7 @@
>
<IconRestart size={16} />
</button>
{:else if instance.status === 'stopped'}
{:else if instance.state === 'stopped'}
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-emerald-50 hover:text-emerald-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
@@ -146,14 +147,14 @@
</div>
</div>
{#if instance.status === 'running'}
<ContainerStats source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }} />
{#if instance.state === 'running'}
<ContainerStats source={{ kind: 'instance', projectId, stageId: stageId, instanceId: instance.id }} />
{/if}
{#if showLogs}
<div class="mt-2">
<ContainerLogs
source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }}
source={{ kind: 'instance', projectId, stageId: stageId, instanceId: instance.id }}
onclose={() => { showLogs = false; }}
/>
</div>
+3 -3
View File
@@ -14,9 +14,9 @@
const { project, instances = [] }: Props = $props();
const runningCount = $derived(instances.filter((i) => i.status === 'running').length);
const stoppedCount = $derived(instances.filter((i) => i.status === 'stopped').length);
const failedCount = $derived(instances.filter((i) => i.status === 'failed').length);
const runningCount = $derived(instances.filter((i) => i.state === 'running').length);
const stoppedCount = $derived(instances.filter((i) => i.state === 'stopped').length);
const failedCount = $derived(instances.filter((i) => i.state === 'failed').length);
const totalCount = $derived(instances.length);
const overallStatus = $derived.by<'failed' | 'running' | 'stopped'>(() => {
@@ -22,7 +22,9 @@
);
const displayName = $derived(
`${container.project_name}-${container.stage_name}-${container.instance.image_tag}`
container.role
? `${container.workload_name}-${container.role}-${container.container.image_tag}`
: `${container.workload_name}-${container.container.image_tag}`
);
</script>
@@ -36,11 +38,13 @@
</h3>
<div class="mt-1.5 flex flex-wrap items-center gap-2">
<span class="inline-flex items-center gap-1 rounded-md bg-[var(--color-brand-50)] px-2 py-0.5 text-xs font-medium text-[var(--color-brand-600)]">
{container.project_name}
</span>
<span class="inline-flex items-center gap-1 rounded-md bg-[var(--surface-card-hover)] px-2 py-0.5 text-xs font-medium text-[var(--text-secondary)]">
{container.stage_name}
{container.workload_name}
</span>
{#if container.role}
<span class="inline-flex items-center gap-1 rounded-md bg-[var(--surface-card-hover)] px-2 py-0.5 text-xs font-medium text-[var(--text-secondary)]">
{container.role}
</span>
{/if}
</div>
</div>
@@ -55,14 +59,14 @@
<div class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--text-secondary)]">
<span class="inline-flex items-center gap-1">
<IconTag size={12} />
{container.instance.image_tag}
{container.container.image_tag}
</span>
<span class="inline-flex items-center gap-1">
<IconClock size={12} />
{$t('stale.lastAlive')}: {$fmt.shortDate(container.instance.last_alive_at)}
{$t('stale.lastAlive')}: {$fmt.shortDate(container.container.last_seen_at)}
</span>
<span class="rounded bg-[var(--surface-card-hover)] px-1.5 py-0.5 font-mono text-[10px]">
{container.instance.status}
{container.container.state}
</span>
</div>
@@ -71,7 +75,7 @@
<button
type="button"
disabled={cleaning}
onclick={() => oncleanup(container.instance.id)}
onclick={() => oncleanup(container.container.id)}
class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-danger)] px-3 py-1.5 text-xs font-medium text-[var(--color-danger)] transition-colors hover:bg-[var(--color-danger-light)] disabled:opacity-50 active:animate-press"
>
<IconTrash size={14} />
@@ -37,8 +37,8 @@
}
if (!cancelled) {
runningCount = allInstances.filter((i) => i.status === 'running').length;
stoppedCount = allInstances.filter((i) => i.status !== 'running').length;
runningCount = allInstances.filter((i) => i.state === 'running').length;
stoppedCount = allInstances.filter((i) => i.state !== 'running').length;
recentErrors = eventStats.error;
loading = false;
}
+21 -31
View File
@@ -33,20 +33,14 @@ export interface Stage {
updated_at: string;
}
export interface Instance {
id: string;
stage_id: string;
project_id: string;
container_id: string;
image_tag: string;
subdomain: string;
npm_proxy_id: number;
status: InstanceStatus;
port: number;
last_alive_at?: string;
created_at: string;
updated_at: string;
}
/**
* Instance is a back-compat alias: project deploys used to live in a
* dedicated `instances` table, but after the workload refactor the canonical
* row is a Container. The Instance name is kept on the frontend so existing
* components don't all rename in one change — new code should use Container
* directly, and `instance.state` (not `.status`) is the current field.
*/
export type Instance = Container;
export type InstanceStatus = 'running' | 'stopped' | 'failed' | 'removing';
@@ -349,24 +343,20 @@ export interface EventLogStats {
total: number;
}
/** A container detected as stale by the backend poller. */
/**
* A container detected as stale by the backend poller.
*
* Shape matches the Go side after the workload refactor:
* the embedded Container row is the canonical state and the workload/role
* fields decorate it for display. The legacy `instance` / `project_name` /
* `stage_name` aliases are exposed as optional getters via the StaleContainerCard
* adapter so we don't have to update every consumer at once.
*/
export interface StaleContainer {
instance: {
id: string;
stage_id: string;
project_id: string;
container_id: string;
image_tag: string;
subdomain: string;
npm_proxy_id: number;
status: string;
port: number;
last_alive_at: string;
created_at: string;
updated_at: string;
};
project_name: string;
stage_name: string;
container: Container;
workload_id: string;
workload_name: string;
role: string;
days_stale: number;
}
+2 -2
View File
@@ -86,12 +86,12 @@
const totalRunning = $derived(
Object.values(instancesByProject)
.flat()
.filter((i) => i.status === 'running').length
.filter((i) => i.state === 'running').length
);
const totalFailed = $derived(
Object.values(instancesByProject)
.flat()
.filter((i) => i.status === 'failed').length
.filter((i) => i.state === 'failed').length
);
const totalStale = $derived(staleContainers.length);
const totalSites = $derived(sites.length);
+3 -3
View File
@@ -41,7 +41,7 @@
cleaningIds = new Set([...cleaningIds, id]);
try {
await api.cleanupStaleContainer(id);
containers = containers.filter((c) => c.instance.id !== id);
containers = containers.filter((c) => c.container.id !== id);
toasts.success($t('stale.cleanedUp'));
} catch (e) {
toasts.error(e instanceof Error ? e.message : $t('stale.cleanupFailed'));
@@ -124,10 +124,10 @@
/>
{:else}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{#each containers as container (container.instance.id)}
{#each containers as container (container.container.id)}
<StaleContainerCard
{container}
cleaning={cleaningIds.has(container.instance.id)}
cleaning={cleaningIds.has(container.container.id)}
oncleanup={requestCleanup}
/>
{/each}
@@ -757,6 +757,7 @@
<InstanceCard
{instance}
{projectId}
stageId={stage.id}
domain={settingsDomain}
onchange={loadProject}
/>