@drfed/models 0.0.0-stage → 0.1.0-dev.554
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +230 -2
- package/dist/activity-delivery.d.mts +111 -0
- package/dist/activity-delivery.d.mts.map +1 -0
- package/dist/activity-delivery.mjs +240 -0
- package/dist/activity-delivery.mjs.map +1 -0
- package/dist/db-DtcLuISw.d.mts +3098 -0
- package/dist/db-DtcLuISw.d.mts.map +1 -0
- package/dist/db.d.mts +2 -0
- package/dist/db.mjs +3 -0
- package/dist/email.d.mts +39 -0
- package/dist/email.d.mts.map +1 -0
- package/dist/email.mjs +12 -0
- package/dist/email.mjs.map +1 -0
- package/dist/index.d.mts +14 -0
- package/dist/index.mjs +18 -0
- package/dist/instance.d.mts +11 -0
- package/dist/instance.d.mts.map +1 -0
- package/dist/instance.mjs +21 -0
- package/dist/instance.mjs.map +1 -0
- package/dist/key.d.mts +2 -0
- package/dist/key.mjs +86 -0
- package/dist/key.mjs.map +1 -0
- package/dist/login.d.mts +49 -0
- package/dist/login.d.mts.map +1 -0
- package/dist/login.mjs +71 -0
- package/dist/login.mjs.map +1 -0
- package/dist/migrate.d.mts +46 -0
- package/dist/migrate.d.mts.map +1 -0
- package/dist/migrate.mjs +58 -0
- package/dist/migrate.mjs.map +1 -0
- package/dist/migration-manifest.d.mts +39 -0
- package/dist/migration-manifest.d.mts.map +1 -0
- package/dist/migration-manifest.mjs +77 -0
- package/dist/migration-manifest.mjs.map +1 -0
- package/dist/migration-session-B4xHeU_a.d.mts +56 -0
- package/dist/migration-session-B4xHeU_a.d.mts.map +1 -0
- package/dist/migration-session.d.mts +2 -0
- package/dist/migration-session.mjs +204 -0
- package/dist/migration-session.mjs.map +1 -0
- package/dist/migration-snapshot-OM5jQN1-.mjs +69 -0
- package/dist/migration-snapshot-OM5jQN1-.mjs.map +1 -0
- package/dist/migration-state.d.mts +41 -0
- package/dist/migration-state.d.mts.map +1 -0
- package/dist/migration-state.mjs +155 -0
- package/dist/migration-state.mjs.map +1 -0
- package/dist/migrations-manifest.json +109 -0
- package/dist/pglite-preparation.d.mts +23 -0
- package/dist/pglite-preparation.d.mts.map +1 -0
- package/dist/pglite-preparation.mjs +77 -0
- package/dist/pglite-preparation.mjs.map +1 -0
- package/dist/pglite-store.d.mts +29 -0
- package/dist/pglite-store.d.mts.map +1 -0
- package/dist/pglite-store.mjs +117 -0
- package/dist/pglite-store.mjs.map +1 -0
- package/dist/relations.d.mts +2 -0
- package/dist/relations.mjs +307 -0
- package/dist/relations.mjs.map +1 -0
- package/dist/resource.d.mts +50 -0
- package/dist/resource.d.mts.map +1 -0
- package/dist/resource.mjs +123 -0
- package/dist/resource.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/schema.d.mts +2 -0
- package/dist/schema.mjs +495 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/slug.d.mts +28 -0
- package/dist/slug.d.mts.map +1 -0
- package/dist/slug.mjs +55 -0
- package/dist/slug.mjs.map +1 -0
- package/dist/text.d.mts +10 -0
- package/dist/text.d.mts.map +1 -0
- package/dist/text.mjs +11 -0
- package/dist/text.mjs.map +1 -0
- package/dist/uuid-CKMzlIND.d.mts +26 -0
- package/dist/uuid-CKMzlIND.d.mts.map +1 -0
- package/dist/uuid.d.mts +2 -0
- package/dist/uuid.mjs +28 -0
- package/dist/uuid.mjs.map +1 -0
- package/drizzle/20260622021748_init/migration.sql +25 -0
- package/drizzle/20260622021748_init/snapshot.json +246 -0
- package/drizzle/20260623162238_dear_felicia_hardy/migration.sql +5 -0
- package/drizzle/20260623162238_dear_felicia_hardy/snapshot.json +321 -0
- package/drizzle/20260624094817_lethal_sinister_six/migration.sql +2 -0
- package/drizzle/20260624094817_lethal_sinister_six/snapshot.json +347 -0
- package/drizzle/20260716000333_email_auth/migration.sql +20 -0
- package/drizzle/20260716000333_email_auth/snapshot.json +575 -0
- package/drizzle/20260723065002_chief_colleen_wing/migration.sql +2 -0
- package/drizzle/20260723065002_chief_colleen_wing/snapshot.json +595 -0
- package/drizzle/20260802205417_separate-instance-local-remote/migration.sql +26 -0
- package/drizzle/20260802205417_separate-instance-local-remote/snapshot.json +768 -0
- package/drizzle/20260804061119_instances-local-remote-constraint/migration.sql +7 -0
- package/drizzle/20260804061119_instances-local-remote-constraint/snapshot.json +843 -0
- package/drizzle/20260818080259_dark_night_thrasher/migration.sql +15 -0
- package/drizzle/20260818080259_dark_night_thrasher/snapshot.json +722 -0
- package/drizzle/20260821072150_merge_remote_actors/migration.sql +54 -0
- package/drizzle/20260821072150_merge_remote_actors/snapshot.json +1312 -0
- package/drizzle/20260906052949_rename_followees_to_following/migration.sql +2 -0
- package/drizzle/20260906052949_rename_followees_to_following/snapshot.json +1315 -0
- package/drizzle/20260908062446_rename_login_tokens_to_login_challenges/migration.sql +1 -0
- package/drizzle/20260908062446_rename_login_tokens_to_login_challenges/snapshot.json +1312 -0
- package/drizzle/20260908065945_simplify_login_challenges/migration.sql +7 -0
- package/drizzle/20260908065945_simplify_login_challenges/snapshot.json +1290 -0
- package/drizzle/20260915061356_tighten_slug_constraint/migration.sql +12 -0
- package/drizzle/20260915061356_tighten_slug_constraint/snapshot.json +1290 -0
- package/drizzle/20260915063339_widen_instance_host/migration.sql +1 -0
- package/drizzle/20260915063339_widen_instance_host/snapshot.json +1290 -0
- package/drizzle/20260916085902_add_objects_activities_and_resources/migration.sql +110 -0
- package/drizzle/20260916085902_add_objects_activities_and_resources/snapshot.json +2263 -0
- package/drizzle/20260917163517_order_local_outbox_items/migration.sql +22 -0
- package/drizzle/20260917163517_order_local_outbox_items/snapshot.json +2263 -0
- package/drizzle/20260918071839_add_activity_object_index/migration.sql +1 -0
- package/drizzle/20260918071839_add_activity_object_index/snapshot.json +2298 -0
- package/drizzle/20261006061745_add_activity_deliveries_and_keys/migration.sql +106 -0
- package/drizzle/20261006061745_add_activity_deliveries_and_keys/snapshot.json +3538 -0
- package/drizzle/20261006085045_snake_case_columns/migration.sql +42 -0
- package/drizzle/20261006085045_snake_case_columns/snapshot.json +3570 -0
- package/drizzle/20261006122653_local_actor_keys/migration.sql +11 -0
- package/drizzle/20261006122653_local_actor_keys/snapshot.json +3627 -0
- package/drizzle/20261010044954_link_activity_deliveries_to_activities/migration.sql +8 -0
- package/drizzle/20261010044954_link_activity_deliveries_to_activities/snapshot.json +3714 -0
- package/drizzle/20261010073134_check_inbound_activity_link/migration.sql +1 -0
- package/drizzle/20261010073134_check_inbound_activity_link/snapshot.json +3721 -0
- package/drizzle/20261010104304_record_object_activity/migration.sql +3 -0
- package/drizzle/20261010104304_record_object_activity/snapshot.json +3756 -0
- package/drizzle/20261010111648_record_delivery_snapshot/migration.sql +29 -0
- package/drizzle/20261010111648_record_delivery_snapshot/snapshot.json +3769 -0
- package/drizzle/20261011144453_record_object_snapshot/migration.sql +10 -0
- package/drizzle/20261011144453_record_object_snapshot/snapshot.json +3808 -0
- package/drizzle/20261011192718_record_actor_followers/migration.sql +1 -0
- package/drizzle/20261011192718_record_actor_followers/snapshot.json +3821 -0
- package/package.json +193 -3
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { lstat, readFile, readdir } from "node:fs/promises";
|
|
5
|
+
//#region src/migration-manifest.ts
|
|
6
|
+
/**
|
|
7
|
+
* Parse a migration directory's UTC timestamp, rejecting invalid dates.
|
|
8
|
+
* @returns The timestamp in milliseconds since the Unix epoch.
|
|
9
|
+
*/
|
|
10
|
+
function migrationTimestamp(name) {
|
|
11
|
+
if (!/^\d{14}_[a-zA-Z0-9_-]+$/u.test(name)) throw new Error("Invalid migration directory name.");
|
|
12
|
+
const stamp = name.slice(0, 14);
|
|
13
|
+
const iso = `${stamp.slice(0, 4)}-${stamp.slice(4, 6)}-${stamp.slice(6, 8)}T${stamp.slice(8, 10)}:${stamp.slice(10, 12)}:${stamp.slice(12, 14)}.000Z`;
|
|
14
|
+
const timestamp = Date.parse(iso);
|
|
15
|
+
if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString() !== iso) throw new Error("Invalid migration UTC timestamp.");
|
|
16
|
+
return timestamp;
|
|
17
|
+
}
|
|
18
|
+
function record(value) {
|
|
19
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validate the manifest format and strictly increasing migration timestamps.
|
|
23
|
+
* @returns A validated manifest, independent of the caller's object.
|
|
24
|
+
*/
|
|
25
|
+
function parseMigrationManifest(value) {
|
|
26
|
+
if (!record(value) || value.formatVersion !== 1 || Object.keys(value).sort().join(",") !== "formatVersion,migrations" || !Array.isArray(value.migrations)) throw new Error("Unsupported migration manifest format.");
|
|
27
|
+
let previous = -Infinity;
|
|
28
|
+
const migrations = [];
|
|
29
|
+
for (const entry of value.migrations) {
|
|
30
|
+
if (!record(entry) || Object.keys(entry).sort().join(",") !== "name,sha256" || typeof entry.name !== "string" || typeof entry.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(entry.sha256)) throw new Error("Invalid migration manifest entry.");
|
|
31
|
+
const timestamp = migrationTimestamp(entry.name);
|
|
32
|
+
if (timestamp <= previous) throw new Error("Migration timestamps must be unique and increasing.");
|
|
33
|
+
previous = timestamp;
|
|
34
|
+
migrations.push({
|
|
35
|
+
name: entry.name,
|
|
36
|
+
sha256: entry.sha256
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
formatVersion: 1,
|
|
41
|
+
migrations
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Ensure a newer manifest preserves every baseline entry as an exact prefix.
|
|
46
|
+
* @returns Nothing; throws if historical migrations were rewritten or removed.
|
|
47
|
+
*/
|
|
48
|
+
function assertMigrationManifestPrefix(baseline, current) {
|
|
49
|
+
const old = parseMigrationManifest(baseline);
|
|
50
|
+
const next = parseMigrationManifest(current);
|
|
51
|
+
if (old.migrations.some((entry, index) => next.migrations[index]?.name !== entry.name || next.migrations[index]?.sha256 !== entry.sha256)) throw new Error("Historical migration identities must remain unchanged.");
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Load and verify raw SQL identities without opening a database or executing SQL.
|
|
55
|
+
* @returns The validated manifest after all bundled SQL files match it.
|
|
56
|
+
*/
|
|
57
|
+
async function verifyMigrationManifest(paths = {}) {
|
|
58
|
+
const manifestPath = paths.manifestPath ?? fileURLToPath(new URL("./migrations-manifest.json", import.meta.url));
|
|
59
|
+
const migrationsFolder = paths.migrationsFolder ?? fileURLToPath(new URL("../drizzle/", import.meta.url));
|
|
60
|
+
const manifest = parseMigrationManifest(JSON.parse(await readFile(manifestPath, "utf8")));
|
|
61
|
+
const names = (await readdir(migrationsFolder, { withFileTypes: true })).map((entry) => {
|
|
62
|
+
if (!entry.isDirectory()) throw new Error("Unexpected entry in the migrations directory.");
|
|
63
|
+
migrationTimestamp(entry.name);
|
|
64
|
+
return entry.name;
|
|
65
|
+
}).sort();
|
|
66
|
+
if (names.length !== manifest.migrations.length || names.some((name, index) => name !== manifest.migrations[index]?.name)) throw new Error("Bundled migration directories do not match the manifest.");
|
|
67
|
+
await Promise.all(manifest.migrations.map(async (entry) => {
|
|
68
|
+
const sql = join(migrationsFolder, entry.name, "migration.sql");
|
|
69
|
+
if (!(await lstat(sql)).isFile()) throw new Error("Migration SQL must be a regular file.");
|
|
70
|
+
if (createHash("sha256").update(await readFile(sql)).digest("hex") !== entry.sha256) throw new Error(`Migration SQL checksum mismatch: ${entry.name}`);
|
|
71
|
+
}));
|
|
72
|
+
return manifest;
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
export { assertMigrationManifestPrefix, migrationTimestamp, parseMigrationManifest, verifyMigrationManifest };
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=migration-manifest.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-manifest.mjs","names":[],"sources":["../src/migration-manifest.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport { createHash } from \"node:crypto\";\nimport { lstat, readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Immutable identity of one raw SQL migration. */\nexport interface MigrationIdentity {\n readonly name: string;\n readonly sha256: string;\n}\n\n/** Versioned, chronological migration identities bundled with the package. */\nexport interface MigrationManifest {\n readonly formatVersion: 1;\n readonly migrations: readonly MigrationIdentity[];\n}\n\n/** Paths override the installed package defaults, for tooling and fixtures. */\nexport interface MigrationManifestPaths {\n readonly manifestPath?: string;\n readonly migrationsFolder?: string;\n}\n\n/**\n * Parse a migration directory's UTC timestamp, rejecting invalid dates.\n * @returns The timestamp in milliseconds since the Unix epoch.\n */\nexport function migrationTimestamp(name: string): number {\n if (!/^\\d{14}_[a-zA-Z0-9_-]+$/u.test(name)) {\n throw new Error(\"Invalid migration directory name.\");\n }\n const stamp = name.slice(0, 14);\n const iso = `${stamp.slice(0, 4)}-${stamp.slice(4, 6)}-${stamp.slice(6, 8)}T${stamp.slice(8, 10)}:${stamp.slice(10, 12)}:${stamp.slice(12, 14)}.000Z`;\n const timestamp = Date.parse(iso);\n if (\n !Number.isFinite(timestamp) ||\n new Date(timestamp).toISOString() !== iso\n ) {\n throw new Error(\"Invalid migration UTC timestamp.\");\n }\n return timestamp;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Validate the manifest format and strictly increasing migration timestamps.\n * @returns A validated manifest, independent of the caller's object.\n */\nexport function parseMigrationManifest(value: unknown): MigrationManifest {\n if (\n !record(value) ||\n value.formatVersion !== 1 ||\n Object.keys(value).sort().join(\",\") !== \"formatVersion,migrations\" ||\n !Array.isArray(value.migrations)\n ) {\n throw new Error(\"Unsupported migration manifest format.\");\n }\n let previous = -Infinity;\n const migrations: MigrationIdentity[] = [];\n for (const entry of value.migrations) {\n if (\n !record(entry) ||\n Object.keys(entry).sort().join(\",\") !== \"name,sha256\" ||\n typeof entry.name !== \"string\" ||\n typeof entry.sha256 !== \"string\" ||\n !/^[a-f0-9]{64}$/u.test(entry.sha256)\n ) {\n throw new Error(\"Invalid migration manifest entry.\");\n }\n const timestamp = migrationTimestamp(entry.name);\n if (timestamp <= previous) {\n throw new Error(\"Migration timestamps must be unique and increasing.\");\n }\n previous = timestamp;\n migrations.push({ name: entry.name, sha256: entry.sha256 });\n }\n return { formatVersion: 1, migrations };\n}\n\n/**\n * Ensure a newer manifest preserves every baseline entry as an exact prefix.\n * @returns Nothing; throws if historical migrations were rewritten or removed.\n */\nexport function assertMigrationManifestPrefix(\n baseline: MigrationManifest,\n current: MigrationManifest,\n): void {\n const old = parseMigrationManifest(baseline);\n const next = parseMigrationManifest(current);\n if (\n old.migrations.some(\n (entry, index) =>\n next.migrations[index]?.name !== entry.name ||\n next.migrations[index]?.sha256 !== entry.sha256,\n )\n ) {\n throw new Error(\"Historical migration identities must remain unchanged.\");\n }\n}\n\n/**\n * Load and verify raw SQL identities without opening a database or executing SQL.\n * @returns The validated manifest after all bundled SQL files match it.\n */\nexport async function verifyMigrationManifest(\n paths: MigrationManifestPaths = {},\n): Promise<MigrationManifest> {\n const manifestPath =\n paths.manifestPath ??\n fileURLToPath(new URL(\"./migrations-manifest.json\", import.meta.url));\n const migrationsFolder =\n paths.migrationsFolder ??\n fileURLToPath(new URL(\"../drizzle/\", import.meta.url));\n const manifest = parseMigrationManifest(\n JSON.parse(await readFile(manifestPath, \"utf8\")),\n );\n const directories = await readdir(migrationsFolder, { withFileTypes: true });\n const names = directories\n .map((entry) => {\n if (!entry.isDirectory()) {\n throw new Error(\"Unexpected entry in the migrations directory.\");\n }\n migrationTimestamp(entry.name);\n return entry.name;\n })\n .sort();\n if (\n names.length !== manifest.migrations.length ||\n names.some((name, index) => name !== manifest.migrations[index]?.name)\n ) {\n throw new Error(\"Bundled migration directories do not match the manifest.\");\n }\n await Promise.all(\n manifest.migrations.map(async (entry) => {\n const sql = join(migrationsFolder, entry.name, \"migration.sql\");\n if (!(await lstat(sql)).isFile()) {\n throw new Error(\"Migration SQL must be a regular file.\");\n }\n const hash = createHash(\"sha256\")\n .update(await readFile(sql))\n .digest(\"hex\");\n if (hash !== entry.sha256) {\n throw new Error(`Migration SQL checksum mismatch: ${entry.name}`);\n }\n }),\n );\n return manifest;\n}\n"],"mappings":";;;;;;;;;AA0CA,SAAgB,mBAAmB,MAAsB;CACvD,IAAI,CAAC,2BAA2B,KAAK,IAAI,GACvC,MAAM,IAAI,MAAM,mCAAmC;CAErD,MAAM,QAAQ,KAAK,MAAM,GAAG,EAAE;CAC9B,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,MAAM,GAAG,EAAE,EAAE,GAAG,MAAM,MAAM,IAAI,EAAE,EAAE,GAAG,MAAM,MAAM,IAAI,EAAE,EAAE;CAC/I,MAAM,YAAY,KAAK,MAAM,GAAG;CAChC,IACE,CAAC,OAAO,SAAS,SAAS,KAC1B,IAAI,KAAK,SAAS,CAAC,CAAC,YAAY,MAAM,KAEtC,MAAM,IAAI,MAAM,kCAAkC;CAEpD,OAAO;AACT;AAEA,SAAS,OAAO,O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J,MAAM,oBACN,cAAc,IAAI,IAAI,eAAe,OAAO,KAAK,GAAG,CAAC;CACvD,MAAM,WAAW,uBACf,KAAK,MAAM,MAAM,SAAS,cAAc,MAAM,CAAC,CACjD;CAEA,MAAM,SAAQ,MADY,QAAQ,kBAAkB,EAAE,eAAe,KAAK,CAAC,EAAA,CAExE,KAAK,UAAU;EACd,IAAI,CAAC,MAAM,YAAY,GACrB,MAAM,IAAI,MAAM,+CAA+C;EAEjE,mBAAmB,MAAM,IAAI;EAC7B,OAAO,MAAM;CACf,CAAC,CAAC,CACD,KAAK;CACR,IACE,MAAM,WAAW,SAAS,WAAW,UACrC,MAAM,MAAM,MAAM,UAAU,SAAS,SAAS,WAAW,MAAM,EAAE,IAAI,GAErE,MAAM,IAAI,MAAM,0DAA0D;CAE5E,MAAM,QAAQ,IACZ,SAAS,WAAW,IAAI,OAAO,UAAU;EACvC,MAAM,MAAM,KAAK,kBAAkB,MAAM,MAAM,eAAe;EAC9D,IAAI,EAAE,MAAM,MAAM,GAAG,EAAA,CAAG,OAAO,GAC7B,MAAM,IAAI,MAAM,uCAAuC;EAKzD,IAHa,WAAW,QAAQ,CAAC,CAC9B,OAAO,MAAM,SAAS,GAAG,CAAC,CAAC,CAC3B,OAAO,KACH,MAAM,MAAM,QACjB,MAAM,IAAI,MAAM,oCAAoC,MAAM,MAAM;CAEpE,CAAC,CACH;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { MigrationManifestPaths } from "./migration-manifest.mjs";
|
|
2
|
+
import { MigrationState } from "./migration-state.mjs";
|
|
3
|
+
import { Client, ClientConfig } from "pg";
|
|
4
|
+
//#region src/migration-preparation-error.d.ts
|
|
5
|
+
type MigrationPreparationCode = "invalid-options" | "invalid-migration-files" | "connection-failed" | "lock-timeout" | "aborted" | "inspection-failed" | "incompatible-history" | "migration-failed" | "cleanup-failed";
|
|
6
|
+
/** Sanitized failure information; raw database errors and credentials are omitted. */
|
|
7
|
+
declare class MigrationPreparationError extends Error {
|
|
8
|
+
readonly code: MigrationPreparationCode;
|
|
9
|
+
readonly state: MigrationState | undefined;
|
|
10
|
+
readonly cleanupFailed: boolean;
|
|
11
|
+
constructor(code: MigrationPreparationCode, state?: MigrationState, cleanupFailed?: boolean);
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/migration-session.d.ts
|
|
15
|
+
/** An exclusive, not-yet-connected client, created anew for each preparation. */
|
|
16
|
+
type MigrationClientFactory = () => Client;
|
|
17
|
+
type PostgresPreparationCredentials = {
|
|
18
|
+
readonly url: string;
|
|
19
|
+
readonly clientFactory?: never;
|
|
20
|
+
readonly connection?: never;
|
|
21
|
+
} | {
|
|
22
|
+
readonly clientFactory: MigrationClientFactory;
|
|
23
|
+
readonly url?: never;
|
|
24
|
+
readonly connection?: never;
|
|
25
|
+
} | {
|
|
26
|
+
readonly connection: Omit<ClientConfig, "connectionString"> & {
|
|
27
|
+
readonly connectionString?: never;
|
|
28
|
+
};
|
|
29
|
+
readonly url?: never;
|
|
30
|
+
readonly clientFactory?: never;
|
|
31
|
+
};
|
|
32
|
+
interface PreparePostgresOptions extends MigrationManifestPaths {
|
|
33
|
+
readonly credentials: PostgresPreparationCredentials;
|
|
34
|
+
readonly migrationsSchema?: string;
|
|
35
|
+
readonly migrationsTable?: string;
|
|
36
|
+
/** Deadline for connecting and acquiring the lock, not for applying SQL. */
|
|
37
|
+
readonly lockTimeoutMs?: number;
|
|
38
|
+
readonly signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Derive stable signed PostgreSQL advisory-lock keys for this history table.
|
|
42
|
+
* @returns Two int32 keys independent of process, connection and package version.
|
|
43
|
+
*/
|
|
44
|
+
declare function migrationLockKey(namespace?: string, table?: string): readonly [number, number];
|
|
45
|
+
/**
|
|
46
|
+
* Verify, lock, inspect and apply migrations on one owned PostgreSQL session.
|
|
47
|
+
* A supplied factory must return a fresh unconnected exclusive Client. The
|
|
48
|
+
* runner owns connect/end, never reconnects, and closes its transport on abort.
|
|
49
|
+
* PostgreSQL may retain an interrupted statement and its lock until it observes
|
|
50
|
+
* that disconnection; no other preparer can bypass that still-held lock.
|
|
51
|
+
* @returns Exact ready history after applying/metadata-upgrading if needed.
|
|
52
|
+
*/
|
|
53
|
+
declare function preparePostgresDatabase(options: PreparePostgresOptions): Promise<MigrationState>;
|
|
54
|
+
//#endregion
|
|
55
|
+
export { preparePostgresDatabase as a, migrationLockKey as i, PostgresPreparationCredentials as n, MigrationPreparationCode as o, PreparePostgresOptions as r, MigrationPreparationError as s, MigrationClientFactory as t };
|
|
56
|
+
//# sourceMappingURL=migration-session-B4xHeU_a.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-session-B4xHeU_a.d.mts","names":[],"sources":["../src/migration-preparation-error.ts","../src/migration-session.ts"],"mappings":";;;;KAiBY;;cA0BC,kCAAkC;WACpC,MAAM;WACN,OAAO;WACP;EAET,YACE,MAAM,0BACN,QAAQ,gBACR;;;;;KCZQ,+BAA+B;KAE/B;WAEG;WACA;WACA;;WAGA,eAAe;WACf;WACA;;WAGA,YAAY,KAAK;aACf;;WAEF;WACA;;UAGE,+BAA+B;WACrC,aAAa;WACb;WACA;;WAEA;WACA,SAAS;;;;;;iBAOJ,iBACd,oBACA;;;;;;;;;iBAkOoB,wBACpB,SAAS,yBACR,QAAQ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as preparePostgresDatabase, i as migrationLockKey, n as PostgresPreparationCredentials, o as MigrationPreparationCode, r as PreparePostgresOptions, s as MigrationPreparationError, t as MigrationClientFactory } from "./migration-session-B4xHeU_a.mjs";
|
|
2
|
+
export { MigrationClientFactory, type MigrationPreparationCode, MigrationPreparationError, PostgresPreparationCredentials, PreparePostgresOptions, migrationLockKey, preparePostgresDatabase };
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { verifyMigrationManifest } from "./migration-manifest.mjs";
|
|
2
|
+
import { inspectMigrationState } from "./migration-state.mjs";
|
|
3
|
+
import { n as MigrationPreparationError, t as withVerifiedMigrationSnapshot } from "./migration-snapshot-OM5jQN1-.mjs";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
6
|
+
import { getLogger } from "@logtape/logtape";
|
|
7
|
+
//#region src/migration-session.ts
|
|
8
|
+
/**
|
|
9
|
+
* Derive stable signed PostgreSQL advisory-lock keys for this history table.
|
|
10
|
+
* @returns Two int32 keys independent of process, connection and package version.
|
|
11
|
+
*/
|
|
12
|
+
function migrationLockKey(namespace = "drizzle", table = "__drizzle_migrations") {
|
|
13
|
+
const hash = createHash("sha256").update(JSON.stringify([
|
|
14
|
+
"org.drfed.migrations",
|
|
15
|
+
namespace,
|
|
16
|
+
table
|
|
17
|
+
])).digest();
|
|
18
|
+
return [hash.readInt32BE(0), hash.readInt32BE(4)];
|
|
19
|
+
}
|
|
20
|
+
const logger = getLogger([
|
|
21
|
+
"drfed",
|
|
22
|
+
"models",
|
|
23
|
+
"migration"
|
|
24
|
+
]);
|
|
25
|
+
var MigrationSession = class {
|
|
26
|
+
client;
|
|
27
|
+
#signal;
|
|
28
|
+
#waiting = new AbortController();
|
|
29
|
+
#deadline;
|
|
30
|
+
#abort;
|
|
31
|
+
#interrupted;
|
|
32
|
+
#connecting = false;
|
|
33
|
+
#key;
|
|
34
|
+
constructor(client, timeout, signal) {
|
|
35
|
+
this.client = client;
|
|
36
|
+
this.#signal = signal;
|
|
37
|
+
this.#abort = () => this.interrupt(new MigrationPreparationError("aborted"));
|
|
38
|
+
client.on("error", () => this.interrupt(new MigrationPreparationError("connection-failed")));
|
|
39
|
+
signal?.addEventListener("abort", this.#abort, { once: true });
|
|
40
|
+
this.#deadline = setTimeout(() => this.interrupt(new MigrationPreparationError("lock-timeout")), timeout);
|
|
41
|
+
}
|
|
42
|
+
get failure() {
|
|
43
|
+
return this.#interrupted;
|
|
44
|
+
}
|
|
45
|
+
interrupt(error) {
|
|
46
|
+
this.#interrupted ??= error;
|
|
47
|
+
this.#waiting.abort(this.#interrupted);
|
|
48
|
+
this.client.connection.stream.destroy(this.#connecting ? this.#interrupted : void 0);
|
|
49
|
+
}
|
|
50
|
+
check() {
|
|
51
|
+
if (this.#interrupted) throw new MigrationPreparationError(this.#interrupted.code, this.#interrupted.state);
|
|
52
|
+
}
|
|
53
|
+
async acquire(key) {
|
|
54
|
+
if (this.#signal?.aborted) this.#abort();
|
|
55
|
+
this.check();
|
|
56
|
+
this.#connecting = true;
|
|
57
|
+
await this.client.connect();
|
|
58
|
+
this.check();
|
|
59
|
+
while (!this.#key) {
|
|
60
|
+
const result = await this.client.query("SELECT pg_try_advisory_lock($1::integer, $2::integer) AS locked, pg_backend_pid() AS backend_pid", [...key]);
|
|
61
|
+
this.check();
|
|
62
|
+
if (result.rows[0]?.locked === true) {
|
|
63
|
+
this.#key = key;
|
|
64
|
+
logger.debug("Acquired migration lock on PostgreSQL backend {backendPid}.", { backendPid: result.rows[0].backend_pid });
|
|
65
|
+
} else await setTimeout$1(50, void 0, { signal: this.#waiting.signal });
|
|
66
|
+
}
|
|
67
|
+
clearTimeout(this.#deadline);
|
|
68
|
+
}
|
|
69
|
+
async #unlock() {
|
|
70
|
+
if (!this.#key || this.#interrupted || this.client.connection.stream.destroyed) return true;
|
|
71
|
+
try {
|
|
72
|
+
return (await this.client.query("SELECT pg_advisory_unlock($1::integer, $2::integer) AS unlocked", [...this.#key])).rows[0]?.unlocked === true;
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async close() {
|
|
78
|
+
clearTimeout(this.#deadline);
|
|
79
|
+
let cleanupFailed = false;
|
|
80
|
+
const deadline = setTimeout(() => {
|
|
81
|
+
cleanupFailed = true;
|
|
82
|
+
this.interrupt(new MigrationPreparationError("cleanup-failed"));
|
|
83
|
+
}, 5e3);
|
|
84
|
+
try {
|
|
85
|
+
cleanupFailed = !await this.#unlock();
|
|
86
|
+
if (cleanupFailed) this.interrupt(new MigrationPreparationError("cleanup-failed"));
|
|
87
|
+
await this.client.end();
|
|
88
|
+
} catch {
|
|
89
|
+
cleanupFailed = true;
|
|
90
|
+
this.interrupt(new MigrationPreparationError("cleanup-failed"));
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(deadline);
|
|
93
|
+
this.#signal?.removeEventListener("abort", this.#abort);
|
|
94
|
+
}
|
|
95
|
+
return cleanupFailed;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
async function inspectSession(session, options, manifest) {
|
|
99
|
+
try {
|
|
100
|
+
const state = await inspectMigrationState(session.client, {
|
|
101
|
+
migrationsSchema: options.migrationsSchema ?? "drizzle",
|
|
102
|
+
migrationsTable: options.migrationsTable ?? "__drizzle_migrations",
|
|
103
|
+
manifest
|
|
104
|
+
});
|
|
105
|
+
session.check();
|
|
106
|
+
return state;
|
|
107
|
+
} catch {
|
|
108
|
+
session.check();
|
|
109
|
+
throw new MigrationPreparationError("inspection-failed");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async function applySession(session, options, manifest) {
|
|
113
|
+
const state = await inspectSession(session, options, manifest);
|
|
114
|
+
if (![
|
|
115
|
+
"ready",
|
|
116
|
+
"pending",
|
|
117
|
+
"uninitialized",
|
|
118
|
+
"upgrade-required"
|
|
119
|
+
].includes(state.status)) throw new MigrationPreparationError("incompatible-history", state);
|
|
120
|
+
if (state.status !== "ready") {
|
|
121
|
+
try {
|
|
122
|
+
const [{ drizzle }, { migrate }] = await Promise.all([import("drizzle-orm/node-postgres"), import("drizzle-orm/node-postgres/migrator")]);
|
|
123
|
+
session.check();
|
|
124
|
+
await withVerifiedMigrationSnapshot(manifest, options, async (migrationsFolder) => {
|
|
125
|
+
session.check();
|
|
126
|
+
await migrate(drizzle({ client: session.client }), {
|
|
127
|
+
migrationsFolder,
|
|
128
|
+
migrationsSchema: options.migrationsSchema ?? "drizzle",
|
|
129
|
+
migrationsTable: options.migrationsTable ?? "__drizzle_migrations"
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
} catch (error) {
|
|
133
|
+
session.check();
|
|
134
|
+
if (error instanceof MigrationPreparationError) throw error;
|
|
135
|
+
throw new MigrationPreparationError("migration-failed");
|
|
136
|
+
}
|
|
137
|
+
session.check();
|
|
138
|
+
}
|
|
139
|
+
const result = await inspectSession(session, options, manifest);
|
|
140
|
+
if (result.status !== "ready") throw new MigrationPreparationError("incompatible-history", result);
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
function checkTransport(client) {
|
|
144
|
+
if (!client.connection?.stream || typeof client.connection.stream.destroy !== "function") throw new MigrationPreparationError("invalid-options");
|
|
145
|
+
}
|
|
146
|
+
function checkAbort(signal) {
|
|
147
|
+
if (signal?.aborted) throw new MigrationPreparationError("aborted");
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Verify, lock, inspect and apply migrations on one owned PostgreSQL session.
|
|
151
|
+
* A supplied factory must return a fresh unconnected exclusive Client. The
|
|
152
|
+
* runner owns connect/end, never reconnects, and closes its transport on abort.
|
|
153
|
+
* PostgreSQL may retain an interrupted statement and its lock until it observes
|
|
154
|
+
* that disconnection; no other preparer can bypass that still-held lock.
|
|
155
|
+
* @returns Exact ready history after applying/metadata-upgrading if needed.
|
|
156
|
+
*/
|
|
157
|
+
async function preparePostgresDatabase(options) {
|
|
158
|
+
const timeout = options.lockTimeoutMs ?? 3e4;
|
|
159
|
+
if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2147483647) throw new MigrationPreparationError("invalid-options");
|
|
160
|
+
checkAbort(options.signal);
|
|
161
|
+
let manifest;
|
|
162
|
+
try {
|
|
163
|
+
manifest = await verifyMigrationManifest(options);
|
|
164
|
+
} catch {
|
|
165
|
+
throw new MigrationPreparationError("invalid-migration-files");
|
|
166
|
+
}
|
|
167
|
+
checkAbort(options.signal);
|
|
168
|
+
let client;
|
|
169
|
+
try {
|
|
170
|
+
if ("clientFactory" in options.credentials) client = options.credentials.clientFactory();
|
|
171
|
+
else {
|
|
172
|
+
const { Client } = await import("pg");
|
|
173
|
+
checkAbort(options.signal);
|
|
174
|
+
client = new Client({
|
|
175
|
+
..."connection" in options.credentials ? options.credentials.connection : { connectionString: options.credentials.url },
|
|
176
|
+
connectionTimeoutMillis: timeout
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
checkAbort(options.signal);
|
|
181
|
+
throw new MigrationPreparationError("connection-failed");
|
|
182
|
+
}
|
|
183
|
+
checkTransport(client);
|
|
184
|
+
const session = new MigrationSession(client, timeout, options.signal);
|
|
185
|
+
let result;
|
|
186
|
+
let failure;
|
|
187
|
+
try {
|
|
188
|
+
await session.acquire(migrationLockKey(options.migrationsSchema, options.migrationsTable));
|
|
189
|
+
result = await applySession(session, options, manifest);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
failure = session.failure ?? (error instanceof MigrationPreparationError ? error : new MigrationPreparationError("connection-failed"));
|
|
192
|
+
} finally {
|
|
193
|
+
const cleanupFailed = await session.close();
|
|
194
|
+
failure ??= session.failure;
|
|
195
|
+
if (cleanupFailed) failure = new MigrationPreparationError(failure?.code ?? "cleanup-failed", failure?.state, true);
|
|
196
|
+
}
|
|
197
|
+
if (failure) throw new MigrationPreparationError(failure.code, failure.state, failure.cleanupFailed);
|
|
198
|
+
if (!result) throw new MigrationPreparationError("inspection-failed");
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
export { MigrationPreparationError, migrationLockKey, preparePostgresDatabase };
|
|
203
|
+
|
|
204
|
+
//# sourceMappingURL=migration-session.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-session.mjs","names":["#signal","#waiting","#deadline","#abort","#interrupted","#connecting","#key","delay","#unlock"],"sources":["../src/migration-session.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport { createHash } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { getLogger } from \"@logtape/logtape\";\nimport type { Client, ClientConfig } from \"pg\";\n\nimport {\n type MigrationManifest,\n type MigrationManifestPaths,\n verifyMigrationManifest,\n} from \"./migration-manifest.ts\";\nimport { MigrationPreparationError } from \"./migration-preparation-error.ts\";\nimport { withVerifiedMigrationSnapshot } from \"./migration-snapshot.ts\";\nimport {\n type MigrationState,\n inspectMigrationState,\n} from \"./migration-state.ts\";\n\nexport {\n MigrationPreparationError,\n type MigrationPreparationCode,\n} from \"./migration-preparation-error.ts\";\n\n/** An exclusive, not-yet-connected client, created anew for each preparation. */\nexport type MigrationClientFactory = () => Client;\n\nexport type PostgresPreparationCredentials =\n | {\n readonly url: string;\n readonly clientFactory?: never;\n readonly connection?: never;\n }\n | {\n readonly clientFactory: MigrationClientFactory;\n readonly url?: never;\n readonly connection?: never;\n }\n | {\n readonly connection: Omit<ClientConfig, \"connectionString\"> & {\n readonly connectionString?: never;\n };\n readonly url?: never;\n readonly clientFactory?: never;\n };\n\nexport interface PreparePostgresOptions extends MigrationManifestPaths {\n readonly credentials: PostgresPreparationCredentials;\n readonly migrationsSchema?: string;\n readonly migrationsTable?: string;\n /** Deadline for connecting and acquiring the lock, not for applying SQL. */\n readonly lockTimeoutMs?: number;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Derive stable signed PostgreSQL advisory-lock keys for this history table.\n * @returns Two int32 keys independent of process, connection and package version.\n */\nexport function migrationLockKey(\n namespace = \"drizzle\",\n table = \"__drizzle_migrations\",\n): readonly [number, number] {\n const hash = createHash(\"sha256\")\n .update(JSON.stringify([\"org.drfed.migrations\", namespace, table]))\n .digest();\n return [hash.readInt32BE(0), hash.readInt32BE(4)];\n}\n\nconst logger = getLogger([\"drfed\", \"models\", \"migration\"]);\n\nclass MigrationSession {\n readonly client: Client;\n readonly #signal: AbortSignal | undefined;\n readonly #waiting = new AbortController();\n readonly #deadline: ReturnType<typeof setTimeout>;\n readonly #abort: () => void;\n #interrupted: MigrationPreparationError | undefined;\n #connecting = false;\n #key: readonly [number, number] | undefined;\n\n constructor(client: Client, timeout: number, signal?: AbortSignal) {\n this.client = client;\n this.#signal = signal;\n this.#abort = () =>\n this.interrupt(new MigrationPreparationError(\"aborted\"));\n client.on(\"error\", () =>\n this.interrupt(new MigrationPreparationError(\"connection-failed\")),\n );\n signal?.addEventListener(\"abort\", this.#abort, { once: true });\n this.#deadline = setTimeout(\n () => this.interrupt(new MigrationPreparationError(\"lock-timeout\")),\n timeout,\n );\n }\n\n get failure(): MigrationPreparationError | undefined {\n return this.#interrupted;\n }\n\n interrupt(error: MigrationPreparationError): void {\n this.#interrupted ??= error;\n this.#waiting.abort(this.#interrupted);\n // Public pg Connection.stream is also the active TLS stream after upgrade.\n // During handshake, an error is essential to settle connect()'s promise.\n // Before connect(), no stream error listeners exist, so destroy without error.\n this.client.connection.stream.destroy(\n this.#connecting ? this.#interrupted : undefined,\n );\n }\n\n check(): void {\n if (this.#interrupted) {\n throw new MigrationPreparationError(\n this.#interrupted.code,\n this.#interrupted.state,\n );\n }\n }\n\n async acquire(key: readonly [number, number]): Promise<void> {\n if (this.#signal?.aborted) {\n this.#abort();\n }\n this.check();\n this.#connecting = true;\n await this.client.connect();\n this.check();\n while (!this.#key) {\n // Acquisition is session-local and reentrant; attempts must be sequential.\n // oxlint-disable-next-line no-await-in-loop\n const result = await this.client.query<{\n locked: boolean;\n backend_pid: number;\n }>(\n \"SELECT pg_try_advisory_lock($1::integer, $2::integer) AS locked, pg_backend_pid() AS backend_pid\",\n [...key],\n );\n this.check();\n if (result.rows[0]?.locked === true) {\n this.#key = key;\n logger.debug(\n \"Acquired migration lock on PostgreSQL backend {backendPid}.\",\n { backendPid: result.rows[0].backend_pid },\n );\n } else {\n // oxlint-disable-next-line no-await-in-loop\n await delay(50, undefined, { signal: this.#waiting.signal });\n }\n }\n clearTimeout(this.#deadline);\n }\n\n async #unlock(): Promise<boolean> {\n if (\n !this.#key ||\n this.#interrupted ||\n this.client.connection.stream.destroyed\n ) {\n return true;\n }\n try {\n const result = await this.client.query<{ unlocked: boolean }>(\n \"SELECT pg_advisory_unlock($1::integer, $2::integer) AS unlocked\",\n [...this.#key],\n );\n return result.rows[0]?.unlocked === true;\n } catch {\n return false;\n }\n }\n\n async close(): Promise<boolean> {\n clearTimeout(this.#deadline);\n let cleanupFailed = false;\n const deadline = setTimeout(() => {\n cleanupFailed = true;\n this.interrupt(new MigrationPreparationError(\"cleanup-failed\"));\n }, 5_000);\n try {\n cleanupFailed = !(await this.#unlock());\n if (cleanupFailed) {\n this.interrupt(new MigrationPreparationError(\"cleanup-failed\"));\n }\n await this.client.end();\n } catch {\n cleanupFailed = true;\n this.interrupt(new MigrationPreparationError(\"cleanup-failed\"));\n } finally {\n clearTimeout(deadline);\n this.#signal?.removeEventListener(\"abort\", this.#abort);\n }\n return cleanupFailed;\n }\n}\n\nasync function inspectSession(\n session: MigrationSession,\n options: PreparePostgresOptions,\n manifest: MigrationManifest,\n): Promise<MigrationState> {\n try {\n const state = await inspectMigrationState(session.client, {\n migrationsSchema: options.migrationsSchema ?? \"drizzle\",\n migrationsTable: options.migrationsTable ?? \"__drizzle_migrations\",\n manifest,\n });\n session.check();\n return state;\n } catch {\n session.check();\n throw new MigrationPreparationError(\"inspection-failed\");\n }\n}\n\nasync function applySession(\n session: MigrationSession,\n options: PreparePostgresOptions,\n manifest: MigrationManifest,\n): Promise<MigrationState> {\n const state = await inspectSession(session, options, manifest);\n if (\n ![\"ready\", \"pending\", \"uninitialized\", \"upgrade-required\"].includes(\n state.status,\n )\n ) {\n throw new MigrationPreparationError(\"incompatible-history\", state);\n }\n if (state.status !== \"ready\") {\n try {\n const [{ drizzle }, { migrate }] = await Promise.all([\n import(\"drizzle-orm/node-postgres\"),\n import(\"drizzle-orm/node-postgres/migrator\"),\n ]);\n session.check();\n await withVerifiedMigrationSnapshot(\n manifest,\n options,\n async (migrationsFolder) => {\n session.check();\n await migrate(drizzle({ client: session.client }), {\n migrationsFolder,\n migrationsSchema: options.migrationsSchema ?? \"drizzle\",\n migrationsTable: options.migrationsTable ?? \"__drizzle_migrations\",\n });\n },\n );\n } catch (error) {\n session.check();\n if (error instanceof MigrationPreparationError) {\n throw error;\n }\n throw new MigrationPreparationError(\"migration-failed\");\n }\n session.check();\n }\n const result = await inspectSession(session, options, manifest);\n if (result.status !== \"ready\") {\n throw new MigrationPreparationError(\"incompatible-history\", result);\n }\n return result;\n}\n\nfunction checkTransport(client: Client): void {\n if (\n !client.connection?.stream ||\n typeof client.connection.stream.destroy !== \"function\"\n ) {\n // The factory contract guarantees no connection needs closing at this point.\n throw new MigrationPreparationError(\"invalid-options\");\n }\n}\n\nfunction checkAbort(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw new MigrationPreparationError(\"aborted\");\n }\n}\n\n/**\n * Verify, lock, inspect and apply migrations on one owned PostgreSQL session.\n * A supplied factory must return a fresh unconnected exclusive Client. The\n * runner owns connect/end, never reconnects, and closes its transport on abort.\n * PostgreSQL may retain an interrupted statement and its lock until it observes\n * that disconnection; no other preparer can bypass that still-held lock.\n * @returns Exact ready history after applying/metadata-upgrading if needed.\n */\nexport async function preparePostgresDatabase(\n options: PreparePostgresOptions,\n): Promise<MigrationState> {\n const timeout = options.lockTimeoutMs ?? 30_000;\n if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647) {\n throw new MigrationPreparationError(\"invalid-options\");\n }\n checkAbort(options.signal);\n let manifest: MigrationManifest;\n try {\n manifest = await verifyMigrationManifest(options);\n } catch {\n throw new MigrationPreparationError(\"invalid-migration-files\");\n }\n checkAbort(options.signal);\n let client: Client;\n try {\n if (\"clientFactory\" in options.credentials) {\n client = options.credentials.clientFactory();\n } else {\n const { Client } = await import(\"pg\");\n checkAbort(options.signal);\n client = new Client({\n ...(\"connection\" in options.credentials\n ? options.credentials.connection\n : { connectionString: options.credentials.url }),\n connectionTimeoutMillis: timeout,\n });\n }\n } catch {\n checkAbort(options.signal);\n throw new MigrationPreparationError(\"connection-failed\");\n }\n checkTransport(client);\n const session = new MigrationSession(client, timeout, options.signal);\n let result: MigrationState | undefined;\n let failure: MigrationPreparationError | undefined;\n try {\n await session.acquire(\n migrationLockKey(options.migrationsSchema, options.migrationsTable),\n );\n result = await applySession(session, options, manifest);\n } catch (error) {\n failure =\n session.failure ??\n (error instanceof MigrationPreparationError\n ? error\n : new MigrationPreparationError(\"connection-failed\"));\n } finally {\n const cleanupFailed = await session.close();\n failure ??= session.failure;\n if (cleanupFailed) {\n failure = new MigrationPreparationError(\n failure?.code ?? \"cleanup-failed\",\n failure?.state,\n true,\n );\n }\n }\n if (failure) {\n throw new MigrationPreparationError(\n failure.code,\n failure.state,\n failure.cleanupFailed,\n );\n }\n if (!result) {\n throw new MigrationPreparationError(\"inspection-failed\");\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;AAyEA,SAAgB,iBACd,YAAY,WACZ,QAAQ,wBACmB;CAC3B,MAAM,OAAO,WAAW,QAAQ,CAAC,CAC9B,OAAO,KAAK,UAAU;EAAC;EAAwB;EAAW;CAAK,CAAC,CAAC,CAAC,CAClE,OAAO;CACV,OAAO,CAAC,KAAK,YAAY,CAAC,GAAG,KAAK,YAAY,CAAC,CAAC;AAClD;AAEA,MAAM,SAAS,UAAU;CAAC;CAAS;CAAU;AAAW,CAAC;AAEzD,IAAM,mBAAN,MAAuB;CACrB;CACA;CACA,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,SAAS,QAAQ,YAAY,cAAc;OACtC;GACL,MAAM,EAAE,WAAW,MAAM,OAAO;GAChC,WAAW,QAAQ,MAAM;GACzB,SAAS,IAAI,OAAO;IAClB,GAAI,gBAAgB,QAAQ,cACxB,QAAQ,YAAY,aACpB,EAAE,kBAAkB,QAAQ,YAAY,IAAI;IAChD,yBAAyB;GAC3B,CAAC;EACH;CACF,QAAQ;EACN,WAAW,QAAQ,MAAM;EACzB,MAAM,IAAI,0BAA0B,mBAAmB;CACzD;CACA,eAAe,MAAM;CACrB,MAAM,UAAU,IAAI,iBAAiB,QAAQ,SAAS,QAAQ,MAAM;CACpE,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,MAAM,QAAQ,QACZ,iBAAiB,QAAQ,kBAAkB,QAAQ,eAAe,CACpE;EACA,SAAS,MAAM,aAAa,SAAS,SAAS,QAAQ;CACxD,SAAS,OAAO;EACd,UACE,QAAQ,YACP,iBAAiB,4BACd,QACA,IAAI,0BAA0B,mBAAmB;CACzD,UAAU;EACR,MAAM,gBAAgB,MAAM,QAAQ,MAAM;EAC1C,YAAY,QAAQ;EACpB,IAAI,eACF,UAAU,IAAI,0BACZ,SAAS,QAAQ,kBACjB,SAAS,OACT,IACF;CAEJ;CACA,IAAI,SACF,MAAM,IAAI,0BACR,QAAQ,MACR,QAAQ,OACR,QAAQ,aACV;CAEF,IAAI,CAAC,QACH,MAAM,IAAI,0BAA0B,mBAAmB;CAEzD,OAAO;AACT"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
//#region src/migration-preparation-error.ts
|
|
7
|
+
const explanations = {
|
|
8
|
+
"invalid-options": "Invalid migration preparation options.",
|
|
9
|
+
"invalid-migration-files": "Could not verify the bundled migration files.",
|
|
10
|
+
"connection-failed": "Could not maintain the migration database connection.",
|
|
11
|
+
"lock-timeout": "Timed out waiting for the migration session lock.",
|
|
12
|
+
aborted: "Migration preparation was aborted.",
|
|
13
|
+
"inspection-failed": "Could not inspect migration history; check database permissions.",
|
|
14
|
+
"incompatible-history": "Database migration history is incompatible with this package.",
|
|
15
|
+
"migration-failed": "Could not apply database migrations.",
|
|
16
|
+
"cleanup-failed": "Could not cleanly release the migration database session."
|
|
17
|
+
};
|
|
18
|
+
/** Sanitized failure information; raw database errors and credentials are omitted. */
|
|
19
|
+
var MigrationPreparationError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
state;
|
|
22
|
+
cleanupFailed;
|
|
23
|
+
constructor(code, state, cleanupFailed = false) {
|
|
24
|
+
super(explanations[code]);
|
|
25
|
+
this.name = "MigrationPreparationError";
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.state = state;
|
|
28
|
+
this.cleanupFailed = cleanupFailed;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/migration-snapshot.ts
|
|
33
|
+
async function withVerifiedMigrationSnapshot(manifest, options, run) {
|
|
34
|
+
const original = options.migrationsFolder ?? fileURLToPath(new URL("../drizzle/", import.meta.url));
|
|
35
|
+
let files;
|
|
36
|
+
try {
|
|
37
|
+
files = await Promise.all(manifest.migrations.map(async (entry) => {
|
|
38
|
+
const sql = await readFile(join(original, entry.name, "migration.sql"));
|
|
39
|
+
if (createHash("sha256").update(sql).digest("hex") !== entry.sha256) throw new MigrationPreparationError("invalid-migration-files");
|
|
40
|
+
return {
|
|
41
|
+
name: entry.name,
|
|
42
|
+
sql
|
|
43
|
+
};
|
|
44
|
+
}));
|
|
45
|
+
} catch {
|
|
46
|
+
throw new MigrationPreparationError("invalid-migration-files");
|
|
47
|
+
}
|
|
48
|
+
const folder = await mkdtemp(join(tmpdir(), "drfed-migration-"));
|
|
49
|
+
try {
|
|
50
|
+
await Promise.all(files.map(async ({ name, sql }) => {
|
|
51
|
+
const directory = join(folder, name);
|
|
52
|
+
await mkdir(directory);
|
|
53
|
+
await writeFile(join(directory, "migration.sql"), sql, {
|
|
54
|
+
flag: "wx",
|
|
55
|
+
mode: 384
|
|
56
|
+
});
|
|
57
|
+
}));
|
|
58
|
+
return await run(folder);
|
|
59
|
+
} finally {
|
|
60
|
+
await rm(folder, {
|
|
61
|
+
recursive: true,
|
|
62
|
+
force: true
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { MigrationPreparationError as n, withVerifiedMigrationSnapshot as t };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=migration-snapshot-OM5jQN1-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-snapshot-OM5jQN1-.mjs","names":[],"sources":["../src/migration-preparation-error.ts","../src/migration-snapshot.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport type { MigrationState } from \"./migration-state.ts\";\n\nexport type MigrationPreparationCode =\n | \"invalid-options\"\n | \"invalid-migration-files\"\n | \"connection-failed\"\n | \"lock-timeout\"\n | \"aborted\"\n | \"inspection-failed\"\n | \"incompatible-history\"\n | \"migration-failed\"\n | \"cleanup-failed\";\n\nconst explanations: Record<MigrationPreparationCode, string> = {\n \"invalid-options\": \"Invalid migration preparation options.\",\n \"invalid-migration-files\": \"Could not verify the bundled migration files.\",\n \"connection-failed\": \"Could not maintain the migration database connection.\",\n \"lock-timeout\": \"Timed out waiting for the migration session lock.\",\n aborted: \"Migration preparation was aborted.\",\n \"inspection-failed\":\n \"Could not inspect migration history; check database permissions.\",\n \"incompatible-history\":\n \"Database migration history is incompatible with this package.\",\n \"migration-failed\": \"Could not apply database migrations.\",\n \"cleanup-failed\": \"Could not cleanly release the migration database session.\",\n};\n\n/** Sanitized failure information; raw database errors and credentials are omitted. */\nexport class MigrationPreparationError extends Error {\n readonly code: MigrationPreparationCode;\n readonly state: MigrationState | undefined;\n readonly cleanupFailed: boolean;\n\n constructor(\n code: MigrationPreparationCode,\n state?: MigrationState,\n cleanupFailed = false,\n ) {\n super(explanations[code]);\n this.name = \"MigrationPreparationError\";\n this.code = code;\n this.state = state;\n this.cleanupFailed = cleanupFailed;\n }\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport { createHash } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type {\n MigrationManifest,\n MigrationManifestPaths,\n} from \"./migration-manifest.ts\";\nimport { MigrationPreparationError } from \"./migration-preparation-error.ts\";\n\n// Drizzle rereads paths internally. Give it a private snapshot of exact verified\n// bytes, so an installation changing while the session waits cannot supply SQL.\nexport async function withVerifiedMigrationSnapshot<T>(\n manifest: MigrationManifest,\n options: MigrationManifestPaths,\n run: (folder: string) => Promise<T>,\n): Promise<T> {\n const original =\n options.migrationsFolder ??\n fileURLToPath(new URL(\"../drizzle/\", import.meta.url));\n let files: { name: string; sql: Buffer }[];\n try {\n files = await Promise.all(\n manifest.migrations.map(async (entry) => {\n const sql = await readFile(join(original, entry.name, \"migration.sql\"));\n if (createHash(\"sha256\").update(sql).digest(\"hex\") !== entry.sha256) {\n throw new MigrationPreparationError(\"invalid-migration-files\");\n }\n return { name: entry.name, sql };\n }),\n );\n } catch {\n throw new MigrationPreparationError(\"invalid-migration-files\");\n }\n const folder = await mkdtemp(join(tmpdir(), \"drfed-migration-\"));\n try {\n await Promise.all(\n files.map(async ({ name, sql }) => {\n const directory = join(folder, name);\n await mkdir(directory);\n await writeFile(join(directory, \"migration.sql\"), sql, {\n flag: \"wx\",\n mode: 0o600,\n });\n }),\n );\n return await run(folder);\n } finally {\n await rm(folder, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;AA4BA,MAAM,eAAyD;CAC7D,mBAAmB;CACnB,2BAA2B;CAC3B,qBAAqB;CACrB,gBAAgB;CAChB,SAAS;CACT,qBACE;CACF,wBACE;CACF,oBAAoB;CACpB,kBAAkB;AACpB;;AAGA,IAAa,4BAAb,cAA+C,MAAM;CACnD;CACA;CACA;CAEA,YACE,MACA,OACA,gBAAgB,OAChB;EACA,MAAM,aAAa,KAAK;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,gBAAgB;CACvB;AACF;;;AC9BA,eAAsB,8BACpB,UACA,SACA,KACY;CACZ,MAAM,WACJ,QAAQ,oBACR,cAAc,IAAI,IAAI,eAAe,OAAO,KAAK,GAAG,CAAC;CACvD,IAAI;CACJ,IAAI;EACF,QAAQ,MAAM,QAAQ,IACpB,SAAS,WAAW,IAAI,OAAO,UAAU;GACvC,MAAM,MAAM,MAAM,SAAS,KAAK,UAAU,MAAM,MAAM,eAAe,CAAC;GACtE,IAAI,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,MAAM,MAAM,QAC3D,MAAM,IAAI,0BAA0B,yBAAyB;GAE/D,OAAO;IAAE,MAAM,MAAM;IAAM;GAAI;EACjC,CAAC,CACH;CACF,QAAQ;EACN,MAAM,IAAI,0BAA0B,yBAAyB;CAC/D;CACA,MAAM,SAAS,MAAM,QAAQ,KAAK,OAAO,GAAG,kBAAkB,CAAC;CAC/D,IAAI;EACF,MAAM,QAAQ,IACZ,MAAM,IAAI,OAAO,EAAE,MAAM,UAAU;GACjC,MAAM,YAAY,KAAK,QAAQ,IAAI;GACnC,MAAM,MAAM,SAAS;GACrB,MAAM,UAAU,KAAK,WAAW,eAAe,GAAG,KAAK;IACrD,MAAM;IACN,MAAM;GACR,CAAC;EACH,CAAC,CACH;EACA,OAAO,MAAM,IAAI,MAAM;CACzB,UAAU;EACR,MAAM,GAAG,QAAQ;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACnD;AACF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { MigrationIdentity, MigrationManifest } from "./migration-manifest.mjs";
|
|
2
|
+
//#region src/migration-state.d.ts
|
|
3
|
+
/** A query-only client; the caller owns its connection and lifetime. */
|
|
4
|
+
interface MigrationQueryClient {
|
|
5
|
+
query<Row extends Record<string, unknown>>(sql: string, parameters?: unknown[]): Promise<{
|
|
6
|
+
rows: Row[];
|
|
7
|
+
}>;
|
|
8
|
+
}
|
|
9
|
+
type MigrationHistoryFormat = "current" | "legacy";
|
|
10
|
+
type MigrationStatus = "ready" | "pending" | "uninitialized" | "upgrade-required" | "modified" | "newer" | "diverged" | "untracked-schema" | "unsupported-format";
|
|
11
|
+
/** Only ready permits startup without applying or upgrading migrations. */
|
|
12
|
+
interface MigrationState {
|
|
13
|
+
readonly status: MigrationStatus;
|
|
14
|
+
readonly format: MigrationHistoryFormat | null;
|
|
15
|
+
readonly applied: number;
|
|
16
|
+
readonly pending: readonly MigrationIdentity[];
|
|
17
|
+
}
|
|
18
|
+
interface InspectMigrationStateOptions {
|
|
19
|
+
readonly migrationsSchema?: string;
|
|
20
|
+
readonly migrationsTable?: string;
|
|
21
|
+
/** A trusted explicit identity set; otherwise verify the installed SQL. */
|
|
22
|
+
readonly manifest?: MigrationManifest;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Compare ordered raw history rows with the immutable manifest, without SQL.
|
|
26
|
+
* Legacy and metadata-upgraded legacy dates may retain generation milliseconds.
|
|
27
|
+
* Both second and hash
|
|
28
|
+
* must match the corresponding prefix entry before metadata can be upgraded.
|
|
29
|
+
* @returns The compatibility state; invalid histories never list pending SQL.
|
|
30
|
+
*/
|
|
31
|
+
declare function classifyMigrationHistory(manifest: MigrationManifest, rows: readonly Record<string, unknown>[], format: MigrationHistoryFormat): MigrationState;
|
|
32
|
+
/**
|
|
33
|
+
* Inspect migration catalogs and history using SELECT statements only.
|
|
34
|
+
* Missing/empty history with DrFed tables fails closed; metadata and permission
|
|
35
|
+
* errors propagate instead of being mistaken for an empty database.
|
|
36
|
+
* @returns A compatibility state without modifying the database or the client.
|
|
37
|
+
*/
|
|
38
|
+
declare function inspectMigrationState(client: MigrationQueryClient, options?: InspectMigrationStateOptions): Promise<MigrationState>;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { InspectMigrationStateOptions, MigrationHistoryFormat, MigrationQueryClient, MigrationState, MigrationStatus, classifyMigrationHistory, inspectMigrationState };
|
|
41
|
+
//# sourceMappingURL=migration-state.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-state.d.mts","names":[],"sources":["../src/migration-state.ts"],"mappings":";;;UA8BiB;EACf,MAAM,YAAY,yBAChB,aACA,yBACC;IAAU,MAAM;;;KAGT;KACA;;UAYK;WACN,QAAQ;WACR,QAAQ;WACR;WACA,kBAAkB;;UAGZ;WACN;WACA;;WAEA,WAAW;;;;;;;;;iBAqDN,yBACd,UAAU,mBACV,eAAe,2BACf,QAAQ,yBACP;;;;;;;iBA6GmB,sBACpB,QAAQ,sBACR,UAAS,+BACR,QAAQ"}
|