Skip to content
TypeScript

feat(server): t3 doctor can delete the database from before 0.1.0 (#20948)

Julius Marminge13aa882c22d5
diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts
index 4197b560881..57437632547 100644
--- a/apps/server/src/cli/doctor.test.ts
+++ b/apps/server/src/cli/doctor.test.ts
@@ -7,46 +7,51 @@ import * as BootService from "../cloud/bootService.ts";
import { runDoctor } from "./doctor.ts";
import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
-it.effect("--fix reclaims space with the service paused, and --dry-run changes nothing", () =>
- Effect.gen(function* () {
- const calls: string[] = [];
- const doctor = (dryRun: boolean) =>
- runDoctor("/test/statev2.sqlite", { fix: true, dryRun, interactive: false }).pipe(
- Effect.provide(
- Layer.mergeAll(
- NodeServices.layer,
- Layer.mock(BootService.BootService)({
- withStopped: (operation) =>
- Effect.sync(() => calls.push("pause")).pipe(
- Effect.andThen(operation),
- Effect.ensuring(Effect.sync(() => calls.push("resume"))),
- ),
- }),
- Layer.succeed(DatabaseMaintenance, {
- // An unconverted database: reclaiming space is recommended.
- inspect: () =>
- Effect.succeed({
- databaseBytes: 2000,
- reclaimableBytes: 1000,
- incrementalVacuumEnabled: false,
- }),
- compact: () =>
- Effect.sync(() => {
- calls.push("compact");
- return {
- beforeBytes: 2000,
- afterBytes: 1000,
- deletedEventCount: 1,
- deletedReceiptCount: 0,
- };
- }),
- }),
+it.effect(
+ "--fix reclaims space with the service paused and keeps the V1 database, and --dry-run changes nothing",
+ () =>
+ Effect.gen(function* () {
+ const calls: string[] = [];
+ const doctor = (dryRun: boolean) =>
+ runDoctor("/test/statev2.sqlite", { fix: true, dryRun, interactive: false }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ NodeServices.layer,
+ Layer.mock(BootService.BootService)({
+ withStopped: (operation) =>
+ Effect.sync(() => calls.push("pause")).pipe(
+ Effect.andThen(operation),
+ Effect.ensuring(Effect.sync(() => calls.push("resume"))),
+ ),
+ }),
+ Layer.succeed(DatabaseMaintenance, {
+ // An unconverted database: reclaiming space is recommended.
+ // A database from before 0.1.0 sits beside it; --fix must keep it.
+ inspect: () =>
+ Effect.succeed({
+ databaseBytes: 2000,
+ reclaimableBytes: 1000,
+ incrementalVacuumEnabled: false,
+ legacyDatabaseBytes: 4000,
+ }),
+ compact: () =>
+ Effect.sync(() => {
+ calls.push("compact");
+ return {
+ beforeBytes: 2000,
+ afterBytes: 1000,
+ deletedEventCount: 1,
+ deletedReceiptCount: 0,
+ };
+ }),
+ removeLegacyDatabase: () => Effect.sync(() => calls.push("remove legacy")),
+ }),
+ ),
),
- ),
- );
- yield* doctor(true);
- assert.deepEqual(calls, []);
- yield* doctor(false);
- assert.deepEqual(calls, ["pause", "compact", "resume"]);
- }),
+ );
+ yield* doctor(true);
+ assert.deepEqual(calls, []);
+ yield* doctor(false);
+ assert.deepEqual(calls, ["pause", "compact", "resume"]);
+ }),
);
diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts
index 62f25277ea9..850e67daf5c 100644
--- a/apps/server/src/cli/doctor.ts
+++ b/apps/server/src/cli/doctor.ts
@@ -25,26 +25,47 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
yield* Console.log(
`Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
);
- if (status.incrementalVacuumEnabled && status.reclaimableBytes === 0) {
- yield* Console.log("Nothing to repair.");
- return;
+ if (status.legacyDatabaseBytes !== null) {
+ yield* Console.log(
+ `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
+ );
}
- const recommended =
- !status.incrementalVacuumEnabled ||
- status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES;
const repairs = [
- {
- id: "database" as const,
- title: "Reclaim database space",
- description: status.incrementalVacuumEnabled
- ? "Returns unused space to disk."
- : "Returns unused space to disk and turns on automatic shrinking.",
- recommended,
- },
+ ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
+ ? []
+ : [
+ {
+ id: "database" as const,
+ title: "Reclaim database space",
+ description: `${
+ status.incrementalVacuumEnabled
+ ? "Returns unused space to disk."
+ : "Returns unused space to disk and turns on automatic shrinking."
+ }\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
+ recommended:
+ !status.incrementalVacuumEnabled ||
+ status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
+ },
+ ]),
+ ...(status.legacyDatabaseBytes === null
+ ? []
+ : [
+ {
+ id: "legacy" as const,
+ title: "Delete the database from before 0.1.0",
+ description: `Frees ${formatBytes(status.legacyDatabaseBytes)}. Your threads and settings are already in the current database.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`,
+ // Never chosen for you: deleting it gives up rolling back.
+ recommended: false,
+ },
+ ]),
];
+ if (repairs.length === 0) {
+ yield* Console.log("Nothing to repair.");
+ return;
+ }
for (const repair of repairs) {
yield* Console.log(
- `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
+ `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
);
}
if (options.dryRun) {
@@ -78,21 +99,29 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
);
return;
}
- const service = yield* BootService.BootService;
- yield* Console.log("\nReclaiming database space. This can take several minutes...");
- // Report inside the pause: a repair that succeeded is worth knowing about
- // even when starting the service again fails afterwards.
- yield* service.withStopped(
- maintenance
- .compact(databasePath)
- .pipe(
- Effect.tap((result) =>
- Console.log(
- `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
+ if (selected.includes("database")) {
+ const service = yield* BootService.BootService;
+ yield* Console.log("\nReclaiming database space. This can take several minutes...");
+ // Report inside the pause: a repair that succeeded is worth knowing about
+ // even when starting the service again fails afterwards.
+ yield* service.withStopped(
+ maintenance
+ .compact(databasePath)
+ .pipe(
+ Effect.tap((result) =>
+ Console.log(
+ `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
+ ),
),
),
- ),
- );
+ );
+ }
+ if (selected.includes("legacy")) {
+ // Only versions before 0.1.0 open this file, so the service keeps running;
+ // the removal itself refuses while one of those still has it open.
+ yield* maintenance.removeLegacyDatabase(databasePath);
+ yield* Console.log("\nDeleted the database from before 0.1.0.");
+ }
});
export const doctorCommand = Command.make("doctor", {
diff --git a/apps/server/src/persistence/DatabaseMaintenance.test.ts b/apps/server/src/persistence/DatabaseMaintenance.test.ts
index 0d597c5b10d..363256120a5 100644
--- a/apps/server/src/persistence/DatabaseMaintenance.test.ts
+++ b/apps/server/src/persistence/DatabaseMaintenance.test.ts
@@ -31,6 +31,45 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
}).pipe(Effect.scoped),
);
+ it.effect("reports and deletes only the database from before 0.1.0", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
+ const userdata = yield* fs.makeTempDirectoryScoped({ prefix: "t3-legacy-" });
+ const dbPath = path.join(userdata, "statev2.sqlite");
+ const legacy = path.join(userdata, "state.sqlite");
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`CREATE TABLE retained_data (value TEXT)`;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
+ assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
+
+ const openLegacy = NodeSqliteClient.layer({ filename: legacy });
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`PRAGMA journal_mode = WAL`;
+ yield* sql`CREATE TABLE v1_data (value TEXT)`;
+ }).pipe(Effect.provide(openLegacy));
+ assert.isAbove((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes ?? 0, 0);
+
+ // A version before 0.1.0 still running against it keeps it.
+ const refused = yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`SELECT value FROM v1_data`;
+ return yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath));
+ }).pipe(Effect.provide(openLegacy));
+ assert.equal(refused._tag, "DatabaseInUseError");
+ assert.isTrue(yield* fs.exists(legacy));
+
+ yield* maintenance.removeLegacyDatabase(dbPath);
+ assert.isFalse(yield* fs.exists(legacy));
+ assert.isFalse(yield* fs.exists(`${legacy}-wal`));
+ assert.isTrue(yield* fs.exists(dbPath));
+ assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
+ }).pipe(Effect.scoped),
+ );
+
it.effect("compacts an existing database offline only once its server has stopped", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/persistence/DatabaseMaintenance.ts b/apps/server/src/persistence/DatabaseMaintenance.ts
index bd794a1e269..48d9b390b15 100644
--- a/apps/server/src/persistence/DatabaseMaintenance.ts
+++ b/apps/server/src/persistence/DatabaseMaintenance.ts
@@ -3,6 +3,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import { isSqlError } from "effect/sql/SqlError";
@@ -25,7 +26,7 @@ export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()
{ path: Schema.String, cause: Schema.Defect() },
) {
override get message() {
- return "Stop the T3 Code server and desktop app before compacting the database.";
+ return "Stop the T3 Code server and desktop app, including any version before 0.1.0, before repairing the database.";
}
}
@@ -56,6 +57,15 @@ export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactErro
}
}
+export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabaseRemoveError>()(
+ "LegacyDatabaseRemoveError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message() {
+ return "Could not delete the database from before 0.1.0. Check that this user can write to the data directory.";
+ }
+}
+
/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
export class DatabaseMaintenance extends Context.Service<
DatabaseMaintenance,
@@ -65,6 +75,8 @@ export class DatabaseMaintenance extends Context.Service<
readonly databaseBytes: number;
readonly reclaimableBytes: number;
readonly incrementalVacuumEnabled: boolean;
+ /** Size of the database from before 0.1.0 still kept beside it, or null. */
+ readonly legacyDatabaseBytes: number | null;
},
DatabaseMissingError | DatabaseInspectError
>;
@@ -81,6 +93,13 @@ export class DatabaseMaintenance extends Context.Service<
| DatabaseProjectionsInvalidError
| DatabaseCompactError
>;
+ /**
+ * Deletes the database from before 0.1.0 kept beside this one. Versions
+ * before 0.1.0 read only that file; this one stays intact.
+ */
+ readonly removeLegacyDatabase: (
+ databasePath: string,
+ ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
}
>()("t3/persistence/DatabaseMaintenance") {}
@@ -102,8 +121,31 @@ const readStorage = Effect.gen(function* () {
};
});
+/**
+ * Holds an exclusive lock on the connection's database. In WAL mode this is
+ * refused while any other connection has the file open, even an idle one,
+ * which is how a running server or desktop app is detected.
+ */
+const lockExclusively = (databasePath: string) =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`PRAGMA busy_timeout = 0`;
+ yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
+ yield* sql`BEGIN EXCLUSIVE`.pipe(
+ Effect.mapError((cause) =>
+ isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
+ ? new DatabaseInUseError({ path: databasePath, cause })
+ : cause,
+ ),
+ );
+ yield* sql`COMMIT`;
+ });
+
const make = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const legacyPath = (databasePath: string) =>
+ path.join(path.dirname(databasePath), "state.sqlite");
const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
if (!(yield* fs.exists(databasePath))) {
@@ -114,9 +156,14 @@ const make = Effect.gen(function* () {
const inspect = Effect.fn("DatabaseMaintenance.inspect")(
function* (databasePath: string) {
yield* locate(databasePath);
- return yield* readStorage.pipe(
+ const storage = yield* readStorage.pipe(
Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
);
+ const legacy = legacyPath(databasePath);
+ const legacyDatabaseBytes = (yield* fs.exists(legacy))
+ ? Number((yield* fs.stat(legacy)).size)
+ : null;
+ return { ...storage, legacyDatabaseBytes };
},
(effect, databasePath) =>
effect.pipe(
@@ -132,19 +179,8 @@ const make = Effect.gen(function* () {
const beforeBytes = Number((yield* fs.stat(databasePath)).size);
const result = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
- // Hold an exclusive lock through compaction and VACUUM. In WAL mode this
- // is refused while any other connection has the file open, even an idle
- // one, which is how a running server or desktop app is detected.
- yield* sql`PRAGMA busy_timeout = 0`;
- yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
- yield* sql`BEGIN EXCLUSIVE`.pipe(
- Effect.mapError((cause) =>
- isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
- ? new DatabaseInUseError({ path: databasePath, cause })
- : cause,
- ),
- );
- yield* sql`COMMIT`;
+ // Held through compaction and VACUUM.
+ yield* lockExclusively(databasePath);
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
if (!(yield* maintenance.verify).valid) {
return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
@@ -183,7 +219,31 @@ const make = Effect.gen(function* () {
),
);
- return DatabaseMaintenance.of({ inspect, compact });
+ const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
+ function* (databasePath: string) {
+ const legacy = legacyPath(databasePath);
+ if (!(yield* fs.exists(legacy))) return;
+ // A version before 0.1.0 may still be running against it. Keep the lock
+ // while deleting, and delete the database before its WAL so a failure
+ // never leaves it without committed transactions.
+ yield* Effect.gen(function* () {
+ yield* lockExclusively(legacy);
+ for (const suffix of ["", "-wal", "-shm"]) {
+ yield* fs.remove(legacy + suffix, { force: true });
+ }
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
+ },
+ (effect, databasePath) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ cause._tag === "DatabaseInUseError"
+ ? cause
+ : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
+ ),
+ ),
+ );
+
+ return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
});
export const layer = Layer.effect(DatabaseMaintenance, make);
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index eb70af50bb0..83693a106c9 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -119,3 +119,8 @@ database through a temporary copy, so it needs free space of about the
database's size twice over: once in the system temporary directory (`TMPDIR`
or `/tmp` on Linux and macOS) and once next to the database for its
write-ahead log.
+
+If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is
+still kept next to the current one so you can roll back. `t3 doctor` offers to
+delete it, but never selects that repair for you and `--fix` skips it: once it
+is gone, a version before 0.1.0 starts with no threads or settings.