Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/cli/docs/stack-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ default `max_worker_processes` to 17 to leave room for those workers; `postgresq
| ------------------------- | --------------------------------------------------------------------------------- |
| `supabase stack destroy` | Permanently delete stacks and their data. |
| `supabase stack list` | List persisted managed local stacks. |
| `supabase stack prune` | Destroy stacks whose project directory no longer exists. |
| `supabase stack install` | Resolve and lock service versions, then download artifacts without a stack. |
| `supabase stack update` | Re-resolve locked service versions and rewrite `supabase/supabase.lock`. |
| `supabase stack outdated` | Report which locked service versions `stack update` would change. |
Expand Down Expand Up @@ -452,6 +453,10 @@ uploads (`stacks/<stack-id>/uploads`) after confirmation. Use `--yes` for unatte
after one confirmation; every id must resolve before anything is destroyed, and a stack that fails
to be destroyed does not stop the rest, though the command still fails.

`supabase stack prune` destroys, after one confirmation, the stacks whose project directory no
longer exists, such as those of deleted worktrees or moved directories; `--dry-run` only lists
them. A directory on an unmounted drive counts as missing, so check with `--dry-run` first.

## Storage and bucket seeding

The `experimental.stack` flag (with the usual `SUPABASE_EXPERIMENTAL_STACK=1|0` env
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,30 @@ export class StackCommandDestroyError extends Data.TaggedError("ExperimentalStac
readonly cause?: unknown;
}> {
get [ErrorActionabilityId](): CliErrorActionabilityDeclaration {
switch (this.reason) {
case "flags":
return { ...actionability.provideFlags, fingerprint_suffix: "flags" };
case "confirmation":
return { ...actionability.provideFlags, fingerprint_suffix: "confirmation" };
case "cancelled":
return { ...actionability.cancelled, fingerprint_suffix: "cancelled" };
case "invalid-config":
return stackTargetInvalidConfigActionability(this.targetIssue);
case "runtime":
return { ...actionability.dockerNotRunning, fingerprint_suffix: "docker_not_running" };
case "uploads":
return { ...actionability.runtimeCrash, fingerprint_suffix: "filesystem_io" };
case "stack":
return causeDeclaration(this.cause) ?? unclassifiedStackFailureActionability(this.cause);
}
return stackDestroyActionability(this);
}
}

/** Classifies a destroy failure; `stack prune` reuses it for the same failures. */
export const stackDestroyActionability = (error: {
readonly reason: StackCommandDestroyError["reason"];
readonly targetIssue?: StackTargetIssue;
readonly cause?: unknown;
}): CliErrorActionabilityDeclaration => {
switch (error.reason) {
case "flags":
return { ...actionability.provideFlags, fingerprint_suffix: "flags" };
case "confirmation":
return { ...actionability.provideFlags, fingerprint_suffix: "confirmation" };
case "cancelled":
return { ...actionability.cancelled, fingerprint_suffix: "cancelled" };
case "invalid-config":
return stackTargetInvalidConfigActionability(error.targetIssue);
case "runtime":
return { ...actionability.dockerNotRunning, fingerprint_suffix: "docker_not_running" };
case "uploads":
return { ...actionability.runtimeCrash, fingerprint_suffix: "filesystem_io" };
case "stack":
return causeDeclaration(error.cause) ?? unclassifiedStackFailureActionability(error.cause);
}
};
139 changes: 11 additions & 128 deletions apps/cli/src/commands/experimental/stack/destroy/destroy.handler.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { Cause, Effect, Exit, FileSystem, Option, Path, Result } from "effect";
import type { StackError } from "@supabase/stack/effect";
import { MachineErrorContext } from "../../../../shared/output/machine-error-context.service.ts";
import { Effect, Option, Path, Result } from "effect";
import { Output } from "../../../../shared/output/output.service.ts";
import { OutputFlag, resolveYes } from "../../../../command-internal/global-flags.ts";
import { promptYesNo } from "../../../../command-internal/prompt-yes-no.ts";
import { Tty } from "../../../../shared/runtime/tty.service.ts";
import { OutputFlag } from "../../../../command-internal/global-flags.ts";
import { CommandSettings } from "../../../../config/command-settings.service.ts";
import { stackUploadsDir } from "../../../../command-internal/stack-config.ts";
import { TelemetryState } from "../../../../telemetry/telemetry-state.service.ts";
import {
isStackId,
Expand All @@ -16,23 +11,10 @@ import {
mapTargetError,
validateStackTarget,
} from "../../../../command-internal/stack-target.ts";
import { destroyScope, destroyStacks, stackLocations } from "../stack-destroy.ts";
import type { StackDestroyFlags } from "./destroy.command.ts";
import { StackCommandDestroyError } from "./destroy.errors.ts";

const destroyError = (id: string) => (cause: StackError) =>
cause.reason === "runtime-unavailable"
? new StackCommandDestroyError({
reason: "runtime",
message: cause.message,
suggestion: `Start the container engine, then run "supabase stack destroy --stack-id ${id} --yes" again; nothing was removed.`,
cause,
})
: new StackCommandDestroyError({
reason: "stack",
message: cause.message,
cause,
});

export const stackDestroy = Effect.fn("experimental.stack.destroy")(function* (
flags: StackDestroyFlags,
) {
Expand All @@ -52,11 +34,7 @@ export const stackDestroy = Effect.fn("experimental.stack.destroy")(function* (

const resolver = yield* StackTargetResolver;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const locations = {
stateRoot: path.join(settings.supabaseHome, "stacks"),
cacheRoot: path.join(settings.supabaseHome, "cache", "stack"),
};
const locations = stackLocations(path, settings.supabaseHome);
const select = Effect.fnUntraced(function* (stackId: string | undefined) {
const lookup =
stackId !== undefined && isStackId(stackId)
Expand Down Expand Up @@ -99,7 +77,7 @@ export const stackDestroy = Effect.fn("experimental.stack.destroy")(function* (
return {
id: target.id,
deleted,
scope: `stack ${target.id} at ${target.projectRoot} and its owned data`,
scope: destroyScope(target.id, target.projectRoot),
};
});
/* Every id resolves before the prompt, so a missing one destroys nothing. */
Expand All @@ -124,108 +102,13 @@ export const stackDestroy = Effect.fn("experimental.stack.destroy")(function* (
});
}
const selected = [...new Map(resolved.map((entry) => [entry.id, entry])).values()];
const yes = yield* resolveYes;
const tty = yield* Tty;
if (!yes && (!tty.stdinIsTty || !output.interactive || output.format !== "text"))
return yield* new StackCommandDestroyError({
reason: "confirmation",
message: "Destroying a stack requires confirmation; rerun with --yes.",
suggestion: "Pass --yes when running non-interactively or in a machine-readable format.",
});
const scope = selected.map((entry) => entry.scope).join("; ");
if (yes) yield* output.raw(`Permanently destroying ${scope}.\n`, "stderr");
else {
const confirmed = yield* promptYesNo(output, false, `Permanently destroy ${scope}?`, false);
if (!confirmed)
return yield* new StackCommandDestroyError({
reason: "cancelled",
message: "Stack destruction was not confirmed.",
});
}
const batch = flags.stackId.length > 1;
const [destroyed, failed] = yield* Effect.partition(selected, ({ id, deleted }) =>
Effect.gen(function* () {
const stack = Option.isSome(deleted)
? deleted.value
: yield* api.open({ ...locations, id }).pipe(Effect.mapError(destroyError(id)));
const destroying = yield* output.task(`Destroying stack ${id}...`);
yield* stack.destroy.pipe(
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? destroying.clear
: Cause.hasInterruptsOnly(exit.cause)
? destroying.cancel()
: destroying.fail(Option.getOrUndefined(Exit.findErrorOption(exit))?.message),
),
Effect.mapError(destroyError(id)),
);
const uploads = stackUploadsDir(path, settings.supabaseHome, id);
yield* fs.remove(uploads, { recursive: true, force: true }).pipe(
Effect.mapError(
(cause) =>
new StackCommandDestroyError({
reason: "uploads",
message: `Stack ${id} was destroyed, but its Storage uploads could not be removed: ${cause.message}`,
suggestion: `Remove ${uploads} manually.`,
cause,
}),
),
);
if (!batch) yield* Effect.annotateCurrentSpan({ "stack.prompted": !yes });
if (output.format === "text")
yield* output.raw(
Option.isSome(deleted)
? `Removed the containers stack ${id} left behind.\n`
: `Stack ${id} destroyed.\n`,
);
else if (!batch) yield* output.success("", { destroyed: true, id });
return { id };
}).pipe(
Effect.scoped,
Effect.mapError((error) => ({ id, error })),
),
);
if (batch)
yield* Effect.annotateCurrentSpan({
"stack.prompted": !yes,
"stack.count": selected.length,
"stack.destroyed_count": destroyed.length,
});
const [failure] = failed;
if (failure !== undefined) {
if (!batch) return yield* failure.error;
/* A stack whose registration is gone counts as destroyed and cannot be retried. */
const leftover = failed.filter(({ error }) => error.reason === "uploads");
const retryable = failed.filter(({ error }) => error.reason !== "uploads");
const machineErrorContext = yield* Effect.serviceOption(MachineErrorContext);
if (Option.isSome(machineErrorContext))
yield* machineErrorContext.value.set({
destroyed_stacks: [...destroyed, ...leftover.map(({ id }) => ({ id }))],
});
const manual =
leftover.length === 0 ? undefined : leftover.map(({ error }) => error.suggestion).join(" ");
const retry = `"supabase stack destroy ${retryable.map(({ id }) => `--stack-id ${id}`).join(" ")} --yes"`;
const runtime =
retryable.length > 0 && retryable.every(({ error }) => error.reason === "runtime");
const retrySuggestion = runtime
? `Start the container engine, then run ${retry} again; nothing was removed for those stacks.`
: `Resolve each error, then run ${retry} to retry the stacks that failed.`;
return yield* new StackCommandDestroyError({
reason: retryable.length === 0 ? "uploads" : runtime ? "runtime" : "stack",
message: `Failed to destroy ${failed.length} managed stack(s).`,
detail: failed.map(({ id, error }) => `${id}: ${error.message}`).join("\n"),
suggestion:
retryable.length === 0
? manual
: manual === undefined
? retrySuggestion
: `${retrySuggestion} ${manual}`,
// Telemetry classifies a batch by its first failure; `detail` lists every stack.
cause: failure.error,
});
}
if (batch && output.format !== "text")
yield* output.success("", { destroyed: true, stacks: destroyed });
const destroyed = yield* destroyStacks(selected, { batch });
if (output.format !== "text")
yield* output.success(
"",
batch ? { destroyed: true, stacks: destroyed } : { destroyed: true, id: destroyed[0]?.id },
);
});
return yield* body.pipe(Effect.ensuring(telemetryState.flush));
});
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,25 @@ describe("stack destroy", () => {
{ timeout: 60_000 },
);

it.live(
"reports the destroyed stack id in JSON",
() =>
Effect.gen(function* () {
const f = yield* fixture(true);
const output = mockOutput({ format: "json" });

yield* runDestroy(Layer.merge(f.layer, output.layer), ["--stack-id", f.stack.id]);

expect(output.messages).toContainEqual(
expect.objectContaining({
type: "success",
data: { destroyed: true, id: f.stack.id },
}),
);
}).pipe(Effect.provide(live)),
{ timeout: 60_000 },
);

it.effect("rejects --stack combined with repeated --stack-id flags", () =>
Effect.gen(function* () {
const f = yield* fixture(true);
Expand Down
32 changes: 3 additions & 29 deletions apps/cli/src/commands/experimental/stack/list/list.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Effect, Path } from "effect";
import { CommandSettings } from "../../../../config/command-settings.service.ts";
import { Output } from "../../../../shared/output/output.service.ts";
import { OutputFlag } from "../../../../command-internal/global-flags.ts";
import { renderGlamourTable } from "../../../../output/glamour-table.ts";
import { TelemetryState } from "../../../../telemetry/telemetry-state.service.ts";
import { StackApi, rejectStackOutput } from "../../../../command-internal/stack-target.ts";
import { renderStackListTable, stackListEntries } from "../stack-list.format.ts";
import { StackCommandListError } from "./list.errors.ts";

export const stackList = Effect.fn("experimental.stack.list")(function* () {
Expand Down Expand Up @@ -43,37 +43,11 @@ export const stackList = Effect.fn("experimental.stack.list")(function* () {
}),
),
);
const stacks = discovered
.map(({ definition, host }) => ({
id: definition.id,
project_root: definition.identity.projectRoot,
name: definition.identity.stackName,
branch_context: definition.identity.branchContext,
runtime: definition.runtime,
owner: host === undefined ? "unavailable" : "reachable",
}))
.sort((left, right) => {
for (const field of ["project_root", "name", "id"] as const) {
if (left[field] !== right[field]) return left[field] < right[field] ? -1 : 1;
}
return 0;
});
const stacks = stackListEntries(discovered);
yield* Effect.annotateCurrentSpan({ "stack.count": stacks.length });
if (output.format === "text") {
yield* output.raw(
stacks.length === 0
? "No managed stacks found.\n"
: `${renderGlamourTable(
["NAME", "PROJECT", "BRANCH", "RUNTIME", "OWNER", "ID"],
stacks.map((stack) => [
stack.name,
stack.project_root,
stack.branch_context,
stack.runtime,
stack.owner,
stack.id.slice(0, 8),
]),
).trimEnd()}\n`,
stacks.length === 0 ? "No managed stacks found.\n" : `${renderStackListTable(stacks)}\n`,
);
} else yield* output.success("", { stacks });
return stacks;
Expand Down
50 changes: 50 additions & 0 deletions apps/cli/src/commands/experimental/stack/prune/SIDE_EFFECTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# `supabase stack prune`

Permanently destroys managed stacks whose project directory no longer exists, for example the
stack of a deleted worktree or a moved project directory. The experimental feature flag controls
command registration.

## Selection and confirmation

Discovery reads the global registry like `stack list`. A stack is selected only when its saved
canonical project root is reported as not found, whatever its branch. A project root that cannot
be checked (for example permission denied) keeps its stack and prints a warning on stderr naming
it. A project on an unmounted volume is reported as not found, so run `--dry-run` first when
projects live on removable or network storage. Registry entries that cannot be read or decoded
are skipped with a warning on stderr, as in `stack list`.

`--dry-run` lists the selected stacks and destroys nothing. Otherwise they are destroyed with the
same cleanup as `stack destroy`: interactive text runs ask once whether to destroy the stacks
listed above, `--yes` skips the question and is required for non-interactive and machine-output
runs, and a stack that fails to be destroyed does not stop the rest. Right before each stack is
destroyed its project root is checked again; a stack whose directory exists again, or can no
longer be checked, is kept with a warning on stderr. A stack that another process destroyed in
the meantime counts as destroyed. Rejection or cancellation destroys nothing, and nothing is
asked when no stack is selected. Explicit legacy `-o/--output` is rejected in favor of
`--output-format`.

## Files and network

Reads `<SUPABASE_HOME or ~/.supabase>/stacks/<id>/state.json`, probes existing local owner control
endpoints and checks whether each saved project root exists. Discovery creates the registry
directory if absent and restricts it to its owner, even with `--dry-run`. Each destroyed stack is
destroyed as `stack destroy` destroys it: its namespace, owned data, port claims and
`stacks/<id>/uploads` are removed, and other stacks are untouched. No hosted API calls are made.
Telemetry flushes to `<SUPABASE_HOME or ~/.supabase>/telemetry.json` on success and failure.

## Output, exit codes and telemetry

Text prints `No stacks found whose project directory no longer exists.` when none is selected.
Otherwise it prints `Found <n> stack(s) whose project directory no longer exists:` and the
`stack list` table of them, then `Stack <id> destroyed.` per destroyed stack. JSON and
stream-json success data contain `dry_run` and `stacks`: the `stack list` entries of the selected
stacks with `--dry-run`, otherwise of the destroyed ones, as found before destruction.

Failures are reported together, even when one stack was selected, with each failed stack in the
error detail. Retryable failures suggest running `supabase stack prune --yes` again, which checks
each directory again; an upload cleanup failure names the directory to remove instead. The
JSON/stream-json error envelope lists the destroyed stacks in `destroyed_stacks`, including those
whose upload cleanup failed. Exit 0 on success, including when none is selected or every selected
stack is kept; 1 on invalid flags, registry failure, rejected or cancelled confirmation, an
unreachable engine, or cleanup failure; 130 on interruption. Standard command telemetry is
unchanged, with no custom events.
Loading
Loading