@devries-cameron20 / t3code-1 / commits / 5da53f87d9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): CLI commands no longer migrate the database of a running server (#26763)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 03:55 UTC 5da53f87d9feba9717bca516215aa3dedd0a694a
14 files changed +265 -125
apps/server/src/auth/EnvironmentAuth.ts
+1 -1
@@ -1478,7 +1478,7 @@ export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1478 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1479 );
1480
1481 -const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
1481 +const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerCliConfig);
1482
1483 export const layerRuntime = layer.pipe(
1484 Layer.provideMerge(ManagedPolicy.layer),
apps/server/src/cli/deferredImports.test.ts
-1
@@ -95,7 +95,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CLI deferred imp
95
96 assert.isTrue(Exit.hasDies(exit));
97 assert.isTrue(yield* fs.exists(runtimeStatePath));
98 - assert.isFalse(yield* fs.exists(NodePath.join(baseDir, "userdata", "server-owner.sqlite")));
98 }),
99 );
100
apps/server/src/cli/environment.ts
+2 -2
@@ -38,7 +38,7 @@ const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A,
38 Layer.provide(
39 Layer.mergeAll(
40 ServerSecretStore.layer,
41 - SqlitePersistence.layerConfig,
41 + SqlitePersistence.layerCliConfig,
42 FetchHttpClient.layer,
43 ),
44 ),
@@ -48,7 +48,7 @@ const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A,
48 Layer.provide(
49 Layer.mergeAll(
50 ServerSecretStore.layer,
51 - SqlitePersistence.layerConfig,
51 + SqlitePersistence.layerCliConfig,
52 ManagedPolicy.layer,
53 ),
54 ),
apps/server/src/cli/pair.ts
+1 -2
@@ -7,6 +7,7 @@ import {
7 } from "@t3tools/contracts";
8 import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
9 import * as HostProcess from "@t3tools/shared/HostProcess";
10 +import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
11 import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
12 import { buildPairingAppLink } from "@t3tools/shared/remote";
13 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
@@ -40,9 +41,7 @@ import {
41 } from "../serverRuntimeState.ts";
42 import {
43 buildPairingUrl,
43 - formatHostForUrl,
44 isLoopbackHost,
45 - isWildcardHost,
45 renderTerminalQrCode,
46 resolveHeadlessConnectionString,
47 } from "../startupAccess.ts";
apps/server/src/cli/project.ts
+1
@@ -217,6 +217,7 @@ const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.lay
217 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
218 ),
219 ),
220 + // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
221 Layer.provideMerge(SqlitePersistence.layerConfig),
222 );
223
apps/server/src/environment/DirectEndpoints.ts
+5 -7
@@ -16,16 +16,14 @@ import * as NodeNet from "node:net";
16 import * as NodeOS from "node:os";
17
18 import * as HostProcess from "@t3tools/shared/HostProcess";
19 -import { isTailnetHost } from "@t3tools/shared/hostClassification";
20 -
21 -import * as ServerConfig from "../config.ts";
19 import {
20 formatHostForUrl,
24 - isLoopbackHost,
25 - isPrivateNetworkAddress,
21 + isTailnetHost,
22 isWildcardHost,
27 - VIRTUAL_INTERFACE,
28 -} from "../startupAccess.ts";
23 +} from "@t3tools/shared/hostClassification";
24 +
25 +import * as ServerConfig from "../config.ts";
26 +import { isLoopbackHost, isPrivateNetworkAddress, VIRTUAL_INTERFACE } from "../startupAccess.ts";
27
28 type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
29
apps/server/src/persistence/Migrations.ts
+19
@@ -216,6 +216,25 @@ const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function*
216 });
217 });
218
219 +const latestMigrationId = Math.max(...migrationEntries.map(([id]) => id));
220 +
221 +// Mirrors the Migrator, which runs only ids above the highest recorded, plus the V2-preview reconciliation.
222 +export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () {
223 + const sql = yield* SqlClient.SqlClient;
224 + const tables = yield* sql`
225 + SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
226 + `;
227 + if (tables.length === 0) return true;
228 + const rows = yield* sql<{ readonly latestId: number | null; readonly previewRows: number }>`
229 + SELECT
230 + MAX(migration_id) AS latestId,
231 + SUM(name = 'OrchestrationV2' AND migration_id IN (53, 54)) AS previewRows
232 + FROM effect_sql_migrations
233 + `;
234 + const row = rows[0];
235 + return (row?.latestId ?? 0) < latestMigrationId || (row?.previewRows ?? 0) > 0;
236 +});
237 +
238 const run = Migrator.make({});
239
240 export interface RunMigrationsOptions {
apps/server/src/persistence/Sqlite.test.ts
+69
@@ -5,14 +5,21 @@ import * as NodePath from "node:path";
5 import * as NodeSqlite from "node:sqlite";
6 import type * as NodeWorkerThreads from "node:worker_threads";
7
8 +import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
9 import * as NodeServices from "@effect/platform-node/NodeServices";
10 import { assert, it } from "@effect/vitest";
11 import * as HostProcess from "@t3tools/shared/HostProcess";
12 +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
13 import * as Effect from "effect/Effect";
14 +import * as FileSystem from "effect/FileSystem";
15 import * as Layer from "effect/Layer";
16 import * as SqlClient from "effect/sql/SqlClient";
17 import { vi } from "vite-plus/test";
18
19 +import * as ServerConfig from "../config.ts";
20 +import * as ProcessRunner from "../processRunner.ts";
21 +import * as ServerOwnership from "../serverOwnership.ts";
22 +import { migrationManifest, runMigrations } from "./Migrations.ts";
23 import * as SqlitePersistence from "./Sqlite.ts";
24
25 const workers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
@@ -183,3 +190,65 @@ it.effect("drops planner statistics a database already has", () => {
190 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
191 );
192 });
193 +
194 +const ownT3Home = Effect.fn(function* () {
195 + const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
196 + // An empty home, so no boot service installed on this machine is read.
197 + const home = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
198 + yield* ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe(
199 + Effect.provide(ProcessRunner.layer),
200 + Effect.provideService(HostProcess.HomeDirectory, home),
201 + Effect.provideService(HostProcess.Environment, {}),
202 + );
203 +});
204 +
205 +const migrateTo = (toMigrationInclusive?: number) =>
206 + Effect.gen(function* () {
207 + const { dbPath } = yield* ServerConfig.ServerConfig;
208 + yield* runMigrations({ toMigrationInclusive }).pipe(
209 + Effect.provide(NodeSqliteClient.layer({ filename: dbPath })),
210 + );
211 + });
212 +
213 +const latestRecordedMigrationId = Effect.gen(function* () {
214 + const { dbPath } = yield* ServerConfig.ServerConfig;
215 + const rows = yield* Effect.gen(function* () {
216 + const sql = yield* SqlClient.SqlClient;
217 + return yield* sql<{ readonly id: number }>`
218 + SELECT MAX(migration_id) AS id FROM effect_sql_migrations
219 + `;
220 + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
221 + return rows[0]?.id;
222 +});
223 +
224 +const layerT3Home = ServerConfig.layerTest(process.cwd(), { prefix: "t3-sqlite-cli-" });
225 +
226 +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("layerCliConfig", (it) => {
227 + it.effect("does not migrate a T3 home a running server owns", () =>
228 + Effect.gen(function* () {
229 + const recorded = Math.max(...migrationManifest.map(([id]) => id)) - 1;
230 + yield* migrateTo(recorded);
231 + yield* ownT3Home();
232 +
233 + const opened = yield* Effect.void.pipe(
234 + Effect.provide(SqlitePersistence.layerCliConfig),
235 + Effect.result,
236 + );
237 +
238 + assert.equal(yield* latestRecordedMigrationId, recorded);
239 + assert.equal(opened._tag, "Failure");
240 + if (opened._tag === "Failure") {
241 + assert.instanceOf(opened.failure, SqlitePersistence.ServerOwnsDatabaseError);
242 + }
243 + }).pipe(Effect.scoped, Effect.provide(layerT3Home)),
244 + );
245 +
246 + it.effect("opens a current T3 home while a running server owns it", () =>
247 + Effect.gen(function* () {
248 + yield* migrateTo();
249 + yield* ownT3Home();
250 +
251 + yield* Effect.void.pipe(Effect.provide(SqlitePersistence.layerCliConfig));
252 + }).pipe(Effect.scoped, Effect.provide(layerT3Home)),
253 + );
254 +});
apps/server/src/persistence/Sqlite.ts
+97 -56
@@ -2,77 +2,118 @@ import * as Effect from "effect/Effect";
2 import * as Layer from "effect/Layer";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 +import * as Schema from "effect/Schema";
6 import * as SqlClient from "effect/sql/SqlClient";
7 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
8
8 -import { runMigrations } from "./Migrations.ts";
9 +import { hasPendingMigrations, runMigrations } from "./Migrations.ts";
10 import { initializeV2Database } from "./initializeV2Database.ts";
11 import * as ServerConfig from "../config.ts";
12 +import * as ServerOwnership from "../serverOwnership.ts";
13
14 const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024;
15
14 -const layerSetup = Layer.effectDiscard(
15 - Effect.gen(function* () {
16 - const sql = yield* SqlClient.SqlClient;
17 - // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
18 - yield* sql`PRAGMA busy_timeout = 5000;`;
19 - yield* sql`PRAGMA foreign_keys = ON;`;
20 - // Existing databases need doctor's offline VACUUM to add pointer maps for this mode.
21 - const tables = yield* sql<{
22 - readonly count: number;
23 - }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
24 - if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
25 - yield* sql`PRAGMA journal_mode = WAL;`;
26 - // FULL fsyncs every event commit on the main thread; NORMAL syncs only at WAL checkpoints.
27 - // App crashes lose nothing; OS crashes or power loss can roll back post-checkpoint commits without corruption.
28 - yield* sql`PRAGMA synchronous = NORMAL;`;
29 - // macOS fsync misses drive caches; F_FULLFSYNC flushes them at checkpoints and is ignored elsewhere.
30 - yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
31 - // Keep statement journals and sort spills off the main thread's disk path.
32 - // Large statements and open savepoints can increase peak memory use.
33 - yield* sql`PRAGMA temp_store = MEMORY;`;
34 - // PASSIVE checkpoints retain peak WAL size until the last connection closes.
35 - yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
36 - yield* runMigrations();
37 - // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
38 - // Connections cache stats; reload after deleting them.
39 - const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
40 - if (statTables.length > 0) {
41 - yield* sql`DELETE FROM sqlite_stat1;`;
42 - yield* sql`ANALYZE sqlite_schema;`;
43 - }
44 - }).pipe(Effect.withSpan("Sqlite.setup")),
45 -);
46 -
47 -export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
48 - const fs = yield* FileSystem.FileSystem;
49 - const path = yield* Path.Path;
50 - yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
16 +export class ServerOwnsDatabaseError extends Schema.TaggedError<ServerOwnsDatabaseError>()(
17 + "ServerOwnsDatabaseError",
18 + { stateDir: Schema.String },
19 +) {
20 + override get message(): string {
21 + return `Another T3 Code process, usually a running server, owns ${this.stateDir}, and this CLI would change its database schema. Use the \`t3\` that matches the running server, or stop that server, then retry. The database was not changed.`;
22 + }
23 +}
24
52 - return Layer.provideMerge(
53 - layerSetup,
54 - NodeSqliteClient.layer({
55 - filename: dbPath,
56 - readerWorker: true,
57 - // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
58 - checkpointWorker: true,
59 - spanAttributes: {
60 - "db.name": path.basename(dbPath),
61 - "service.name": "t3code-server",
62 - },
25 +// CLI commands open the server's database from another process; migrating behind its owner changes the schema it runs on.
26 +const runMigrationsAsOwner = Effect.fn("SqlitePersistence.runMigrationsAsOwner")(function* () {
27 + // With nothing pending, runMigrations only validates the recorded history and writes nothing.
28 + if (!(yield* hasPendingMigrations())) return yield* runMigrations();
29 + const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
30 + yield* ServerOwnership.holdServerOwnershipLock(serverRuntimeStatePath).pipe(
31 + Effect.catchTags({
32 + ServerAlreadyRunningError: ({ stateDir }) =>
33 + Effect.fail(new ServerOwnsDatabaseError({ stateDir })),
34 }),
35 );
65 -}, Layer.unwrap);
36 + yield* runMigrations();
37 +}, Effect.scoped);
38 +
39 +const makeLayerSetup = <E, R>(migrate: Effect.Effect<unknown, E, R>) =>
40 + Layer.effectDiscard(
41 + Effect.gen(function* () {
42 + const sql = yield* SqlClient.SqlClient;
43 + // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
44 + yield* sql`PRAGMA busy_timeout = 5000;`;
45 + yield* sql`PRAGMA foreign_keys = ON;`;
46 + // Existing databases need doctor's offline VACUUM to add pointer maps for this mode.
47 + const tables = yield* sql<{
48 + readonly count: number;
49 + }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
50 + if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
51 + yield* sql`PRAGMA journal_mode = WAL;`;
52 + // FULL fsyncs every event commit on the main thread; NORMAL syncs only at WAL checkpoints.
53 + // App crashes lose nothing; OS crashes or power loss can roll back post-checkpoint commits without corruption.
54 + yield* sql`PRAGMA synchronous = NORMAL;`;
55 + // macOS fsync misses drive caches; F_FULLFSYNC flushes them at checkpoints and is ignored elsewhere.
56 + yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
57 + // Keep statement journals and sort spills off the main thread's disk path.
58 + // Large statements and open savepoints can increase peak memory use.
59 + yield* sql`PRAGMA temp_store = MEMORY;`;
60 + // PASSIVE checkpoints retain peak WAL size until the last connection closes.
61 + yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
62 + yield* migrate;
63 + // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
64 + // Connections cache stats; reload after deleting them.
65 + const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
66 + if (statTables.length > 0) {
67 + yield* sql`DELETE FROM sqlite_stat1;`;
68 + yield* sql`ANALYZE sqlite_schema;`;
69 + }
70 + }).pipe(Effect.withSpan("Sqlite.setup")),
71 + );
72 +
73 +const layerSetup = makeLayerSetup(runMigrations());
74 +
75 +const makeLayerFromPath = <E, R>(setup: Layer.Layer<never, E, R>) =>
76 + Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
77 + const fs = yield* FileSystem.FileSystem;
78 + const path = yield* Path.Path;
79 + yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
80 +
81 + return Layer.provideMerge(
82 + setup,
83 + NodeSqliteClient.layer({
84 + filename: dbPath,
85 + readerWorker: true,
86 + // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
87 + checkpointWorker: true,
88 + spanAttributes: {
89 + "db.name": path.basename(dbPath),
90 + "service.name": "t3code-server",
91 + },
92 + }),
93 + );
94 + }, Layer.unwrap);
95 +
96 +export const layerFromPath = makeLayerFromPath(layerSetup);
97
98 export const layerMemory = Layer.provideMerge(
99 layerSetup,
100 NodeSqliteClient.layer({ filename: ":memory:" }),
101 );
102
72 -export const layerConfig = Layer.unwrap(
73 - Effect.gen(function* () {
74 - const { dbPath } = yield* ServerConfig.ServerConfig;
75 - yield* initializeV2Database(dbPath);
76 - return layerFromPath(dbPath);
77 - }),
103 +const makeLayerConfig = <E, R>(
104 + fromPath: (dbPath: string) => Layer.Layer<SqlClient.SqlClient, E, R>,
105 +) =>
106 + Layer.unwrap(
107 + Effect.gen(function* () {
108 + const { dbPath } = yield* ServerConfig.ServerConfig;
109 + yield* initializeV2Database(dbPath);
110 + return fromPath(dbPath);
111 + }),
112 + );
113 +
114 +export const layerConfig = makeLayerConfig(layerFromPath);
115 +
116 +/** For CLI commands: pending migrations run only while no server owns the T3 home. */
117 +export const layerCliConfig = makeLayerConfig(
118 + makeLayerFromPath(makeLayerSetup(runMigrationsAsOwner())),
119 );
apps/server/src/serverOwnership.ts
+55 -42
@@ -174,12 +174,53 @@ const olderBootServiceHome = Effect.fn("olderBootServiceHome")(
174 Effect.orElseSucceed(() => undefined),
175 );
176
177 +const ownershipLockPath = (stateDir: string) => NodePath.join(stateDir, "server-owner.sqlite");
178 +
179 /**
178 - * Hold an exclusive lock on the state directory until the scope closes. The
179 - * lock is an exclusive transaction on `server-owner.sqlite`, which never holds
180 - * data and must never be unlinked: the OS releases it when the process exits,
181 - * even on SIGKILL, so a crashed owner never blocks the next start.
180 + * The lock is an exclusive transaction on `server-owner.sqlite`, which never
181 + * holds data and must never be unlinked: the OS releases it when the process
182 + * exits, even on SIGKILL, so a crashed owner never blocks the next start.
183 */
184 +const openOwnershipLock = (stateDir: string) =>
185 + Effect.try({
186 + try: () => {
187 + const lockPath = ownershipLockPath(stateDir);
188 + NodeFS.mkdirSync(stateDir, { recursive: true });
189 + let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
190 + if (before === undefined) {
191 + NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644));
192 + before = NodeFS.statSync(lockPath, { bigint: true });
193 + }
194 + const db = new NodeSqlite.DatabaseSync(lockPath);
195 + try {
196 + db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
197 + const identity = NodeFS.statSync(lockPath, { bigint: true });
198 + return {
199 + db,
200 + identity,
201 + replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino,
202 + };
203 + } catch (cause) {
204 + db.close();
205 + throw cause;
206 + }
207 + },
208 + catch: (cause) =>
209 + isSqliteBusy(cause)
210 + ? new ServerAlreadyRunningError({ stateDir })
211 + : new ServerOwnershipError({ stateDir, cause }),
212 + });
213 +
214 +/** Hold only the ownership lock until the scope closes, without claiming the runtime state. */
215 +export const holdServerOwnershipLock = Effect.fn("holdServerOwnershipLock")(function* (
216 + statePath: string,
217 +) {
218 + yield* Effect.acquireRelease(openOwnershipLock(NodePath.dirname(statePath)), ({ db }) =>
219 + Effect.sync(() => db.close()),
220 + );
221 +});
222 +
223 +/** Hold an exclusive lock on the state directory until the scope closes. */
224 export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(function* (
225 statePath: string,
226 ) {
@@ -188,45 +229,17 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
229 const ownerId = yield* random
230 .uuidV4()
231 .pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause })));
191 - const lockPath = NodePath.join(stateDir, "server-owner.sqlite");
192 - const lock = yield* Effect.acquireRelease(
193 - Effect.try({
194 - try: () => {
195 - NodeFS.mkdirSync(stateDir, { recursive: true });
196 - let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
197 - if (before === undefined) {
198 - NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644));
199 - before = NodeFS.statSync(lockPath, { bigint: true });
200 - }
201 - const db = new NodeSqlite.DatabaseSync(lockPath);
202 - try {
203 - db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
204 - const identity = NodeFS.statSync(lockPath, { bigint: true });
205 - return {
206 - db,
207 - identity,
208 - replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino,
209 - };
210 - } catch (cause) {
211 - db.close();
212 - throw cause;
213 - }
214 - },
215 - catch: (cause) =>
216 - isSqliteBusy(cause)
217 - ? new ServerAlreadyRunningError({ stateDir })
218 - : new ServerOwnershipError({ stateDir, cause }),
219 - }),
220 - ({ db }) =>
221 - readPersistedServerRuntimeState(statePath).pipe(
222 - Effect.flatMap((state) =>
223 - Option.isSome(state) && state.value.ownerId === ownerId
224 - ? clearPersistedServerRuntimeState(statePath)
225 - : Effect.void,
226 - ),
227 - Effect.ignore({ log: true }),
228 - Effect.ensuring(Effect.sync(() => db.close())),
232 + const lockPath = ownershipLockPath(stateDir);
233 + const lock = yield* Effect.acquireRelease(openOwnershipLock(stateDir), ({ db }) =>
234 + readPersistedServerRuntimeState(statePath).pipe(
235 + Effect.flatMap((state) =>
236 + Option.isSome(state) && state.value.ownerId === ownerId
237 + ? clearPersistedServerRuntimeState(statePath)
238 + : Effect.void,
239 ),
240 + Effect.ignore({ log: true }),
241 + Effect.ensuring(Effect.sync(() => db.close())),
242 + ),
243 );
244
245 const previous = yield* readPersistedServerRuntimeState(statePath).pipe(
apps/server/src/serverRuntimeStartup.ts
+2 -6
@@ -10,6 +10,7 @@ import {
10 ProviderInstanceId,
11 ThreadId,
12 } from "@t3tools/contracts";
13 +import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
14 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
15 import * as Cause from "effect/Cause";
16 import * as Console from "effect/Console";
@@ -49,12 +50,7 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
50 import { getServerOwners } from "./telemetry/Identify.ts";
51 import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
52 import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
52 -import {
53 - formatHeadlessServeOutput,
54 - formatHostForUrl,
55 - isWildcardHost,
56 - issueHeadlessServeAccessInfo,
57 -} from "./startupAccess.ts";
53 +import { formatHeadlessServeOutput, issueHeadlessServeAccessInfo } from "./startupAccess.ts";
54
55 export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
56 "ServerRuntimeStartupError",
apps/server/src/serverRuntimeState.ts
+1 -1
@@ -5,9 +5,9 @@ import * as Option from "effect/Option";
5 import * as Schema from "effect/Schema";
6
7 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
8 +import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
9 import packageJson from "../package.json" with { type: "json" };
10 import type * as ServerConfig from "./config.ts";
10 -import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
11
12 export const PersistedServerRuntimeState = Schema.Struct({
13 version: Schema.Literal(1),
apps/server/src/startupAccess.ts
+6 -7
@@ -1,7 +1,12 @@
1 import * as NodeNet from "node:net";
2 import * as NodeOS from "node:os";
3
4 -import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification";
4 +import {
5 + formatHostForUrl,
6 + isPrivateNetworkHost,
7 + isSharedAddressSpaceHost,
8 + isWildcardHost,
9 +} from "@t3tools/shared/hostClassification";
10 import { QrCode } from "@t3tools/shared/qrCode";
11 import { buildPairingAppLink } from "@t3tools/shared/remote";
12 import * as Effect from "effect/Effect";
@@ -33,12 +38,6 @@ export const isLoopbackHost = (host: string | undefined): boolean => {
38 );
39 };
40
36 -export const isWildcardHost = (host: string | undefined): boolean =>
37 - host === "0.0.0.0" || host === "::" || host === "[::]";
38 -
39 -export const formatHostForUrl = (host: string): string =>
40 - host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
41 -
41 /**
42 * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
43 * macOS's `bridge100`+) have private addresses only this machine reaches. A
packages/shared/src/hostClassification.ts
+6
@@ -174,3 +174,9 @@ export const isPublicFaviconHost = (host: string): boolean => {
174 if (first === 0x3fff && (ipv6[1]! & 0xf000) === 0) return false;
175 return true;
176 };
177 +
178 +export const isWildcardHost = (host: string | undefined): boolean =>
179 + host === "0.0.0.0" || host === "::" || host === "[::]";
180 +
181 +export const formatHostForUrl = (host: string): string =>
182 + host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;