@nauth-toolkit/database-typeorm-postgres 0.3.2 → 0.4.0
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/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -1
- package/dist/index.js.map +1 -1
- package/dist/utils/migration-lock.d.ts +52 -0
- package/dist/utils/migration-lock.d.ts.map +1 -0
- package/dist/utils/migration-lock.js +109 -0
- package/dist/utils/migration-lock.js.map +1 -0
- package/dist/utils/run-migrations.d.ts +6 -0
- package/dist/utils/run-migrations.d.ts.map +1 -1
- package/dist/utils/run-migrations.js +64 -12
- package/dist/utils/run-migrations.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -14,4 +14,16 @@ export * from './entities';
|
|
|
14
14
|
* Consumers should not need to call this directly.
|
|
15
15
|
*/
|
|
16
16
|
export { runNAuthMigrations } from './utils/run-migrations';
|
|
17
|
+
/**
|
|
18
|
+
* Migration lock helpers (PostgreSQL).
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* Exported so consumers applying migrations out-of-band (an ECS one-off task, a
|
|
22
|
+
* Kubernetes Job) can take the same lock nauth-toolkit uses and stay mutually
|
|
23
|
+
* exclusive with any instance that still boots with `migrations.autoRun` enabled.
|
|
24
|
+
* The lock is a session-scoped advisory lock (`pg_try_advisory_lock`) derived from the
|
|
25
|
+
* migrations table name.
|
|
26
|
+
*/
|
|
27
|
+
export { acquireMigrationLock, computeAdvisoryLockKey, MIGRATION_LOCK_TIMEOUT_MS } from './utils/migration-lock';
|
|
28
|
+
export type { MigrationLockHandle } from './utils/migration-lock';
|
|
17
29
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,gBAAgB,EAAE,gCAAgC,EAAE,MAAM,YAAY,CAAC;AAGhF,cAAc,YAAY,CAAC;AAM3B;;;;;;GAMG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,gBAAgB,EAAE,gCAAgC,EAAE,MAAM,YAAY,CAAC;AAGhF,cAAc,YAAY,CAAC;AAM3B;;;;;;GAMG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;;;;;;;GASG;AACH,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACjH,YAAY,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
20
20
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
21
21
|
};
|
|
22
22
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
-
exports.runNAuthMigrations = exports.getNAuthTransientStorageEntities = exports.getNAuthEntities = void 0;
|
|
23
|
+
exports.MIGRATION_LOCK_TIMEOUT_MS = exports.computeAdvisoryLockKey = exports.acquireMigrationLock = exports.runNAuthMigrations = exports.getNAuthTransientStorageEntities = exports.getNAuthEntities = void 0;
|
|
24
24
|
// Export helper function for getting entities (preferred)
|
|
25
25
|
var entities_1 = require("./entities");
|
|
26
26
|
Object.defineProperty(exports, "getNAuthEntities", { enumerable: true, get: function () { return entities_1.getNAuthEntities; } });
|
|
@@ -39,4 +39,18 @@ __exportStar(require("./entities"), exports);
|
|
|
39
39
|
*/
|
|
40
40
|
var run_migrations_1 = require("./utils/run-migrations");
|
|
41
41
|
Object.defineProperty(exports, "runNAuthMigrations", { enumerable: true, get: function () { return run_migrations_1.runNAuthMigrations; } });
|
|
42
|
+
/**
|
|
43
|
+
* Migration lock helpers (PostgreSQL).
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* Exported so consumers applying migrations out-of-band (an ECS one-off task, a
|
|
47
|
+
* Kubernetes Job) can take the same lock nauth-toolkit uses and stay mutually
|
|
48
|
+
* exclusive with any instance that still boots with `migrations.autoRun` enabled.
|
|
49
|
+
* The lock is a session-scoped advisory lock (`pg_try_advisory_lock`) derived from the
|
|
50
|
+
* migrations table name.
|
|
51
|
+
*/
|
|
52
|
+
var migration_lock_1 = require("./utils/migration-lock");
|
|
53
|
+
Object.defineProperty(exports, "acquireMigrationLock", { enumerable: true, get: function () { return migration_lock_1.acquireMigrationLock; } });
|
|
54
|
+
Object.defineProperty(exports, "computeAdvisoryLockKey", { enumerable: true, get: function () { return migration_lock_1.computeAdvisoryLockKey; } });
|
|
55
|
+
Object.defineProperty(exports, "MIGRATION_LOCK_TIMEOUT_MS", { enumerable: true, get: function () { return migration_lock_1.MIGRATION_LOCK_TIMEOUT_MS; } });
|
|
42
56
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;;AAEH,0DAA0D;AAC1D,uCAAgF;AAAvE,4GAAA,gBAAgB,OAAA;AAAE,4HAAA,gCAAgC,OAAA;AAE3D,4EAA4E;AAC5E,6CAA2B;AAE3B,+EAA+E;AAC/E,aAAa;AACb,+EAA+E;AAE/E;;;;;;GAMG;AACH,yDAA4D;AAAnD,oHAAA,kBAAkB,OAAA"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;;AAEH,0DAA0D;AAC1D,uCAAgF;AAAvE,4GAAA,gBAAgB,OAAA;AAAE,4HAAA,gCAAgC,OAAA;AAE3D,4EAA4E;AAC5E,6CAA2B;AAE3B,+EAA+E;AAC/E,aAAa;AACb,+EAA+E;AAE/E;;;;;;GAMG;AACH,yDAA4D;AAAnD,oHAAA,kBAAkB,OAAA;AAE3B;;;;;;;;;GASG;AACH,yDAAiH;AAAxG,sHAAA,oBAAoB,OAAA;AAAE,wHAAA,sBAAsB,OAAA;AAAE,2HAAA,yBAAyB,OAAA"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { DataSource } from 'typeorm';
|
|
2
|
+
import type { NAuthLogger } from '@nauth-toolkit/core';
|
|
3
|
+
/**
|
|
4
|
+
* How long to wait for another instance to finish migrating before giving up.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Deliberately not configurable. Long enough to cover a realistic migration on a large
|
|
8
|
+
* table, short enough that a genuinely stuck deploy fails with a clear error instead of
|
|
9
|
+
* hanging forever.
|
|
10
|
+
*/
|
|
11
|
+
export declare const MIGRATION_LOCK_TIMEOUT_MS = 300000;
|
|
12
|
+
/**
|
|
13
|
+
* A held PostgreSQL advisory lock.
|
|
14
|
+
*/
|
|
15
|
+
export interface MigrationLockHandle {
|
|
16
|
+
/**
|
|
17
|
+
* Release the advisory lock and return its connection to the pool.
|
|
18
|
+
*
|
|
19
|
+
* Safe to call more than once.
|
|
20
|
+
*/
|
|
21
|
+
release(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Derive a stable 64-bit PostgreSQL advisory lock key from the migrations table name.
|
|
25
|
+
*
|
|
26
|
+
* @remarks
|
|
27
|
+
* Deriving from the table name means two applications sharing one database but using
|
|
28
|
+
* different `tablePrefix` values migrate independently instead of blocking each other.
|
|
29
|
+
*
|
|
30
|
+
* @param migrationsTableName - Name of the nauth migrations table
|
|
31
|
+
* @returns Signed 64-bit key as a decimal string (PostgreSQL `bigint`)
|
|
32
|
+
*/
|
|
33
|
+
export declare function computeAdvisoryLockKey(migrationsTableName: string): string;
|
|
34
|
+
/**
|
|
35
|
+
* Acquire a PostgreSQL session-level advisory lock for the migration run.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* The lock is held on a dedicated `QueryRunner` connection for the entire migration run.
|
|
39
|
+
* PostgreSQL releases session-level advisory locks automatically when the connection
|
|
40
|
+
* ends, so a crashed or killed instance can never leave a permanent lock behind — this
|
|
41
|
+
* is why an advisory lock is used rather than a lock row in a table.
|
|
42
|
+
*
|
|
43
|
+
* Polls with `pg_try_advisory_lock` instead of blocking on `pg_advisory_lock` so that
|
|
44
|
+
* waiting is bounded by {@link MIGRATION_LOCK_TIMEOUT_MS} and progress can be logged.
|
|
45
|
+
*
|
|
46
|
+
* @param dataSource - Initialized DataSource used for the migration run
|
|
47
|
+
* @param migrationsTableName - Name of the nauth migrations table (scopes the lock)
|
|
48
|
+
* @param logger - NAuth logger instance
|
|
49
|
+
* @returns A handle to release the lock, or `null` if it could not be acquired in time
|
|
50
|
+
*/
|
|
51
|
+
export declare function acquireMigrationLock(dataSource: DataSource, migrationsTableName: string, logger: NAuthLogger): Promise<MigrationLockHandle | null>;
|
|
52
|
+
//# sourceMappingURL=migration-lock.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-lock.d.ts","sourceRoot":"","sources":["../../src/utils/migration-lock.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,SAAS,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,SAAU,CAAC;AAOjD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;OAIG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAOD;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,mBAAmB,EAAE,MAAM,GAAG,MAAM,CAG1E;AAWD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,UAAU,EACtB,mBAAmB,EAAE,MAAM,EAC3B,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAoDrC"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MIGRATION_LOCK_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.computeAdvisoryLockKey = computeAdvisoryLockKey;
|
|
5
|
+
exports.acquireMigrationLock = acquireMigrationLock;
|
|
6
|
+
const crypto_1 = require("crypto");
|
|
7
|
+
/**
|
|
8
|
+
* How long to wait for another instance to finish migrating before giving up.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Deliberately not configurable. Long enough to cover a realistic migration on a large
|
|
12
|
+
* table, short enough that a genuinely stuck deploy fails with a clear error instead of
|
|
13
|
+
* hanging forever.
|
|
14
|
+
*/
|
|
15
|
+
exports.MIGRATION_LOCK_TIMEOUT_MS = 300_000;
|
|
16
|
+
/**
|
|
17
|
+
* Delay between advisory lock acquisition attempts while waiting.
|
|
18
|
+
*/
|
|
19
|
+
const LOCK_RETRY_DELAY_MS = 1_000;
|
|
20
|
+
/**
|
|
21
|
+
* Derive a stable 64-bit PostgreSQL advisory lock key from the migrations table name.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* Deriving from the table name means two applications sharing one database but using
|
|
25
|
+
* different `tablePrefix` values migrate independently instead of blocking each other.
|
|
26
|
+
*
|
|
27
|
+
* @param migrationsTableName - Name of the nauth migrations table
|
|
28
|
+
* @returns Signed 64-bit key as a decimal string (PostgreSQL `bigint`)
|
|
29
|
+
*/
|
|
30
|
+
function computeAdvisoryLockKey(migrationsTableName) {
|
|
31
|
+
const digest = (0, crypto_1.createHash)('sha256').update(`nauth-toolkit:migrations:${migrationsTableName}`).digest();
|
|
32
|
+
return BigInt.asIntN(64, digest.readBigUInt64BE(0)).toString();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Pause for the given number of milliseconds.
|
|
36
|
+
*
|
|
37
|
+
* @param ms - Delay in milliseconds
|
|
38
|
+
*/
|
|
39
|
+
function delay(ms) {
|
|
40
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Acquire a PostgreSQL session-level advisory lock for the migration run.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* The lock is held on a dedicated `QueryRunner` connection for the entire migration run.
|
|
47
|
+
* PostgreSQL releases session-level advisory locks automatically when the connection
|
|
48
|
+
* ends, so a crashed or killed instance can never leave a permanent lock behind — this
|
|
49
|
+
* is why an advisory lock is used rather than a lock row in a table.
|
|
50
|
+
*
|
|
51
|
+
* Polls with `pg_try_advisory_lock` instead of blocking on `pg_advisory_lock` so that
|
|
52
|
+
* waiting is bounded by {@link MIGRATION_LOCK_TIMEOUT_MS} and progress can be logged.
|
|
53
|
+
*
|
|
54
|
+
* @param dataSource - Initialized DataSource used for the migration run
|
|
55
|
+
* @param migrationsTableName - Name of the nauth migrations table (scopes the lock)
|
|
56
|
+
* @param logger - NAuth logger instance
|
|
57
|
+
* @returns A handle to release the lock, or `null` if it could not be acquired in time
|
|
58
|
+
*/
|
|
59
|
+
async function acquireMigrationLock(dataSource, migrationsTableName, logger) {
|
|
60
|
+
const lockKey = computeAdvisoryLockKey(migrationsTableName);
|
|
61
|
+
const queryRunner = dataSource.createQueryRunner();
|
|
62
|
+
await queryRunner.connect();
|
|
63
|
+
let released = false;
|
|
64
|
+
const handle = {
|
|
65
|
+
async release() {
|
|
66
|
+
if (released)
|
|
67
|
+
return;
|
|
68
|
+
released = true;
|
|
69
|
+
try {
|
|
70
|
+
await queryRunner.query('SELECT pg_advisory_unlock($1::bigint)', [lockKey]);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
// Non-fatal: PostgreSQL drops the lock when the session ends.
|
|
74
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
75
|
+
logger.warn(`[nauth-toolkit] Failed to release migration advisory lock: ${message}`);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await queryRunner.release();
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
const deadline = Date.now() + exports.MIGRATION_LOCK_TIMEOUT_MS;
|
|
83
|
+
let waitLogged = false;
|
|
84
|
+
try {
|
|
85
|
+
for (;;) {
|
|
86
|
+
const rows = (await queryRunner.query('SELECT pg_try_advisory_lock($1::bigint) AS acquired', [
|
|
87
|
+
lockKey,
|
|
88
|
+
]));
|
|
89
|
+
if (rows[0]?.acquired === true) {
|
|
90
|
+
logger.debug(`[nauth-toolkit] Acquired migration advisory lock (key: ${lockKey})`);
|
|
91
|
+
return handle;
|
|
92
|
+
}
|
|
93
|
+
if (Date.now() >= deadline) {
|
|
94
|
+
await queryRunner.release();
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
if (!waitLogged) {
|
|
98
|
+
waitLogged = true;
|
|
99
|
+
logger.log('[nauth-toolkit] Another instance is applying migrations; waiting for it to finish...');
|
|
100
|
+
}
|
|
101
|
+
await delay(LOCK_RETRY_DELAY_MS);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
await queryRunner.release();
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=migration-lock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-lock.js","sourceRoot":"","sources":["../../src/utils/migration-lock.ts"],"names":[],"mappings":";;;AA8CA,wDAGC;AA4BD,oDAwDC;AArID,mCAAoC;AAIpC;;;;;;;GAOG;AACU,QAAA,yBAA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,CAAC,CAAC;gBACjE,MAAM,CAAC,IAAI,CAAC,8DAA8D,OAAO,EAAE,CAAC,CAAC;YACvF,CAAC;oBAAS,CAAC;gBACT,MAAM,WAAW,CAAC,OAAO,EAAE,CAAC;YAC9B,CAAC;QACH,CAAC;KACF,CAAC;IAEF,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,iCAAyB,CAAC;IACxD,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,IAAI,CAAC;QACH,SAAS,CAAC;YACR,MAAM,IAAI,GAAG,CAAC,MAAM,WAAW,CAAC,KAAK,CAAC,qDAAqD,EAAE;gBAC3F,OAAO;aACR,CAAC,CAAsB,CAAC;YAEzB,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,KAAK,IAAI,EAAE,CAAC;gBAC/B,MAAM,CAAC,KAAK,CAAC,0DAA0D,OAAO,GAAG,CAAC,CAAC;gBACnF,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,QAAQ,EAAE,CAAC;gBAC3B,MAAM,WAAW,CAAC,OAAO,EAAE,CAAC;gBAC5B,OAAO,IAAI,CAAC;YACd,CAAC;YAED,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,UAAU,GAAG,IAAI,CAAC;gBAClB,MAAM,CAAC,GAAG,CAAC,sFAAsF,CAAC,CAAC;YACrG,CAAC;YAED,MAAM,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,WAAW,CAAC,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC"}
|
|
@@ -8,6 +8,12 @@ import type { NAuthConfig, NAuthLogger } from '@nauth-toolkit/core';
|
|
|
8
8
|
* ensuring zero interference with consumer migrations. The consumer's DataSource
|
|
9
9
|
* is never modified or accessed for migration purposes.
|
|
10
10
|
*
|
|
11
|
+
* The run is serialized across instances by a PostgreSQL session-level advisory lock, so
|
|
12
|
+
* containers that boot in parallel (ECS tasks, Kubernetes pods) cannot race to create the
|
|
13
|
+
* same tables on a first deployment or apply the same migration twice on a later one.
|
|
14
|
+
* Instances that lose the race wait for the winner and then find nothing left to do. The
|
|
15
|
+
* lock is released by the database if an instance dies, so it can never wedge a deploy.
|
|
16
|
+
*
|
|
11
17
|
* @param dataSource - Consumer's DataSource (only used to extract connection config)
|
|
12
18
|
* @param logger - NAuth logger instance
|
|
13
19
|
* @param config - NAuth configuration
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-migrations.d.ts","sourceRoot":"","sources":["../../src/utils/run-migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"run-migrations.d.ts","sourceRoot":"","sources":["../../src/utils/run-migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAsFpE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,kBAAkB,CACtC,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,IAAI,CAAC,CA2Ef"}
|
|
@@ -4,6 +4,29 @@ exports.runNAuthMigrations = runNAuthMigrations;
|
|
|
4
4
|
const typeorm_1 = require("typeorm");
|
|
5
5
|
const migrations_1 = require("../migrations");
|
|
6
6
|
const entities_1 = require("../entities");
|
|
7
|
+
const migration_lock_1 = require("./migration-lock");
|
|
8
|
+
/**
|
|
9
|
+
* Check whether any nauth migrations are still pending.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* Used only on the lock-timeout path, to distinguish "another instance already did the
|
|
13
|
+
* work" from "the schema is genuinely out of date". Treats a failed check as pending so
|
|
14
|
+
* an unclear state fails loudly instead of starting on an unmigrated schema.
|
|
15
|
+
*
|
|
16
|
+
* @param dataSource - Initialized nauth DataSource
|
|
17
|
+
* @param logger - NAuth logger instance
|
|
18
|
+
* @returns True if migrations remain unapplied (or the check could not be performed)
|
|
19
|
+
*/
|
|
20
|
+
async function hasPendingMigrations(dataSource, logger) {
|
|
21
|
+
try {
|
|
22
|
+
return await dataSource.showMigrations();
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
26
|
+
logger.warn(`[nauth-toolkit] Could not determine pending migrations: ${message}`);
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
7
30
|
function getMigrationsTableName(config) {
|
|
8
31
|
const tablePrefix = config.tablePrefix ?? 'nauth_';
|
|
9
32
|
return `${tablePrefix}migrations`;
|
|
@@ -48,6 +71,12 @@ function extractConnectionConfig(dataSource) {
|
|
|
48
71
|
* ensuring zero interference with consumer migrations. The consumer's DataSource
|
|
49
72
|
* is never modified or accessed for migration purposes.
|
|
50
73
|
*
|
|
74
|
+
* The run is serialized across instances by a PostgreSQL session-level advisory lock, so
|
|
75
|
+
* containers that boot in parallel (ECS tasks, Kubernetes pods) cannot race to create the
|
|
76
|
+
* same tables on a first deployment or apply the same migration twice on a later one.
|
|
77
|
+
* Instances that lose the race wait for the winner and then find nothing left to do. The
|
|
78
|
+
* lock is released by the database if an instance dies, so it can never wedge a deploy.
|
|
79
|
+
*
|
|
51
80
|
* @param dataSource - Consumer's DataSource (only used to extract connection config)
|
|
52
81
|
* @param logger - NAuth logger instance
|
|
53
82
|
* @param config - NAuth configuration
|
|
@@ -70,19 +99,42 @@ async function runNAuthMigrations(dataSource, logger, config) {
|
|
|
70
99
|
try {
|
|
71
100
|
// Initialize the isolated nauth DataSource
|
|
72
101
|
await nauthDataSource.initialize();
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (!
|
|
80
|
-
|
|
81
|
-
|
|
102
|
+
// ============================================================================
|
|
103
|
+
// Acquire the cross-instance migration lock
|
|
104
|
+
// ============================================================================
|
|
105
|
+
// Without this, instances starting in parallel each see an empty migrations table
|
|
106
|
+
// and race to apply the same DDL.
|
|
107
|
+
const lock = await (0, migration_lock_1.acquireMigrationLock)(nauthDataSource, migrationsTableName, logger);
|
|
108
|
+
if (!lock) {
|
|
109
|
+
// Timed out waiting for the instance that holds the lock. Continue only if it
|
|
110
|
+
// already applied everything; never migrate concurrently.
|
|
111
|
+
if (!(await hasPendingMigrations(nauthDataSource, logger))) {
|
|
112
|
+
logger.warn(`[nauth-toolkit] Timed out after ${migration_lock_1.MIGRATION_LOCK_TIMEOUT_MS}ms waiting for the migration lock, but no migrations are pending; continuing startup.`);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
throw new Error(`[nauth-toolkit] Timed out after ${migration_lock_1.MIGRATION_LOCK_TIMEOUT_MS}ms waiting for another instance to finish migrations, and migrations are still pending. ` +
|
|
116
|
+
`Apply migrations before rolling out and set migrations.autoRun to false, or investigate the instance holding the lock.`);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
logger.log(`[nauth-toolkit] Running ${migrations_1.migrations.length} NAuth migration(s) using isolated DataSource (table: ${migrationsTableName})`);
|
|
120
|
+
logger.log('[nauth-toolkit] Checking for pending migrations...');
|
|
121
|
+
// Run migrations on the isolated DataSource
|
|
122
|
+
const executed = (await nauthDataSource.runMigrations({
|
|
123
|
+
transaction: 'all',
|
|
124
|
+
}));
|
|
125
|
+
if (!executed.length) {
|
|
126
|
+
logger.log('[nauth-toolkit] No pending migrations.');
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
logger.log(`[nauth-toolkit] Executed ${executed.length} migration(s):`);
|
|
130
|
+
for (const m of executed)
|
|
131
|
+
logger.log(` ${m.name}`);
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
// Release before destroying the DataSource so the lock is dropped explicitly
|
|
135
|
+
// rather than relying on connection teardown.
|
|
136
|
+
await lock.release();
|
|
82
137
|
}
|
|
83
|
-
logger.log(`[nauth-toolkit] Executed ${executed.length} migration(s):`);
|
|
84
|
-
for (const m of executed)
|
|
85
|
-
logger.log(` ${m.name}`);
|
|
86
138
|
}
|
|
87
139
|
finally {
|
|
88
140
|
// Always destroy the isolated DataSource to clean up connections
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-migrations.js","sourceRoot":"","sources":["../../src/utils/run-migrations.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"run-migrations.js","sourceRoot":"","sources":["../../src/utils/run-migrations.ts"],"names":[],"mappings":";;AAyGA,gDA+EC;AAxLD,qCAAqC;AAErC,8CAA2C;AAC3C,0CAAiF;AACjF,qDAAmF;AAInF;;;;;;;;;;;GAWG;AACH,KAAK,UAAU,oBAAoB,CAAC,UAAsB,EAAE,MAAmB;IAC7E,IAAI,CAAC;QACH,OAAO,MAAM,UAAU,CAAC,cAAc,EAAE,CAAC;IAC3C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,MAAM,CAAC,IAAI,CAAC,2DAA2D,OAAO,EAAE,CAAC,CAAC;QAClF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,sBAAsB,CAAC,MAAmB;IACjD,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,QAAQ,CAAC;IACnD,OAAO,GAAG,WAAW,YAAY,CAAC;AACpC,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,uBAAuB,CAAC,UAAsB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,iEAAiE;QACjE,IAAI,eAAe,CAAC,aAAa,EAAE,CAAC;YAClC,MAAM,eAAe,CAAC,OAAO,EAAE,CAAC;QAClC,CAAC;IACH,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nauth-toolkit/database-typeorm-postgres",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "PostgreSQL storage adapter for nauth-toolkit via TypeORM",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"format:check": "prettier --check \"src/**/*.ts\""
|
|
15
15
|
},
|
|
16
16
|
"peerDependencies": {
|
|
17
|
-
"@nauth-toolkit/core": "^0.
|
|
17
|
+
"@nauth-toolkit/core": "^0.4.0",
|
|
18
18
|
"typeorm": "^0.3.20",
|
|
19
19
|
"pg": "^8.0.0"
|
|
20
20
|
},
|