sqlstack 3.7.1-dev.0 → 3.7.2-dev.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/cjs/core/errors.d.ts +13 -0
- package/dist/cjs/core/errors.d.ts.map +1 -1
- package/dist/cjs/core/errors.js +18 -1
- package/dist/cjs/core/errors.js.map +1 -1
- package/dist/cjs/family.d.ts +6 -0
- package/dist/cjs/family.d.ts.map +1 -1
- package/dist/cjs/family.js +126 -33
- package/dist/cjs/family.js.map +1 -1
- package/dist/cjs/familyBinding.d.ts +4 -0
- package/dist/cjs/familyBinding.d.ts.map +1 -1
- package/dist/cjs/familyBinding.js.map +1 -1
- package/dist/cjs/stack.d.ts.map +1 -1
- package/dist/cjs/stack.js +29 -4
- package/dist/cjs/stack.js.map +1 -1
- package/dist/cjs/transactions.d.ts +61 -0
- package/dist/cjs/transactions.d.ts.map +1 -1
- package/dist/cjs/transactions.js +163 -24
- package/dist/cjs/transactions.js.map +1 -1
- package/dist/esm/core/errors.js +16 -0
- package/dist/esm/core/errors.js.map +1 -1
- package/dist/esm/family.js +127 -34
- package/dist/esm/family.js.map +1 -1
- package/dist/esm/familyBinding.js.map +1 -1
- package/dist/esm/stack.js +29 -4
- package/dist/esm/stack.js.map +1 -1
- package/dist/esm/transactions.js +163 -24
- package/dist/esm/transactions.js.map +1 -1
- package/package.json +1 -1
|
@@ -55,6 +55,19 @@ export declare class TransactionBusyError extends SqlStackError {
|
|
|
55
55
|
readonly code = "tx-busy";
|
|
56
56
|
cause?: unknown;
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* A database family's provider.open() did not settle within the family's
|
|
60
|
+
* `openTimeoutMs`. The attempt was abandoned: waiting acquires are rejected
|
|
61
|
+
* and their leases rolled back, and a handle that arrives later is closed.
|
|
62
|
+
* `code` is `'family-open-timeout'`.
|
|
63
|
+
*/
|
|
64
|
+
export declare class FamilyOpenTimeoutError extends SqlStackError {
|
|
65
|
+
constructor(family: string, keyId: string, timeoutMs: number);
|
|
66
|
+
readonly code = "family-open-timeout";
|
|
67
|
+
family: string;
|
|
68
|
+
keyId: string;
|
|
69
|
+
timeoutMs: number;
|
|
70
|
+
}
|
|
58
71
|
export declare class RollbackTransactionError extends SqlStackError {
|
|
59
72
|
constructor(message?: string, cause?: unknown);
|
|
60
73
|
cause?: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,CAAC,EAAE,MAAM;CAI7B;AAED,qBAAa,kBAAmB,SAAQ,aAAa;gBACvC,WAAW,EAAE,MAAM;CAIhC;AAED,qBAAa,WAAY,SAAQ,aAAa;;CAK7C;AAED,qBAAa,cAAe,SAAQ,aAAa;gBACnC,WAAW,EAAE,MAAM;CAIhC;AAKD,qBAAa,iBAAkB,SAAQ,aAAa;gBACtC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IAUzC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,qBAAa,eAAgB,SAAQ,aAAa;gBACpC,OAAO,EAAE,MAAM;IAK3B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,qBAAa,aAAc,SAAQ,aAAa;gBAClC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK;IAQvD,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,qBAAa,uBAAwB,SAAQ,aAAa;gBAC5C,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;IAK5C,QAAQ,CAAC,IAAI,gBAAgB;IAC7B,KAAK,CAAC,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KAAK,CAAC,EAAE,OAAO;IAK5C,QAAQ,CAAC,IAAI,gBAAgB;IAC7B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,SAAQ,aAAa;gBACzC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;IAK5C,QAAQ,CAAC,IAAI,aAAa;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,aAAa;gBAC3C,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAO5D,QAAQ,CAAC,IAAI,yBAAyB;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAID,qBAAa,wBAAyB,SAAQ,aAAa;gBAC7C,OAAO,SAA4B,EAAE,KAAK,CAAC,EAAE,OAAO;IAKhE,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB"}
|
package/dist/cjs/core/errors.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RollbackTransactionError = exports.TransactionBusyError = exports.TransactionExpiredError = exports.DatabaseError = exports.ValidationError = exports.ExpectedRowsError = exports.RowsExistError = exports.NoRowsError = exports.ExactlyOneRowError = exports.SqlStackError = void 0;
|
|
3
|
+
exports.RollbackTransactionError = exports.FamilyOpenTimeoutError = exports.TransactionBusyError = exports.TransactionExpiredError = exports.DatabaseError = exports.ValidationError = exports.ExpectedRowsError = exports.RowsExistError = exports.NoRowsError = exports.ExactlyOneRowError = exports.SqlStackError = void 0;
|
|
4
4
|
class SqlStackError extends Error {
|
|
5
5
|
constructor(message) {
|
|
6
6
|
super(message);
|
|
@@ -100,6 +100,23 @@ class TransactionBusyError extends SqlStackError {
|
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
exports.TransactionBusyError = TransactionBusyError;
|
|
103
|
+
/**
|
|
104
|
+
* A database family's provider.open() did not settle within the family's
|
|
105
|
+
* `openTimeoutMs`. The attempt was abandoned: waiting acquires are rejected
|
|
106
|
+
* and their leases rolled back, and a handle that arrives later is closed.
|
|
107
|
+
* `code` is `'family-open-timeout'`.
|
|
108
|
+
*/
|
|
109
|
+
class FamilyOpenTimeoutError extends SqlStackError {
|
|
110
|
+
constructor(family, keyId, timeoutMs) {
|
|
111
|
+
super(`Opening "${family}/${keyId}" timed out after ${timeoutMs}ms; the attempt was abandoned.`);
|
|
112
|
+
this.code = 'family-open-timeout';
|
|
113
|
+
this.family = family;
|
|
114
|
+
this.keyId = keyId;
|
|
115
|
+
this.timeoutMs = timeoutMs;
|
|
116
|
+
this.name = 'FamilyOpenTimeoutError';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.FamilyOpenTimeoutError = FamilyOpenTimeoutError;
|
|
103
120
|
// Signals that the current transaction should be rolled back.
|
|
104
121
|
// If `cause` is provided, wrappers may rethrow it after rollback.
|
|
105
122
|
class RollbackTransactionError extends SqlStackError {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC;AAED,MAAa,kBAAmB,SAAQ,aAAa;IACnD,YAAY,WAAmB;QAC7B,KAAK,CAAC,iCAAiC,WAAW,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AALD,gDAKC;AAED,MAAa,WAAY,SAAQ,aAAa;IAC5C;QACE,KAAK,CAAC,kCAAkC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AE,IAAI,CAAC;QAC7D,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CAKF;AAbD,sCAaC;AAED;;;;;;GAMG;AACH,MAAa,uBAAwB,SAAQ,aAAa;IACxD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,YAAY,CAAC;QAH3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CAGF;AARD,0DAQC;AAED;;;;GAIG;AACH,MAAa,oBAAqB,SAAQ,aAAa;IACrD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,SAAS,CAAC;QAHxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CAGF;AARD,oDAQC;AAED,8DAA8D;AAC9D,kEAAkE;AAClE,MAAa,wBAAyB,SAAQ,aAAa;IACzD,YAAY,OAAO,GAAG,yBAAyB,EAAE,KAAe;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CAEF;AAPD,4DAOC","sourcesContent":["export class SqlStackError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = 'SqlStackError';\n }\n}\n\nexport class ExactlyOneRowError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected exactly one row, got ${actualCount}`);\n this.name = 'ExactlyOneRowError';\n }\n}\n\nexport class NoRowsError extends SqlStackError {\n constructor() {\n super('Expected at least one row, got 0');\n this.name = 'NoRowsError';\n }\n}\n\nexport class RowsExistError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected no rows, got ${actualCount}`);\n this.name = 'RowsExistError';\n }\n}\n\n// A result-shape decorator (@Single/@Only/@Exist/@None) was applied to a\n// method whose statement produced no result set (a plain write). Shapes\n// require rows; use `... RETURNING` or drop the decorator.\nexport class ExpectedRowsError extends SqlStackError {\n constructor(method: string, shape: string) {\n const decorator = '@' + shape.charAt(0).toUpperCase() + shape.slice(1);\n super(\n `${decorator} on ${method} requires a result set, but the statement produced a write result ` +\n `({ rowsAffected }). Add a RETURNING clause or remove the shape decorator.`\n );\n this.method = method;\n this.shape = shape;\n this.name = 'ExpectedRowsError';\n }\n method: string;\n shape: string;\n}\n\nexport class ValidationError extends SqlStackError {\n constructor(details: string) {\n super(`Validation failed: ${details}`);\n this.details = details;\n this.name = 'ValidationError';\n }\n details: string;\n}\n\n/**\n * A statement failed: the driver rejected it, or (for the `run(...)` forms\n * that take arguments) the SQL could not be compiled, bound, or routed to a\n * database. The original error is kept in `.cause`; when the cause carries a\n * string driver code (`SQLITE_CONSTRAINT_UNIQUE`, `23505`, `ER_DUP_ENTRY`)\n * it is copied to `.code` so existing `err.code` checks keep working.\n */\nexport class DatabaseError extends SqlStackError {\n constructor(message: string, sql: string, cause?: Error) {\n super(`${message}\\nSQL: ${sql}`);\n this.sql = sql;\n this.cause = cause;\n const code = (cause as { code?: unknown } | undefined)?.code;\n if (typeof code === 'string') this.code = code;\n this.name = 'DatabaseError';\n }\n sql: string;\n cause?: Error;\n /** Driver error code copied from `cause` when it is a string. */\n code?: string;\n}\n\n/**\n * The database ended the transaction on its own and rolled it back: a sqlego\n * lease ran out (no statement within the lease), the transaction hit the\n * server's hard cap on its duration, or the client connection dropped.\n * `code` is `'tx-expired'`. Statements fail with it (wrapped in\n * DatabaseError, which copies the code); COMMIT fails with it directly.\n */\nexport class TransactionExpiredError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionExpiredError';\n }\n readonly code = 'tx-expired';\n cause?: unknown;\n}\n\n/**\n * Another process held the database in a transaction for longer than the\n * server lets a request wait (sqlego's queue timeout). Nothing ran; the\n * statement or BEGIN can be retried. `code` is `'tx-busy'`.\n */\nexport class TransactionBusyError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionBusyError';\n }\n readonly code = 'tx-busy';\n cause?: unknown;\n}\n\n// Signals that the current transaction should be rolled back.\n// If `cause` is provided, wrappers may rethrow it after rollback.\nexport class RollbackTransactionError extends SqlStackError {\n constructor(message = 'Transaction rolled back', cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'RollbackTransactionError';\n }\n cause?: unknown;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC;AAED,MAAa,kBAAmB,SAAQ,aAAa;IACnD,YAAY,WAAmB;QAC7B,KAAK,CAAC,iCAAiC,WAAW,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AALD,gDAKC;AAED,MAAa,WAAY,SAAQ,aAAa;IAC5C;QACE,KAAK,CAAC,kCAAkC,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AALD,kCAKC;AAED,MAAa,cAAe,SAAQ,aAAa;IAC/C,YAAY,WAAmB;QAC7B,KAAK,CAAC,yBAAyB,WAAW,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AALD,wCAKC;AAED,yEAAyE;AACzE,wEAAwE;AACxE,2DAA2D;AA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AY,CAAC;QAH3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CAGF;AARD,0DAQC;AAED;;;;GAIG;AACH,MAAa,oBAAqB,SAAQ,aAAa;IACrD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,SAAS,CAAC;QAHxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CAGF;AARD,oDAQC;AAED;;;;;GAKG;AACH,MAAa,sBAAuB,SAAQ,aAAa;IACvD,YAAY,MAAc,EAAE,KAAa,EAAE,SAAiB;QAC1D,KAAK,CAAC,YAAY,MAAM,IAAI,KAAK,qBAAqB,SAAS,gCAAgC,CAAC,CAAC;QAM1F,SAAI,GAAG,qBAAqB,CAAC;QALpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CAKF;AAZD,wDAYC;AAED,8DAA8D;AAC9D,kEAAkE;AAClE,MAAa,wBAAyB,SAAQ,aAAa;IACzD,YAAY,OAAO,GAAG,yBAAyB,EAAE,KAAe;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CAEF;AAPD,4DAOC","sourcesContent":["export class SqlStackError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = 'SqlStackError';\n }\n}\n\nexport class ExactlyOneRowError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected exactly one row, got ${actualCount}`);\n this.name = 'ExactlyOneRowError';\n }\n}\n\nexport class NoRowsError extends SqlStackError {\n constructor() {\n super('Expected at least one row, got 0');\n this.name = 'NoRowsError';\n }\n}\n\nexport class RowsExistError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected no rows, got ${actualCount}`);\n this.name = 'RowsExistError';\n }\n}\n\n// A result-shape decorator (@Single/@Only/@Exist/@None) was applied to a\n// method whose statement produced no result set (a plain write). Shapes\n// require rows; use `... RETURNING` or drop the decorator.\nexport class ExpectedRowsError extends SqlStackError {\n constructor(method: string, shape: string) {\n const decorator = '@' + shape.charAt(0).toUpperCase() + shape.slice(1);\n super(\n `${decorator} on ${method} requires a result set, but the statement produced a write result ` +\n `({ rowsAffected }). Add a RETURNING clause or remove the shape decorator.`\n );\n this.method = method;\n this.shape = shape;\n this.name = 'ExpectedRowsError';\n }\n method: string;\n shape: string;\n}\n\nexport class ValidationError extends SqlStackError {\n constructor(details: string) {\n super(`Validation failed: ${details}`);\n this.details = details;\n this.name = 'ValidationError';\n }\n details: string;\n}\n\n/**\n * A statement failed: the driver rejected it, or (for the `run(...)` forms\n * that take arguments) the SQL could not be compiled, bound, or routed to a\n * database. The original error is kept in `.cause`; when the cause carries a\n * string driver code (`SQLITE_CONSTRAINT_UNIQUE`, `23505`, `ER_DUP_ENTRY`)\n * it is copied to `.code` so existing `err.code` checks keep working.\n */\nexport class DatabaseError extends SqlStackError {\n constructor(message: string, sql: string, cause?: Error) {\n super(`${message}\\nSQL: ${sql}`);\n this.sql = sql;\n this.cause = cause;\n const code = (cause as { code?: unknown } | undefined)?.code;\n if (typeof code === 'string') this.code = code;\n this.name = 'DatabaseError';\n }\n sql: string;\n cause?: Error;\n /** Driver error code copied from `cause` when it is a string. */\n code?: string;\n}\n\n/**\n * The database ended the transaction on its own and rolled it back: a sqlego\n * lease ran out (no statement within the lease), the transaction hit the\n * server's hard cap on its duration, or the client connection dropped.\n * `code` is `'tx-expired'`. Statements fail with it (wrapped in\n * DatabaseError, which copies the code); COMMIT fails with it directly.\n */\nexport class TransactionExpiredError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionExpiredError';\n }\n readonly code = 'tx-expired';\n cause?: unknown;\n}\n\n/**\n * Another process held the database in a transaction for longer than the\n * server lets a request wait (sqlego's queue timeout). Nothing ran; the\n * statement or BEGIN can be retried. `code` is `'tx-busy'`.\n */\nexport class TransactionBusyError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionBusyError';\n }\n readonly code = 'tx-busy';\n cause?: unknown;\n}\n\n/**\n * A database family's provider.open() did not settle within the family's\n * `openTimeoutMs`. The attempt was abandoned: waiting acquires are rejected\n * and their leases rolled back, and a handle that arrives later is closed.\n * `code` is `'family-open-timeout'`.\n */\nexport class FamilyOpenTimeoutError extends SqlStackError {\n constructor(family: string, keyId: string, timeoutMs: number) {\n super(`Opening \"${family}/${keyId}\" timed out after ${timeoutMs}ms; the attempt was abandoned.`);\n this.family = family;\n this.keyId = keyId;\n this.timeoutMs = timeoutMs;\n this.name = 'FamilyOpenTimeoutError';\n }\n readonly code = 'family-open-timeout';\n family: string;\n keyId: string;\n timeoutMs: number;\n}\n\n// Signals that the current transaction should be rolled back.\n// If `cause` is provided, wrappers may rethrow it after rollback.\nexport class RollbackTransactionError extends SqlStackError {\n constructor(message = 'Transaction rolled back', cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'RollbackTransactionError';\n }\n cause?: unknown;\n}\n"]}
|
package/dist/cjs/family.d.ts
CHANGED
|
@@ -32,6 +32,12 @@ export interface FamilyConfig<K = string> {
|
|
|
32
32
|
/** Max concurrently open members (default 16). Leased members never evict. */
|
|
33
33
|
maxOpen?: number;
|
|
34
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Max ms to wait for provider.open(). On expiry waiting acquires reject with
|
|
37
|
+
* FamilyOpenTimeoutError and a handle that arrives later is closed.
|
|
38
|
+
* Default: no timeout.
|
|
39
|
+
*/
|
|
40
|
+
openTimeoutMs?: number;
|
|
35
41
|
}
|
|
36
42
|
/** Concrete member identity: owning stack + family registration + key. */
|
|
37
43
|
export interface FamilyMemberEntry extends DatabaseEntry {
|
package/dist/cjs/family.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"family.d.ts","sourceRoot":"","sources":["../../src/family.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"family.d.ts","sourceRoot":"","sources":["../../src/family.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAEvD;;;;GAIG;AAEH,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;IACrC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,MAAM;IAChD,6EAA6E;IAC7E,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,CAAC,CAAC;IAChC,0EAA0E;IAC1E,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC;IACvB,gFAAgF;IAChF,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAChC,6DAA6D;IAC7D,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACnC,kCAAkC;IAClC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACnC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClC,6EAA6E;IAC7E,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,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,sDAAsD;IAChD,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,aAAa,CAAC;IAoC/C,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IASvF,8EAA8E;IACxE,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAYhD,sFAAsF;IAChF,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAc3C,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAQ1D,0EAA0E;IACpE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAmKhC"}
|
package/dist/cjs/family.js
CHANGED
|
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
11
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
12
|
};
|
|
13
|
-
var _FamilyRuntime_instances, _FamilyRuntime_stack, _FamilyRuntime_provider, _FamilyRuntime_maxOpen, _FamilyRuntime_members, _FamilyRuntime_useTick, _FamilyRuntime_closed,
|
|
13
|
+
var _FamilyRuntime_instances, _FamilyRuntime_stack, _FamilyRuntime_provider, _FamilyRuntime_maxOpen, _FamilyRuntime_openTimeoutMs, _FamilyRuntime_members, _FamilyRuntime_entries, _FamilyRuntime_reaper, _FamilyRuntime_useTick, _FamilyRuntime_closed, _FamilyRuntime_entry, _FamilyRuntime_record, _FamilyRuntime_pruneIfIdle, _FamilyRuntime_open, _FamilyRuntime_startOpen, _FamilyRuntime_closeHandle, _FamilyRuntime_evictIfNeeded, _FamilyRuntime_assertOpen;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.FamilyRuntime = void 0;
|
|
16
16
|
const errors_1 = require("./core/errors");
|
|
@@ -23,13 +23,29 @@ class FamilyRuntime {
|
|
|
23
23
|
_FamilyRuntime_stack.set(this, void 0);
|
|
24
24
|
_FamilyRuntime_provider.set(this, void 0);
|
|
25
25
|
_FamilyRuntime_maxOpen.set(this, void 0);
|
|
26
|
+
_FamilyRuntime_openTimeoutMs.set(this, void 0);
|
|
27
|
+
/** Live records only: a record exists while it has a lease, an open handle, or an open in flight. */
|
|
26
28
|
_FamilyRuntime_members.set(this, new Map());
|
|
29
|
+
// Entry identity outlives a pruned record for as long as anyone holds the
|
|
30
|
+
// entry (transactions key by entry object); a live record holds it strongly.
|
|
31
|
+
_FamilyRuntime_entries.set(this, new Map());
|
|
32
|
+
_FamilyRuntime_reaper.set(this, new FinalizationRegistry((keyId) => {
|
|
33
|
+
if (__classPrivateFieldGet(this, _FamilyRuntime_entries, "f").get(keyId)?.deref() === undefined)
|
|
34
|
+
__classPrivateFieldGet(this, _FamilyRuntime_entries, "f").delete(keyId);
|
|
35
|
+
}));
|
|
27
36
|
_FamilyRuntime_useTick.set(this, 0);
|
|
28
37
|
_FamilyRuntime_closed.set(this, false);
|
|
29
38
|
__classPrivateFieldSet(this, _FamilyRuntime_stack, stack, "f");
|
|
30
39
|
this.name = name;
|
|
31
40
|
__classPrivateFieldSet(this, _FamilyRuntime_provider, config.provider, "f");
|
|
32
41
|
__classPrivateFieldSet(this, _FamilyRuntime_maxOpen, config.cache?.maxOpen ?? 16, "f");
|
|
42
|
+
const timeout = config.openTimeoutMs;
|
|
43
|
+
// setTimeout fires after 1ms for delays above 2^31-1.
|
|
44
|
+
if (timeout !== undefined && !(Number.isFinite(timeout) && timeout > 0 && timeout <= 2147483647)) {
|
|
45
|
+
throw new errors_1.SqlStackError(`Database family "${name}": openTimeoutMs must be a positive number of milliseconds ` +
|
|
46
|
+
`(max 2147483647), got ${String(timeout)}.`);
|
|
47
|
+
}
|
|
48
|
+
__classPrivateFieldSet(this, _FamilyRuntime_openTimeoutMs, timeout, "f");
|
|
33
49
|
}
|
|
34
50
|
normalize(input) {
|
|
35
51
|
const key = __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").normalizeKey(input);
|
|
@@ -38,7 +54,7 @@ class FamilyRuntime {
|
|
|
38
54
|
}
|
|
39
55
|
/** Stable concrete identity for a key; no I/O. */
|
|
40
56
|
ref(input) {
|
|
41
|
-
return __classPrivateFieldGet(this, _FamilyRuntime_instances, "m",
|
|
57
|
+
return __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_entry).call(this, this.normalize(input).keyId);
|
|
42
58
|
}
|
|
43
59
|
async exists(input) {
|
|
44
60
|
const { key } = this.normalize(input);
|
|
@@ -48,36 +64,42 @@ class FamilyRuntime {
|
|
|
48
64
|
}
|
|
49
65
|
async create(input) {
|
|
50
66
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_assertOpen).call(this);
|
|
51
|
-
const
|
|
67
|
+
const { key } = this.normalize(input);
|
|
52
68
|
if (!__classPrivateFieldGet(this, _FamilyRuntime_provider, "f").create)
|
|
53
69
|
unsupported(this.name, 'create');
|
|
54
|
-
const db = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").create(
|
|
70
|
+
const db = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").create(key);
|
|
55
71
|
await db.close();
|
|
56
72
|
}
|
|
57
73
|
async ensure(input) {
|
|
58
74
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_assertOpen).call(this);
|
|
59
|
-
const
|
|
75
|
+
const { key } = this.normalize(input);
|
|
60
76
|
if (!__classPrivateFieldGet(this, _FamilyRuntime_provider, "f").ensure)
|
|
61
77
|
unsupported(this.name, 'ensure');
|
|
62
|
-
const db = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").ensure(
|
|
78
|
+
const db = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").ensure(key);
|
|
63
79
|
await db.close();
|
|
64
80
|
}
|
|
65
81
|
/** Acquire a lease on an opened (existing) member. */
|
|
66
82
|
async acquire(input) {
|
|
67
83
|
var _a;
|
|
68
84
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_assertOpen).call(this);
|
|
69
|
-
const
|
|
85
|
+
const { key, keyId } = this.normalize(input);
|
|
86
|
+
const member = __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_record).call(this, keyId);
|
|
70
87
|
// Count the lease before awaiting the open. Otherwise, while this acquire
|
|
71
88
|
// is suspended, a concurrent release on the same member (or any other)
|
|
72
89
|
// runs eviction, sees zero leases, and closes the handle this acquire is
|
|
73
90
|
// about to return — with maxOpen: 0 that hands the caller a closed member.
|
|
74
91
|
member.leases++;
|
|
75
92
|
try {
|
|
76
|
-
await __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_open).call(this, member);
|
|
93
|
+
await __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_open).call(this, member, key);
|
|
94
|
+
// closeAll() may have run while this acquire was suspended (even on an
|
|
95
|
+
// already-cached member). It owns every handle from then on; never hand
|
|
96
|
+
// out a lease on a closed family.
|
|
97
|
+
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_assertOpen).call(this);
|
|
77
98
|
}
|
|
78
99
|
catch (err) {
|
|
79
100
|
member.leases = Math.max(0, member.leases - 1);
|
|
80
101
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_evictIfNeeded).call(this);
|
|
102
|
+
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_pruneIfIdle).call(this, member);
|
|
81
103
|
throw err;
|
|
82
104
|
}
|
|
83
105
|
member.lastUsed = __classPrivateFieldSet(this, _FamilyRuntime_useTick, (_a = __classPrivateFieldGet(this, _FamilyRuntime_useTick, "f"), ++_a), "f");
|
|
@@ -91,6 +113,7 @@ class FamilyRuntime {
|
|
|
91
113
|
released = true;
|
|
92
114
|
member.leases = Math.max(0, member.leases - 1);
|
|
93
115
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_evictIfNeeded).call(this);
|
|
116
|
+
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_pruneIfIdle).call(this, member);
|
|
94
117
|
},
|
|
95
118
|
};
|
|
96
119
|
}
|
|
@@ -117,27 +140,33 @@ class FamilyRuntime {
|
|
|
117
140
|
/** Physically delete a member. Fails while leased; closes the cached handle first. */
|
|
118
141
|
async deleteMember(input) {
|
|
119
142
|
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_assertOpen).call(this);
|
|
120
|
-
const
|
|
143
|
+
const { key, keyId } = this.normalize(input);
|
|
121
144
|
if (!__classPrivateFieldGet(this, _FamilyRuntime_provider, "f").delete)
|
|
122
145
|
unsupported(this.name, 'delete');
|
|
123
|
-
|
|
124
|
-
|
|
146
|
+
const member = __classPrivateFieldGet(this, _FamilyRuntime_members, "f").get(keyId);
|
|
147
|
+
if (member && member.leases > 0) {
|
|
148
|
+
throw new errors_1.SqlStackError(`Cannot delete "${this.name}/${keyId}": ${member.leases} lease(s) are active.`);
|
|
125
149
|
}
|
|
126
|
-
if (member
|
|
150
|
+
if (member?.db)
|
|
127
151
|
await __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_closeHandle).call(this, member);
|
|
128
|
-
await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").delete(
|
|
129
|
-
__classPrivateFieldGet(this, _FamilyRuntime_members, "f").delete(member.entry.keyId);
|
|
152
|
+
await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").delete(key);
|
|
130
153
|
}
|
|
131
154
|
async inspect(input) {
|
|
132
|
-
const
|
|
155
|
+
const { key, keyId } = this.normalize(input);
|
|
133
156
|
if (!__classPrivateFieldGet(this, _FamilyRuntime_provider, "f").inspect)
|
|
134
157
|
unsupported(this.name, 'inspect');
|
|
135
|
-
const facts = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").inspect(
|
|
136
|
-
|
|
158
|
+
const facts = await __classPrivateFieldGet(this, _FamilyRuntime_provider, "f").inspect(key);
|
|
159
|
+
const member = __classPrivateFieldGet(this, _FamilyRuntime_members, "f").get(keyId);
|
|
160
|
+
return { ...facts, cached: !!member?.db, activeLeases: member?.leases ?? 0 };
|
|
137
161
|
}
|
|
138
162
|
/** Close every cached handle (root disposal). Databases are preserved. */
|
|
139
163
|
async closeAll() {
|
|
140
164
|
__classPrivateFieldSet(this, _FamilyRuntime_closed, true, "f");
|
|
165
|
+
// Abandon in-flight opens before any await: waiters reject, and a handle
|
|
166
|
+
// that lands later is closed by its attempt instead of leaking.
|
|
167
|
+
for (const member of __classPrivateFieldGet(this, _FamilyRuntime_members, "f").values()) {
|
|
168
|
+
member.opening?.abandon(new errors_1.SqlStackError(`Database family "${this.name}" was closed while "${this.name}/${member.entry.keyId}" was opening.`));
|
|
169
|
+
}
|
|
141
170
|
const failures = [];
|
|
142
171
|
for (const member of __classPrivateFieldGet(this, _FamilyRuntime_members, "f").values()) {
|
|
143
172
|
if (!member.db)
|
|
@@ -150,18 +179,18 @@ class FamilyRuntime {
|
|
|
150
179
|
}
|
|
151
180
|
}
|
|
152
181
|
__classPrivateFieldGet(this, _FamilyRuntime_members, "f").clear();
|
|
182
|
+
__classPrivateFieldGet(this, _FamilyRuntime_entries, "f").clear();
|
|
153
183
|
if (failures.length) {
|
|
154
184
|
throw new errors_1.SqlStackError(`Family close failed for ${failures.join(', ')}`);
|
|
155
185
|
}
|
|
156
186
|
}
|
|
157
187
|
}
|
|
158
188
|
exports.FamilyRuntime = FamilyRuntime;
|
|
159
|
-
_FamilyRuntime_stack = new WeakMap(), _FamilyRuntime_provider = new WeakMap(), _FamilyRuntime_maxOpen = new WeakMap(), _FamilyRuntime_members = new WeakMap(), _FamilyRuntime_useTick = new WeakMap(), _FamilyRuntime_closed = new WeakMap(), _FamilyRuntime_instances = new WeakSet(),
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
if (!member) {
|
|
189
|
+
_FamilyRuntime_stack = new WeakMap(), _FamilyRuntime_provider = new WeakMap(), _FamilyRuntime_maxOpen = new WeakMap(), _FamilyRuntime_openTimeoutMs = new WeakMap(), _FamilyRuntime_members = new WeakMap(), _FamilyRuntime_entries = new WeakMap(), _FamilyRuntime_reaper = new WeakMap(), _FamilyRuntime_useTick = new WeakMap(), _FamilyRuntime_closed = new WeakMap(), _FamilyRuntime_instances = new WeakSet(), _FamilyRuntime_entry = function _FamilyRuntime_entry(keyId) {
|
|
190
|
+
let entry = __classPrivateFieldGet(this, _FamilyRuntime_entries, "f").get(keyId)?.deref();
|
|
191
|
+
if (!entry) {
|
|
163
192
|
const self = this;
|
|
164
|
-
|
|
193
|
+
entry = {
|
|
165
194
|
name: this.name,
|
|
166
195
|
family: this.name,
|
|
167
196
|
keyId,
|
|
@@ -176,27 +205,91 @@ _FamilyRuntime_stack = new WeakMap(), _FamilyRuntime_provider = new WeakMap(), _
|
|
|
176
205
|
return state.db;
|
|
177
206
|
},
|
|
178
207
|
};
|
|
179
|
-
|
|
208
|
+
__classPrivateFieldGet(this, _FamilyRuntime_entries, "f").set(keyId, new WeakRef(entry));
|
|
209
|
+
__classPrivateFieldGet(this, _FamilyRuntime_reaper, "f").register(entry, keyId);
|
|
210
|
+
}
|
|
211
|
+
return entry;
|
|
212
|
+
}, _FamilyRuntime_record = function _FamilyRuntime_record(keyId) {
|
|
213
|
+
let member = __classPrivateFieldGet(this, _FamilyRuntime_members, "f").get(keyId);
|
|
214
|
+
if (!member) {
|
|
215
|
+
member = { entry: __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_entry).call(this, keyId), leases: 0, lastUsed: 0 };
|
|
180
216
|
__classPrivateFieldGet(this, _FamilyRuntime_members, "f").set(keyId, member);
|
|
181
217
|
}
|
|
182
|
-
return
|
|
183
|
-
},
|
|
218
|
+
return member;
|
|
219
|
+
}, _FamilyRuntime_pruneIfIdle = function _FamilyRuntime_pruneIfIdle(member) {
|
|
220
|
+
if (member.leases > 0 || member.db || member.opening)
|
|
221
|
+
return;
|
|
222
|
+
if (__classPrivateFieldGet(this, _FamilyRuntime_members, "f").get(member.entry.keyId) === member)
|
|
223
|
+
__classPrivateFieldGet(this, _FamilyRuntime_members, "f").delete(member.entry.keyId);
|
|
224
|
+
}, _FamilyRuntime_open = async function _FamilyRuntime_open(member, key) {
|
|
184
225
|
if (member.db)
|
|
185
226
|
return;
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
227
|
+
member.opening ?? (member.opening = __classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_startOpen).call(this, member, key));
|
|
228
|
+
await member.opening.promise;
|
|
229
|
+
}, _FamilyRuntime_startOpen = function _FamilyRuntime_startOpen(member, key) {
|
|
230
|
+
let settled = false;
|
|
231
|
+
let timer;
|
|
232
|
+
let resolve;
|
|
233
|
+
let reject;
|
|
234
|
+
const promise = new Promise((res, rej) => {
|
|
235
|
+
resolve = res;
|
|
236
|
+
reject = rej;
|
|
237
|
+
});
|
|
238
|
+
promise.catch(() => undefined); // surfaced to awaiting callers
|
|
239
|
+
// Exactly one of open/error/timeout/close wins; later outcomes are no-ops.
|
|
240
|
+
const settle = () => {
|
|
241
|
+
if (settled)
|
|
242
|
+
return false;
|
|
243
|
+
settled = true;
|
|
244
|
+
if (timer !== undefined)
|
|
245
|
+
clearTimeout(timer);
|
|
246
|
+
if (member.opening === attempt)
|
|
247
|
+
member.opening = undefined; // never clobber a newer attempt
|
|
248
|
+
return true;
|
|
249
|
+
};
|
|
250
|
+
const attempt = {
|
|
251
|
+
promise,
|
|
252
|
+
abandon: (reason) => {
|
|
253
|
+
if (settle())
|
|
254
|
+
reject(reason);
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
if (__classPrivateFieldGet(this, _FamilyRuntime_openTimeoutMs, "f") !== undefined) {
|
|
258
|
+
const ms = __classPrivateFieldGet(this, _FamilyRuntime_openTimeoutMs, "f");
|
|
259
|
+
timer = setTimeout(() => attempt.abandon(new errors_1.FamilyOpenTimeoutError(this.name, member.entry.keyId, ms)), ms);
|
|
260
|
+
}
|
|
261
|
+
let pending;
|
|
262
|
+
try {
|
|
263
|
+
pending = Promise.resolve(__classPrivateFieldGet(this, _FamilyRuntime_provider, "f").open(key));
|
|
264
|
+
}
|
|
265
|
+
catch (err) {
|
|
266
|
+
pending = Promise.reject(err);
|
|
267
|
+
}
|
|
268
|
+
pending.then((db) => {
|
|
269
|
+
if (!settle()) {
|
|
270
|
+
// Late arrival (timed out or family closed): nobody owns this handle.
|
|
271
|
+
void Promise.resolve()
|
|
272
|
+
.then(() => db.close())
|
|
273
|
+
.catch(() => undefined);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
member.db = db; // single publication point, while waiters still hold leases
|
|
277
|
+
resolve(db);
|
|
278
|
+
}, (err) => {
|
|
279
|
+
if (settle())
|
|
280
|
+
reject(err);
|
|
281
|
+
});
|
|
282
|
+
return attempt;
|
|
194
283
|
}, _FamilyRuntime_closeHandle = async function _FamilyRuntime_closeHandle(member) {
|
|
195
284
|
const db = member.db;
|
|
196
285
|
member.db = undefined;
|
|
286
|
+
__classPrivateFieldGet(this, _FamilyRuntime_instances, "m", _FamilyRuntime_pruneIfIdle).call(this, member);
|
|
197
287
|
if (db)
|
|
198
288
|
await db.close();
|
|
199
289
|
}, _FamilyRuntime_evictIfNeeded = function _FamilyRuntime_evictIfNeeded() {
|
|
290
|
+
// Once closed, closeAll owns every handle: it awaits the close and reports failures.
|
|
291
|
+
if (__classPrivateFieldGet(this, _FamilyRuntime_closed, "f"))
|
|
292
|
+
return;
|
|
200
293
|
const open = [...__classPrivateFieldGet(this, _FamilyRuntime_members, "f").values()].filter((m) => m.db);
|
|
201
294
|
if (open.length <= __classPrivateFieldGet(this, _FamilyRuntime_maxOpen, "f"))
|
|
202
295
|
return;
|
package/dist/cjs/family.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"family.js","sourceRoot":"","sources":["../../src/family.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,0CAA8C;AA2D9C,SAAS,WAAW,CAAC,MAAc,EAAE,EAAU;IAC7C,MAAM,IAAI,sBAAa,CACrB,oBAAoB,MAAM,sBAAsB,EAAE,+CAA+C,CAClG,CAAC;AACJ,CAAC;AAED,MAAa,aAAa;IASxB,YAAY,KAAe,EAAE,IAAY,EAAE,MAAuB;;QAPzD,uCAAiB;QACjB,0CAAqC;QACrC,yCAAiB;QACjB,iCAAW,IAAI,GAAG,EAAuB,EAAC;QACnD,iCAAW,CAAC,EAAC;QACb,gCAAU,KAAK,EAAC;QAGd,uBAAA,IAAI,wBAAU,KAAK,MAAA,CAAC;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,uBAAA,IAAI,2BAAa,MAAM,CAAC,QAAQ,MAAA,CAAC;QACjC,uBAAA,IAAI,0BAAY,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,MAAA,CAAC;IAC9C,CAAC;IAED,SAAS,CAAC,KAAc;QACtB,MAAM,GAAG,GAAG,uBAAA,IAAI,+BAAU,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAC/C,MAAM,KAAK,GAAG,uBAAA,IAAI,+BAAU,CAAC,KAAK,CAAC,CAAC,CAAC,uBAAA,IAAI,+BAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7E,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;IACxB,CAAC;IAED,kDAAkD;IAClD,GAAG,CAAC,KAAc;QACh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AAC;SAC7B,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;IAC3C,KAAK,MAAM,MAAM,IAAI,SAAS,EAAE,CAAC;QAC/B,IAAI,CAAC,GAAG,uBAAA,IAAI,8BAAS,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,IAAI,uBAAA,IAAI,8BAAS;YAAE,MAAM;QACnF,8EAA8E;QAC9E,KAAK,uBAAA,IAAI,4DAAa,MAAjB,IAAI,EAAc,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;AACH,CAAC;IAGC,IAAI,uBAAA,IAAI,6BAAQ,EAAE,CAAC;QACjB,MAAM,IAAI,sBAAa,CAAC,oBAAoB,IAAI,CAAC,IAAI,iCAAiC,CAAC,CAAC;IAC1F,CAAC;AACH,CAAC","sourcesContent":["import type { Database } from './registry';\nimport { SqlStackError } from './core/errors';\nimport type { SqlStack, DatabaseEntry } from './stack';\n\n/**\n * Dynamic database families (spec 17): one registration that resolves many\n * concrete databases by key. The provider owns physical mechanics; the\n * family runtime owns identity, leases, bounded caching, and lifecycle.\n */\n\nexport interface DatabaseInspection {\n state: 'closed' | 'open' | 'missing';\n [fact: string]: unknown;\n}\n\nexport interface DatabaseFamilyProvider<K = string> {\n /** Normalize/validate an application key. Must be deterministic and safe. */\n normalizeKey(input: unknown): K;\n /** Serialize a normalized key to the identity string used for routing. */\n keyId?(key: K): string;\n /** Open an EXISTING database. Must fail if it does not exist (never create). */\n open(key: K): Promise<Database>;\n /** Create a NEW database. Must fail if it already exists. */\n create?(key: K): Promise<Database>;\n /** Explicit create-if-missing. */\n ensure?(key: K): Promise<Database>;\n exists?(key: K): Promise<boolean>;\n /** Physically delete the database (handle already closed by the runtime). */\n delete?(key: K): Promise<void>;\n inspect?(key: K): Promise<DatabaseInspection>;\n list?(): AsyncIterable<K>;\n}\n\nexport interface FamilyConfig<K = string> {\n provider: DatabaseFamilyProvider<K>;\n cache?: {\n /** Max concurrently open members (default 16). Leased members never evict. */\n maxOpen?: number;\n };\n}\n\n/** Concrete member identity: owning stack + family registration + key. */\nexport interface FamilyMemberEntry extends DatabaseEntry {\n readonly family: string;\n readonly keyId: string;\n}\n\nexport interface DatabaseLease {\n readonly entry: FamilyMemberEntry;\n release(): Promise<void>;\n}\n\ntype MemberState = {\n entry: FamilyMemberEntry;\n db?: Database;\n opening?: Promise<Database>;\n leases: number;\n lastUsed: number;\n};\n\nfunction unsupported(family: string, op: string): never {\n throw new SqlStackError(\n `Database family \"${family}\" does not support ${op}(): its provider declares no such capability.`\n );\n}\n\nexport class FamilyRuntime<K = string> {\n readonly name: string;\n readonly #stack: SqlStack;\n readonly #provider: DatabaseFamilyProvider<K>;\n readonly #maxOpen: number;\n readonly #members = new Map<string, MemberState>();\n #useTick = 0;\n #closed = false;\n\n constructor(stack: SqlStack, name: string, config: FamilyConfig<K>) {\n this.#stack = stack;\n this.name = name;\n this.#provider = config.provider;\n this.#maxOpen = config.cache?.maxOpen ?? 16;\n }\n\n normalize(input: unknown): { key: K; keyId: string } {\n const key = this.#provider.normalizeKey(input);\n const keyId = this.#provider.keyId ? this.#provider.keyId(key) : String(key);\n return { key, keyId };\n }\n\n /** Stable concrete identity for a key; no I/O. */\n ref(input: unknown): FamilyMemberEntry {\n return this.#member(input).entry;\n }\n\n async exists(input: unknown): Promise<boolean> {\n const { key } = this.normalize(input);\n if (!this.#provider.exists) unsupported(this.name, 'exists');\n return this.#provider.exists(key);\n }\n\n async create(input: unknown): Promise<void> {\n this.#assertOpen();\n const member = this.#member(input);\n if (!this.#provider.create) unsupported(this.name, 'create');\n const db = await this.#provider.create(member.key);\n await db.close();\n }\n\n async ensure(input: unknown): Promise<void> {\n this.#assertOpen();\n const member = this.#member(input);\n if (!this.#provider.ensure) unsupported(this.name, 'ensure');\n const db = await this.#provider.ensure(member.key);\n await db.close();\n }\n\n /** Acquire a lease on an opened (existing) member. */\n async acquire(input: unknown): Promise<DatabaseLease> {\n this.#assertOpen();\n const member = this.#member(input);\n // Count the lease before awaiting the open. Otherwise, while this acquire\n // is suspended, a concurrent release on the same member (or any other)\n // runs eviction, sees zero leases, and closes the handle this acquire is\n // about to return — with maxOpen: 0 that hands the caller a closed member.\n member.leases++;\n try {\n await this.#open(member);\n } catch (err) {\n member.leases = Math.max(0, member.leases - 1);\n this.#evictIfNeeded();\n throw err;\n }\n member.lastUsed = ++this.#useTick;\n this.#evictIfNeeded();\n let released = false;\n return {\n entry: member.entry,\n release: async () => {\n if (released) return;\n released = true;\n member.leases = Math.max(0, member.leases - 1);\n this.#evictIfNeeded();\n },\n };\n }\n\n async with<T>(input: unknown, fn: (entry: FamilyMemberEntry) => Promise<T>): Promise<T> {\n const lease = await this.acquire(input);\n try {\n return await fn(lease.entry);\n } finally {\n await lease.release();\n }\n }\n\n /** Close/evict a member's cached handle; the database itself is preserved. */\n async closeMember(input: unknown): Promise<void> {\n const { keyId } = this.normalize(input);\n const member = this.#members.get(keyId);\n if (!member?.db) return;\n if (member.leases > 0) {\n throw new SqlStackError(\n `Cannot close \"${this.name}/${keyId}\": ${member.leases} lease(s) are active.`\n );\n }\n await this.#closeHandle(member);\n }\n\n /** Physically delete a member. Fails while leased; closes the cached handle first. */\n async deleteMember(input: unknown): Promise<void> {\n this.#assertOpen();\n const member = this.#member(input);\n if (!this.#provider.delete) unsupported(this.name, 'delete');\n if (member.leases > 0) {\n throw new SqlStackError(\n `Cannot delete \"${this.name}/${member.entry.keyId}\": ${member.leases} lease(s) are active.`\n );\n }\n if (member.db) await this.#closeHandle(member);\n await this.#provider.delete(member.key);\n this.#members.delete(member.entry.keyId);\n }\n\n async inspect(input: unknown): Promise<DatabaseInspection> {\n const member = this.#member(input);\n if (!this.#provider.inspect) unsupported(this.name, 'inspect');\n const facts = await this.#provider.inspect(member.key);\n return { ...facts, cached: !!member.db, activeLeases: member.leases };\n }\n\n /** Close every cached handle (root disposal). Databases are preserved. */\n async closeAll(): Promise<void> {\n this.#closed = true;\n const failures: string[] = [];\n for (const member of this.#members.values()) {\n if (!member.db) continue;\n try {\n await this.#closeHandle(member);\n } catch (err: any) {\n failures.push(`\"${this.name}/${member.entry.keyId}\": ${err?.message ?? String(err)}`);\n }\n }\n this.#members.clear();\n if (failures.length) {\n throw new SqlStackError(`Family close failed for ${failures.join(', ')}`);\n }\n }\n\n #member(input: unknown): MemberState & { key: K } {\n const { key, keyId } = this.normalize(input);\n let member = this.#members.get(keyId);\n if (!member) {\n const self = this;\n const entry: FamilyMemberEntry = {\n name: this.name,\n family: this.name,\n keyId,\n owned: true,\n stack: this.#stack,\n get db(): Database {\n const state = self.#members.get(keyId);\n if (!state?.db) {\n throw new SqlStackError(\n `Database family member \"${self.name}/${keyId}\" is not open. ` +\n 'Acquire it through withDatabase(...)/family.with(...) before querying.'\n );\n }\n return state.db;\n },\n };\n member = { entry, leases: 0, lastUsed: 0 };\n this.#members.set(keyId, member);\n }\n return Object.assign(member, { key: this.normalize(input).key });\n }\n\n async #open(member: MemberState & { key: K }): Promise<void> {\n if (member.db) return;\n if (!member.opening) {\n member.opening = this.#provider.open(member.key).finally(() => {\n member.opening = undefined;\n });\n member.opening.catch(() => undefined); // surfaced to awaiting callers\n }\n const db = await member.opening;\n member.db = db;\n }\n\n async #closeHandle(member: MemberState): Promise<void> {\n const db = member.db;\n member.db = undefined;\n if (db) await db.close();\n }\n\n #evictIfNeeded(): void {\n const open = [...this.#members.values()].filter((m) => m.db);\n if (open.length <= this.#maxOpen) return;\n const evictable = open\n .filter((m) => m.leases === 0)\n .sort((a, b) => a.lastUsed - b.lastUsed);\n for (const member of evictable) {\n if ([...this.#members.values()].filter((m) => m.db).length <= this.#maxOpen) break;\n // Fire-and-forget close; eviction failures must not break the acquiring flow.\n void this.#closeHandle(member).catch(() => undefined);\n }\n }\n\n #assertOpen(): void {\n if (this.#closed) {\n throw new SqlStackError(`Database family \"${this.name}\" belongs to a closed SqlStack.`);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"family.js","sourceRoot":"","sources":["../../src/family.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,0CAAsE;AAuEtE,SAAS,WAAW,CAAC,MAAc,EAAE,EAAU;IAC7C,MAAM,IAAI,sBAAa,CACrB,oBAAoB,MAAM,sBAAsB,EAAE,+CAA+C,CAClG,CAAC;AACJ,CAAC;AAED,MAAa,aAAa;IAiBxB,YAAY,KAAe,EAAE,IAAY,EAAE,MAAuB;;QAfzD,uCAAiB;QACjB,0CAAqC;QACrC,yCAAiB;QACjB,+CAAmC;QAC5C,qGAAqG;QAC5F,iCAAW,IAAI,GAAG,EAAuB,EAAC;QACnD,0EAA0E;QAC1E,6EAA6E;QACpE,iCAAW,IAAI,GAAG,EAAsC,EAAC;QACzD,gCAAU,IAAI,oBAAoB,CAAS,CAAC,KAAK,EAAE,EAAE;YAC5D,IAAI,uBAAA,IAAI,8BAAS,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,KAAK,SAAS;gBAAE,uBAAA,IAAI,8BAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnF,CAAC,CAAC,EAAC;QACH,iCAAW,CAAC,EAAC;QACb,gCAAU,KAAK,EAAC;QAGd,uBAAA,IAAI,wBAAU,KAAK,MAAA,CAAC;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,uBAAA,IAAI,2BAAa,MAAM,CAAC,QAAQ,MAAA,CAAC;QACjC,uBAAA,IAAI,0BAAY,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,MAAA,CAAC;QAC5C,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC;QACrC,sDAAsD;QACtD,IAAI,OAAO,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,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M,SAAS,GAAG,IAAI;SACnB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;SAC7B,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;IAC3C,KAAK,MAAM,MAAM,IAAI,SAAS,EAAE,CAAC;QAC/B,IAAI,CAAC,GAAG,uBAAA,IAAI,8BAAS,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,IAAI,uBAAA,IAAI,8BAAS;YAAE,MAAM;QACnF,8EAA8E;QAC9E,KAAK,uBAAA,IAAI,4DAAa,MAAjB,IAAI,EAAc,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;AACH,CAAC;IAGC,IAAI,uBAAA,IAAI,6BAAQ,EAAE,CAAC;QACjB,MAAM,IAAI,sBAAa,CAAC,oBAAoB,IAAI,CAAC,IAAI,iCAAiC,CAAC,CAAC;IAC1F,CAAC;AACH,CAAC","sourcesContent":["/// <reference lib=\"es2021.weakref\" />\nimport type { Database } from './registry';\nimport { SqlStackError, FamilyOpenTimeoutError } from './core/errors';\nimport type { SqlStack, DatabaseEntry } from './stack';\n\n/**\n * Dynamic database families (spec 17): one registration that resolves many\n * concrete databases by key. The provider owns physical mechanics; the\n * family runtime owns identity, leases, bounded caching, and lifecycle.\n */\n\nexport interface DatabaseInspection {\n state: 'closed' | 'open' | 'missing';\n [fact: string]: unknown;\n}\n\nexport interface DatabaseFamilyProvider<K = string> {\n /** Normalize/validate an application key. Must be deterministic and safe. */\n normalizeKey(input: unknown): K;\n /** Serialize a normalized key to the identity string used for routing. */\n keyId?(key: K): string;\n /** Open an EXISTING database. Must fail if it does not exist (never create). */\n open(key: K): Promise<Database>;\n /** Create a NEW database. Must fail if it already exists. */\n create?(key: K): Promise<Database>;\n /** Explicit create-if-missing. */\n ensure?(key: K): Promise<Database>;\n exists?(key: K): Promise<boolean>;\n /** Physically delete the database (handle already closed by the runtime). */\n delete?(key: K): Promise<void>;\n inspect?(key: K): Promise<DatabaseInspection>;\n list?(): AsyncIterable<K>;\n}\n\nexport interface FamilyConfig<K = string> {\n provider: DatabaseFamilyProvider<K>;\n cache?: {\n /** Max concurrently open members (default 16). Leased members never evict. */\n maxOpen?: number;\n };\n /**\n * Max ms to wait for provider.open(). On expiry waiting acquires reject with\n * FamilyOpenTimeoutError and a handle that arrives later is closed.\n * Default: no timeout.\n */\n openTimeoutMs?: number;\n}\n\n/** Concrete member identity: owning stack + family registration + key. */\nexport interface FamilyMemberEntry extends DatabaseEntry {\n readonly family: string;\n readonly keyId: string;\n}\n\nexport interface DatabaseLease {\n readonly entry: FamilyMemberEntry;\n release(): Promise<void>;\n}\n\ntype MemberState = {\n entry: FamilyMemberEntry;\n db?: Database;\n opening?: OpenAttempt;\n leases: number;\n lastUsed: number;\n};\n\n/** One provider.open() call; settles exactly once (open, error, timeout, or close). */\ntype OpenAttempt = {\n promise: Promise<Database>;\n abandon(reason: Error): void;\n};\n\nfunction unsupported(family: string, op: string): never {\n throw new SqlStackError(\n `Database family \"${family}\" does not support ${op}(): its provider declares no such capability.`\n );\n}\n\nexport class FamilyRuntime<K = string> {\n readonly name: string;\n readonly #stack: SqlStack;\n readonly #provider: DatabaseFamilyProvider<K>;\n readonly #maxOpen: number;\n readonly #openTimeoutMs: number | undefined;\n /** Live records only: a record exists while it has a lease, an open handle, or an open in flight. */\n readonly #members = new Map<string, MemberState>();\n // Entry identity outlives a pruned record for as long as anyone holds the\n // entry (transactions key by entry object); a live record holds it strongly.\n readonly #entries = new Map<string, WeakRef<FamilyMemberEntry>>();\n readonly #reaper = new FinalizationRegistry<string>((keyId) => {\n if (this.#entries.get(keyId)?.deref() === undefined) this.#entries.delete(keyId);\n });\n #useTick = 0;\n #closed = false;\n\n constructor(stack: SqlStack, name: string, config: FamilyConfig<K>) {\n this.#stack = stack;\n this.name = name;\n this.#provider = config.provider;\n this.#maxOpen = config.cache?.maxOpen ?? 16;\n const timeout = config.openTimeoutMs;\n // setTimeout fires after 1ms for delays above 2^31-1.\n if (timeout !== undefined && !(Number.isFinite(timeout) && timeout > 0 && timeout <= 2_147_483_647)) {\n throw new SqlStackError(\n `Database family \"${name}\": openTimeoutMs must be a positive number of milliseconds ` +\n `(max 2147483647), got ${String(timeout)}.`\n );\n }\n this.#openTimeoutMs = timeout;\n }\n\n normalize(input: unknown): { key: K; keyId: string } {\n const key = this.#provider.normalizeKey(input);\n const keyId = this.#provider.keyId ? this.#provider.keyId(key) : String(key);\n return { key, keyId };\n }\n\n /** Stable concrete identity for a key; no I/O. */\n ref(input: unknown): FamilyMemberEntry {\n return this.#entry(this.normalize(input).keyId);\n }\n\n async exists(input: unknown): Promise<boolean> {\n const { key } = this.normalize(input);\n if (!this.#provider.exists) unsupported(this.name, 'exists');\n return this.#provider.exists(key);\n }\n\n async create(input: unknown): Promise<void> {\n this.#assertOpen();\n const { key } = this.normalize(input);\n if (!this.#provider.create) unsupported(this.name, 'create');\n const db = await this.#provider.create(key);\n await db.close();\n }\n\n async ensure(input: unknown): Promise<void> {\n this.#assertOpen();\n const { key } = this.normalize(input);\n if (!this.#provider.ensure) unsupported(this.name, 'ensure');\n const db = await this.#provider.ensure(key);\n await db.close();\n }\n\n /** Acquire a lease on an opened (existing) member. */\n async acquire(input: unknown): Promise<DatabaseLease> {\n this.#assertOpen();\n const { key, keyId } = this.normalize(input);\n const member = this.#record(keyId);\n // Count the lease before awaiting the open. Otherwise, while this acquire\n // is suspended, a concurrent release on the same member (or any other)\n // runs eviction, sees zero leases, and closes the handle this acquire is\n // about to return — with maxOpen: 0 that hands the caller a closed member.\n member.leases++;\n try {\n await this.#open(member, key);\n // closeAll() may have run while this acquire was suspended (even on an\n // already-cached member). It owns every handle from then on; never hand\n // out a lease on a closed family.\n this.#assertOpen();\n } catch (err) {\n member.leases = Math.max(0, member.leases - 1);\n this.#evictIfNeeded();\n this.#pruneIfIdle(member);\n throw err;\n }\n member.lastUsed = ++this.#useTick;\n this.#evictIfNeeded();\n let released = false;\n return {\n entry: member.entry,\n release: async () => {\n if (released) return;\n released = true;\n member.leases = Math.max(0, member.leases - 1);\n this.#evictIfNeeded();\n this.#pruneIfIdle(member);\n },\n };\n }\n\n async with<T>(input: unknown, fn: (entry: FamilyMemberEntry) => Promise<T>): Promise<T> {\n const lease = await this.acquire(input);\n try {\n return await fn(lease.entry);\n } finally {\n await lease.release();\n }\n }\n\n /** Close/evict a member's cached handle; the database itself is preserved. */\n async closeMember(input: unknown): Promise<void> {\n const { keyId } = this.normalize(input);\n const member = this.#members.get(keyId);\n if (!member?.db) return;\n if (member.leases > 0) {\n throw new SqlStackError(\n `Cannot close \"${this.name}/${keyId}\": ${member.leases} lease(s) are active.`\n );\n }\n await this.#closeHandle(member);\n }\n\n /** Physically delete a member. Fails while leased; closes the cached handle first. */\n async deleteMember(input: unknown): Promise<void> {\n this.#assertOpen();\n const { key, keyId } = this.normalize(input);\n if (!this.#provider.delete) unsupported(this.name, 'delete');\n const member = this.#members.get(keyId);\n if (member && member.leases > 0) {\n throw new SqlStackError(\n `Cannot delete \"${this.name}/${keyId}\": ${member.leases} lease(s) are active.`\n );\n }\n if (member?.db) await this.#closeHandle(member);\n await this.#provider.delete(key);\n }\n\n async inspect(input: unknown): Promise<DatabaseInspection> {\n const { key, keyId } = this.normalize(input);\n if (!this.#provider.inspect) unsupported(this.name, 'inspect');\n const facts = await this.#provider.inspect(key);\n const member = this.#members.get(keyId);\n return { ...facts, cached: !!member?.db, activeLeases: member?.leases ?? 0 };\n }\n\n /** Close every cached handle (root disposal). Databases are preserved. */\n async closeAll(): Promise<void> {\n this.#closed = true;\n // Abandon in-flight opens before any await: waiters reject, and a handle\n // that lands later is closed by its attempt instead of leaking.\n for (const member of this.#members.values()) {\n member.opening?.abandon(\n new SqlStackError(\n `Database family \"${this.name}\" was closed while \"${this.name}/${member.entry.keyId}\" was opening.`\n )\n );\n }\n const failures: string[] = [];\n for (const member of this.#members.values()) {\n if (!member.db) continue;\n try {\n await this.#closeHandle(member);\n } catch (err: any) {\n failures.push(`\"${this.name}/${member.entry.keyId}\": ${err?.message ?? String(err)}`);\n }\n }\n this.#members.clear();\n this.#entries.clear();\n if (failures.length) {\n throw new SqlStackError(`Family close failed for ${failures.join(', ')}`);\n }\n }\n\n /** The member's stable entry: the live one if anyone still holds it, else a new one. */\n #entry(keyId: string): FamilyMemberEntry {\n let entry = this.#entries.get(keyId)?.deref();\n if (!entry) {\n const self = this;\n entry = {\n name: this.name,\n family: this.name,\n keyId,\n owned: true,\n stack: this.#stack,\n get db(): Database {\n const state = self.#members.get(keyId);\n if (!state?.db) {\n throw new SqlStackError(\n `Database family member \"${self.name}/${keyId}\" is not open. ` +\n 'Acquire it through withDatabase(...)/family.with(...) before querying.'\n );\n }\n return state.db;\n },\n };\n this.#entries.set(keyId, new WeakRef(entry));\n this.#reaper.register(entry, keyId);\n }\n return entry;\n }\n\n /** Get or create the live record for a key. Only acquire creates records. */\n #record(keyId: string): MemberState {\n let member = this.#members.get(keyId);\n if (!member) {\n member = { entry: this.#entry(keyId), leases: 0, lastUsed: 0 };\n this.#members.set(keyId, member);\n }\n return member;\n }\n\n /** Drop a record with no lease, handle, or open in flight (never a newer record for the key). */\n #pruneIfIdle(member: MemberState): void {\n if (member.leases > 0 || member.db || member.opening) return;\n if (this.#members.get(member.entry.keyId) === member) this.#members.delete(member.entry.keyId);\n }\n\n async #open(member: MemberState, key: K): Promise<void> {\n if (member.db) return;\n member.opening ??= this.#startOpen(member, key);\n await member.opening.promise;\n }\n\n #startOpen(member: MemberState, key: K): OpenAttempt {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let resolve!: (db: Database) => void;\n let reject!: (err: unknown) => void;\n const promise = new Promise<Database>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n promise.catch(() => undefined); // surfaced to awaiting callers\n\n // Exactly one of open/error/timeout/close wins; later outcomes are no-ops.\n const settle = (): boolean => {\n if (settled) return false;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n if (member.opening === attempt) member.opening = undefined; // never clobber a newer attempt\n return true;\n };\n const attempt: OpenAttempt = {\n promise,\n abandon: (reason) => {\n if (settle()) reject(reason);\n },\n };\n\n if (this.#openTimeoutMs !== undefined) {\n const ms = this.#openTimeoutMs;\n timer = setTimeout(\n () => attempt.abandon(new FamilyOpenTimeoutError(this.name, member.entry.keyId, ms)),\n ms\n );\n }\n\n let pending: Promise<Database>;\n try {\n pending = Promise.resolve(this.#provider.open(key));\n } catch (err) {\n pending = Promise.reject(err);\n }\n pending.then(\n (db) => {\n if (!settle()) {\n // Late arrival (timed out or family closed): nobody owns this handle.\n void Promise.resolve()\n .then(() => db.close())\n .catch(() => undefined);\n return;\n }\n member.db = db; // single publication point, while waiters still hold leases\n resolve(db);\n },\n (err) => {\n if (settle()) reject(err);\n }\n );\n return attempt;\n }\n\n async #closeHandle(member: MemberState): Promise<void> {\n const db = member.db;\n member.db = undefined;\n this.#pruneIfIdle(member);\n if (db) await db.close();\n }\n\n #evictIfNeeded(): void {\n // Once closed, closeAll owns every handle: it awaits the close and reports failures.\n if (this.#closed) return;\n const open = [...this.#members.values()].filter((m) => m.db);\n if (open.length <= this.#maxOpen) return;\n const evictable = open\n .filter((m) => m.leases === 0)\n .sort((a, b) => a.lastUsed - b.lastUsed);\n for (const member of evictable) {\n if ([...this.#members.values()].filter((m) => m.db).length <= this.#maxOpen) break;\n // Fire-and-forget close; eviction failures must not break the acquiring flow.\n void this.#closeHandle(member).catch(() => undefined);\n }\n }\n\n #assertOpen(): void {\n if (this.#closed) {\n throw new SqlStackError(`Database family \"${this.name}\" belongs to a closed SqlStack.`);\n }\n }\n}\n"]}
|
|
@@ -16,6 +16,10 @@ export type BindingFrame = {
|
|
|
16
16
|
readonly keyId: string;
|
|
17
17
|
/** Acquired lazily on first database resolution inside the frame. */
|
|
18
18
|
lease?: DatabaseLease;
|
|
19
|
+
/** Single-flight memo of the in-flight acquire; cleared if it rejects. */
|
|
20
|
+
leasing?: Promise<DatabaseLease>;
|
|
21
|
+
/** Set when withDatabase's callback has settled; no resolution may use the frame after. */
|
|
22
|
+
closed?: boolean;
|
|
19
23
|
};
|
|
20
24
|
export declare function currentBinding(stack: SqlStack, family: string): BindingFrame | undefined;
|
|
21
25
|
export declare function runWithBinding<T>(frame: BindingFrame, fn: () => T): T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"familyBinding.d.ts","sourceRoot":"","sources":["../../src/familyBinding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,qEAAqE;IACrE,KAAK,CAAC,EAAE,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"familyBinding.d.ts","sourceRoot":"","sources":["../../src/familyBinding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,qEAAqE;IACrE,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,0EAA0E;IAC1E,OAAO,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IACjC,2FAA2F;IAC3F,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAIF,wBAAgB,cAAc,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAQxF;AAED,wBAAgB,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAGrE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"familyBinding.js","sourceRoot":"","sources":["../../src/familyBinding.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"familyBinding.js","sourceRoot":"","sources":["../../src/familyBinding.ts"],"names":[],"mappings":";;AA4BA,wCAQC;AAED,wCAGC;AAzCD,uDAAqD;AA0BrD,MAAM,GAAG,GAAG,IAAI,oCAAiB,EAA2B,CAAC;AAE7D,SAAgB,cAAc,CAAC,KAAe,EAAE,MAAc;IAC5D,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC9B,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,KAAK,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC5C,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM;YAAE,OAAO,KAAK,CAAC;IACrE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAgB,cAAc,CAAI,KAAmB,EAAE,EAAW;IAChE,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC;IACpC,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;AACzC,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { SqlStack } from './stack';\nimport type { DatabaseLease } from './family';\n\n/**\n * SQLStack-owned flow-local family binding (spec 17 §10-11).\n *\n * This carries WHICH concrete member of a dynamic family is selected for the\n * current execution flow. It is deliberately separate from the IoC execution\n * context (which owns root identity) and from transaction state. Frames are\n * keyed by SqlStack instance, so two roots binding the same family name can\n * never observe each other's selection.\n */\nexport type BindingFrame = {\n readonly stack: SqlStack;\n readonly family: string;\n readonly keyInput: unknown;\n readonly keyId: string;\n /** Acquired lazily on first database resolution inside the frame. */\n lease?: DatabaseLease;\n /** Single-flight memo of the in-flight acquire; cleared if it rejects. */\n leasing?: Promise<DatabaseLease>;\n /** Set when withDatabase's callback has settled; no resolution may use the frame after. */\n closed?: boolean;\n};\n\nconst als = new AsyncLocalStorage<readonly BindingFrame[]>();\n\nexport function currentBinding(stack: SqlStack, family: string): BindingFrame | undefined {\n const frames = als.getStore();\n if (!frames) return undefined;\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n if (frame.stack === stack && frame.family === family) return frame;\n }\n return undefined;\n}\n\nexport function runWithBinding<T>(frame: BindingFrame, fn: () => T): T {\n const frames = als.getStore() ?? [];\n return als.run([...frames, frame], fn);\n}\n"]}
|
package/dist/cjs/stack.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stack.d.ts","sourceRoot":"","sources":["../../src/stack.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AASnD,OAAO,EAA8B,KAAK,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C,EAAE,aAAa,CAAC,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,CAAA;KAAE,GAC1E,IAAI;IAaP,QAAQ,IAAI,WAAW,GAAG,SAAS;IAInC,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED;;;;OAIG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgCtB,0EAA0E;IAC1E,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAezB"}
|
package/dist/cjs/stack.js
CHANGED
|
@@ -51,6 +51,11 @@ const errors_1 = require("./core/errors");
|
|
|
51
51
|
const resources_1 = require("./core/resources");
|
|
52
52
|
const family_1 = require("./family");
|
|
53
53
|
const familyBinding_1 = require("./familyBinding");
|
|
54
|
+
function bindingEnded(family, keyId) {
|
|
55
|
+
return new errors_1.SqlStackError(`SQLStack database family "${family}" binding for "${keyId}" has ended: ` +
|
|
56
|
+
'withDatabase(...) already settled. A query started inside the callback ' +
|
|
57
|
+
'was not awaited before it returned.');
|
|
58
|
+
}
|
|
54
59
|
/**
|
|
55
60
|
* Environment-owned SQLStack runtime (spec 16 §12-13, repo spec 19 §3-5).
|
|
56
61
|
*
|
|
@@ -195,6 +200,12 @@ class SqlStack {
|
|
|
195
200
|
return await (0, familyBinding_1.runWithBinding)(frame, fn);
|
|
196
201
|
}
|
|
197
202
|
finally {
|
|
203
|
+
// Close the frame first so no new resolution can lease through it, then
|
|
204
|
+
// drain any acquire still in flight so its lease is released here.
|
|
205
|
+
frame.closed = true;
|
|
206
|
+
const inFlight = frame.leasing;
|
|
207
|
+
if (inFlight)
|
|
208
|
+
await inFlight.then(() => undefined, () => undefined);
|
|
198
209
|
await frame.lease?.release();
|
|
199
210
|
}
|
|
200
211
|
}
|
|
@@ -224,10 +235,24 @@ class SqlStack {
|
|
|
224
235
|
`orchestration boundary with sqlStack.withDatabase("${key}", key, ...) ` +
|
|
225
236
|
'or acquire a member explicitly via sqlStack.family(...).with(...).');
|
|
226
237
|
}
|
|
227
|
-
if (
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
238
|
+
if (frame.closed)
|
|
239
|
+
throw bindingEnded(key, frame.keyId);
|
|
240
|
+
if (frame.lease)
|
|
241
|
+
return frame.lease.entry;
|
|
242
|
+
// Single-flight: concurrent first resolutions in one frame share one
|
|
243
|
+
// acquire, so exactly one lease is taken and released at scope end.
|
|
244
|
+
frame.leasing ?? (frame.leasing = fam.acquire(frame.keyInput).then((lease) => {
|
|
245
|
+
frame.lease = lease;
|
|
246
|
+
return lease;
|
|
247
|
+
}, (err) => {
|
|
248
|
+
// A failed acquire leaves nothing to release; allow a retry.
|
|
249
|
+
frame.leasing = undefined;
|
|
250
|
+
throw err;
|
|
251
|
+
}));
|
|
252
|
+
const lease = await frame.leasing;
|
|
253
|
+
if (frame.closed)
|
|
254
|
+
throw bindingEnded(key, frame.keyId);
|
|
255
|
+
return lease.entry;
|
|
231
256
|
}
|
|
232
257
|
}
|
|
233
258
|
return this.getEntry(name);
|