Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export const buildLocalDbContainerInputs = (
// this call would otherwise use.
preloadedContext?: LocalProjectContext,
/** The existing db container's network, used when the flag is absent and the env names none. */
runningNetworkId?: string,
existingDbNetworkId?: string,
): Effect.Effect<
LocalDbContainerInputs,
DbConfigLoadError | InvalidServiceVersionTagError,
Expand Down Expand Up @@ -137,7 +137,7 @@ export const buildLocalDbContainerInputs = (
projectEnvValues,
),
projectId,
runningNetworkId,
existingDbNetworkId,
});
// Only needed on Linux; Docker Desktop already resolves `host.docker.internal` elsewhere.
const extraHosts = platform === "linux" ? ["host.docker.internal:host-gateway"] : [];
Expand Down
22 changes: 17 additions & 5 deletions apps/cli/src/command-internal/db-bootstrap/local-db-running.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,10 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>

/* Built-in networks are skipped: Docker rejects aliases on them. A network created by id, or named
with `=` (which `--network` rejects), goes back by id. Podman's mode is always `bridge`. */
const attachedNetwork = (inspect: Readonly<Record<string, unknown>>): string | undefined => {
const attachedNetwork = (
inspect: Readonly<Record<string, unknown>>,
byName?: boolean,
): string | undefined => {
const hostConfig = isRecord(inspect["HostConfig"]) ? inspect["HostConfig"] : {};
const created = hostConfig["NetworkMode"];
const settings = isRecord(inspect["NetworkSettings"]) ? inspect["NetworkSettings"] : {};
Expand All @@ -161,15 +164,24 @@ const attachedNetwork = (inspect: Readonly<Record<string, unknown>>): string | u
) ?? (attached.length === 1 ? attached[0] : undefined);
if (chosen === undefined) return undefined;
const id = typeof chosen.id === "string" && chosen.id.length > 0 ? chosen.id : undefined;
/* `byName` keeps a name only, never the NetworkID a network prune can leave stale: a name
Docker could read as an option or as a full id yields nothing. */
if (byName === true)
return /^(?![0-9a-f]{64}$)[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(chosen.name)
? chosen.name
: undefined;
return chosen.name.includes("=") || (id !== undefined && id === created) ? id : chosen.name;
};

type ExistingLocalDbState = Extract<LocalDbState, { readonly exists: true }>;

/** A missing or garbled `State` counts as running, so only an explicit `Running: false` differs. */
const existingDbState = (inspect: Readonly<Record<string, unknown>>): ExistingLocalDbState => {
const existingDbState = (
inspect: Readonly<Record<string, unknown>>,
byName?: boolean,
): ExistingLocalDbState => {
const state = isRecord(inspect["State"]) ? inspect["State"] : {};
const network = attachedNetwork(inspect);
const network = attachedNetwork(inspect, byName);
return {
exists: true,
running: state["Running"] !== false,
Expand All @@ -178,15 +190,15 @@ const existingDbState = (inspect: Readonly<Record<string, unknown>>): ExistingLo
};
};

export const parseInspectStdout = (stdout: string): ExistingLocalDbState => {
export const parseInspectStdout = (stdout: string, byName?: boolean): ExistingLocalDbState => {
let parsed: unknown;
try {
parsed = JSON.parse(stdout);
} catch {
parsed = undefined;
}
const first: unknown = Array.isArray(parsed) ? parsed[0] : undefined;
return existingDbState(isRecord(first) ? first : {});
return existingDbState(isRecord(first) ? first : {}, byName);
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ const startLocalDatabaseInScope = Effect.fn("DbBootstrap.startLocalDatabase")(fu
debug,
undefined,
context,
dbState.exists ? dbState.network : undefined,
);
const {
context: { projectId, hostname },
Expand Down
19 changes: 18 additions & 1 deletion apps/cli/src/commands/db/start/start.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,15 +321,19 @@ interface DbContainerState {
function leftBehindDbRoute(
state: DbContainerState,
base: (args: ReadonlyArray<string>) => RouteResult,
network?: string,
): (args: ReadonlyArray<string>) => RouteResult {
let removed = false;
const networks = network === undefined ? {} : { [network]: {} };
return (args) => {
if (args[0] === "container" && args[1] === "rm" && args.includes(DB_CONTAINER)) {
removed = true;
return { exitCode: 0 };
}
if (!removed && args[0] === "container" && args[1] === "inspect" && args[2] === DB_CONTAINER) {
return { stdout: [JSON.stringify([{ State: state }])] };
return {
stdout: [JSON.stringify([{ State: state, NetworkSettings: { Networks: networks } }])],
};
}
if (!removed && args[0] === "create" && containerNameFromCreateArgs(args) === DB_CONTAINER) {
return {
Expand Down Expand Up @@ -690,6 +694,19 @@ describe("db start", () => {
},
);

it.effect("brings a stopped db container back up on its network", () => {
const { layer, child } = setup({
route: leftBehindDbRoute({ Running: false, Status: "exited" }, defaultRoute(), "local-net"),
projectId: DB_PROJECT_ID,
});
return Effect.gen(function* () {
yield* dbStart(DEFAULT_FLAGS).pipe(Effect.provide(layer));
const args = createArgs(child.spawned);
const networkIndex = args?.indexOf("--network") ?? -1;
expect(args?.[networkIndex + 1]).toBe("local-net");
}).pipe(withEmptyConfigEnv);
});

it.effect.each(["Engine API", "container CLI"] as const)(
"inside Bitbucket Pipelines the %s-reported stopped container fails with a supabase stop suggestion and is left in place",
(probe) => {
Expand Down
26 changes: 19 additions & 7 deletions apps/cli/src/commands/start/start.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
resolveEmailTemplateContentPath,
} from "../../command-internal/config-validate.ts";
import {
containerCliOutput,
dockerSupportsHealthStartInterval,
isContainerNotFoundMessage,
} from "../../command-internal/container-cli.ts";
Expand Down Expand Up @@ -135,6 +136,7 @@ import {
rollbackStart,
} from "../../command-internal/db-bootstrap/rollback.ts";
import { resolveDbBootstrapConfig } from "../../command-internal/db-bootstrap/bootstrap-config.ts";
import { parseInspectStdout } from "../../command-internal/db-bootstrap/local-db-running.ts";
import { startDatabase } from "../../command-internal/db-bootstrap/start-database.ts";
import { START_SERVICES } from "./start.services.ts";
import {
Expand Down Expand Up @@ -785,17 +787,27 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) {
),
);

// `--network-id` wins over the generated `supabase_network_<project>` fallback, falling back
// to `SUPABASE_NETWORK_ID` only when the flag was never passed. See
// {@link resolveDockerNetworkMode} for the full flag/env precedence.
// `--network-id`, then `SUPABASE_NETWORK_ID`, then a stopped stack's network, then the
// generated `supabase_network_<project>`; see {@link resolveDockerNetworkMode}.
const networkIdFlag = yield* NetworkIdFlag;
const envNetworkId = yield* supabaseEnvStringWithProjectFallback(
"SUPABASE_NETWORK_ID",
projectEnvValues,
);
/* Read before recovery removes the container, and only when it can decide. Recovery prunes
the project's networks, which can leave an id stale, so the network is kept by name. */
const stoppedDbNetworkId =
shouldRecoverStoppedStack && Option.isNone(networkIdFlag) && envNetworkId.length === 0
? yield* containerCliOutput(spawner, ["container", "inspect", dbContainerId]).pipe(
Effect.map(({ stdout }) => parseInspectStdout(stdout, true).network),
Effect.orElseSucceed(() => undefined),
)
: undefined;
const networkId = resolveDockerNetworkMode({
explicit: Option.getOrUndefined(networkIdFlag),
envNetworkId: yield* supabaseEnvStringWithProjectFallback(
"SUPABASE_NETWORK_ID",
projectEnvValues,
),
envNetworkId,
projectId,
existingDbNetworkId: stoppedDbNetworkId,
});
// Linux-only `host.docker.internal:host-gateway` extra host; empty on darwin/windows, where
// Docker Desktop already resolves that hostname.
Expand Down
45 changes: 44 additions & 1 deletion apps/cli/src/commands/start/start.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,48 @@ describe("start integration", () => {
}).pipe(Effect.provide([BunServices.layer, BunCrypto.layer])),
);

it.effect.each([
["its network", "local-net", "local-net", "local-net"],
["the network it joined by id", "local-net", "0f3a", "local-net"],
[
"the generated network when its network is named like an option",
"-net",
"0f3a",
"supabase_network_demo",
],
] as const)("brings a stopped stack back up on %s", ([, name, mode, network]) =>
Effect.gen(function* () {
const recovering = recoveringStackRoute(STOPPED_STATE, tempRoot.current);
const { layer, child } = yield* setup({
/* Only the network read inspects without `--format`; answer it until recovery removes
the container. */
route: (args) => {
const answer = recovering(args);
return args.join(" ") === "container inspect supabase_db_demo" &&
answer.stdout?.[0] === STOPPED_STATE
? {
stdout: [
JSON.stringify([
{
HostConfig: { NetworkMode: mode },
NetworkSettings: { Networks: { [name]: { NetworkID: "0f3a" } } },
},
]),
],
}
: answer;
},
});

yield* start(flags()).pipe(Effect.provide(layer));

const networks = child.spawned
.filter((spawn) => spawn.args[0] === "create")
.map((spawn) => spawn.args[spawn.args.indexOf("--network") + 1]);
expect(new Set(networks)).toEqual(new Set([network]));
}).pipe(withEmptyConfigEnv, Effect.provide([BunServices.layer, BunCrypto.layer])),
);

it.effect("does not remove containers when the project id sanitizes to empty", () =>
Effect.gen(function* () {
const { layer, child } = yield* setup({
Expand Down Expand Up @@ -1416,7 +1458,8 @@ describe("start integration", () => {
if (
args[0] === "container" &&
args[1] === "inspect" &&
args[2] === "supabase_db_demo"
args[2] === "supabase_db_demo" &&
args.includes("--format")
) {
dbInspects += 1;
if (dbInspects === 1) return { stdout: [STOPPED_STATE] };
Expand Down
6 changes: 3 additions & 3 deletions apps/cli/src/shared/functions/functions-docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,16 @@ export function resolveDockerNetworkMode(input: {
readonly explicit: string | undefined;
readonly envNetworkId: string | undefined;
readonly projectId: string;
/** A running stack's network, used when the flag is absent and the env names none. */
readonly runningNetworkId?: string;
/** The existing db container's network, used when the flag is absent and the env names none. */
readonly existingDbNetworkId?: string;
}): string {
if (input.explicit !== undefined) {
return input.explicit.length > 0 ? input.explicit : localDockerId("network", input.projectId);
}
if (input.envNetworkId !== undefined && input.envNetworkId.length > 0) {
return input.envNetworkId;
}
return input.runningNetworkId ?? localDockerId("network", input.projectId);
return input.existingDbNetworkId ?? localDockerId("network", input.projectId);
}

const dockerCliProjectLabel = "com.supabase.cli.project";
Expand Down
6 changes: 3 additions & 3 deletions apps/cli/src/shared/functions/functions-docker.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,16 +364,16 @@ describe("resolveDockerNetworkMode", () => {
expect(result).toBe("supabase_network_my-project");
});

it("keeps a running stack's network only when neither the flag nor the env names one", () => {
it("keeps the existing db container's network only when neither the flag nor the env names one", () => {
const resolve = (explicit: string | undefined, envNetworkId: string) =>
resolveDockerNetworkMode({
explicit,
envNetworkId,
projectId: "my-project",
runningNetworkId: "running-network",
existingDbNetworkId: "existing-network",
});

expect(resolve(undefined, "")).toBe("running-network");
expect(resolve(undefined, "")).toBe("existing-network");
expect(resolve(undefined, "env-network")).toBe("env-network");
expect(resolve("supabase_network_my-project", "")).toBe("supabase_network_my-project");
expect(resolve("", "")).toBe("supabase_network_my-project");
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/src/shared/functions/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1817,15 +1817,15 @@ const startEdgeRuntime = Effect.fn("functions.serve.startEdgeRuntime")(function*
edgeRuntimeVersionOverride,
);

const runningNetworkId = yield* inspectLocalDb(projectId);
const existingDbNetworkId = yield* inspectLocalDb(projectId);
const networkMode = resolveDockerNetworkMode({
explicit: Option.getOrUndefined(input.networkId),
envNetworkId: yield* supabaseEnvStringWithProjectFallback(
"SUPABASE_NETWORK_ID",
resolved.projectEnvValues,
),
projectId,
runningNetworkId,
existingDbNetworkId,
});
yield* bestEffortRemoveContainer(containerId);

Expand Down
Loading