@webiny/api-core-sql 6.6.0-alpha.1 → 6.6.0-alpha.10
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/ApiCoreSqlFeature.d.ts +5 -0
- package/ApiCoreSqlFeature.js +5 -4
- package/ApiCoreSqlFeature.js.map +1 -1
- package/TableManager.d.ts +17 -0
- package/TableManager.js +35 -2
- package/TableManager.js.map +1 -1
- package/adminUsers/index.js +20 -17
- package/adminUsers/index.js.map +1 -1
- package/connectionRetry/index.d.ts +3 -0
- package/connectionRetry/index.js +2 -0
- package/connectionRetry/isConnectionError.d.ts +1 -0
- package/connectionRetry/isConnectionError.js +28 -0
- package/connectionRetry/isConnectionError.js.map +1 -0
- package/connectionRetry/withPgConnectionRetry.d.ts +49 -0
- package/connectionRetry/withPgConnectionRetry.js +175 -0
- package/connectionRetry/withPgConnectionRetry.js.map +1 -0
- package/index.d.ts +3 -0
- package/index.js +3 -0
- package/index.js.map +1 -1
- package/keyValueStore/index.js +160 -21
- package/keyValueStore/index.js.map +1 -1
- package/package.json +8 -7
- package/schemaManaged.d.ts +8 -0
- package/schemaManaged.js +4 -0
- package/schemaManaged.js.map +1 -0
- package/security/index.js +47 -47
- package/security/index.js.map +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.d.ts +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.js +4 -6
- package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
- package/tenancy/index.js +9 -9
- package/tenancy/index.js.map +1 -1
package/ApiCoreSqlFeature.d.ts
CHANGED
|
@@ -6,6 +6,11 @@ export interface ApiCoreSqlConfig {
|
|
|
6
6
|
/**
|
|
7
7
|
* Registers the SQL implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register
|
|
8
8
|
* resolves + builds it. Mirrors ApiCoreDdbFeature.
|
|
9
|
+
*
|
|
10
|
+
* The storage operations are built once, here, and `create()` hands out the same object. It runs on
|
|
11
|
+
* every request (ApiCoreFeature is per-request), and building per request created a new TableManager
|
|
12
|
+
* each time: every one stayed in the global test registry, so a long-running server leaked one per
|
|
13
|
+
* request, and each started with no verified tables. The operations hold no per-request state.
|
|
9
14
|
*/
|
|
10
15
|
export declare const ApiCoreSqlFeature: {
|
|
11
16
|
name: string;
|
package/ApiCoreSqlFeature.js
CHANGED
|
@@ -4,11 +4,12 @@ import { createApiCoreSql } from "./createApiCoreSql.js";
|
|
|
4
4
|
const ApiCoreSqlFeature = createFeature({
|
|
5
5
|
name: "ApiCoreSql",
|
|
6
6
|
register (container, { knex, tableNamePrefix }) {
|
|
7
|
+
const storageOperations = createApiCoreSql({
|
|
8
|
+
knex,
|
|
9
|
+
tableNamePrefix
|
|
10
|
+
});
|
|
7
11
|
container.registerInstance(ApiCoreStorageOperationsFactory, {
|
|
8
|
-
create: ()=>
|
|
9
|
-
knex,
|
|
10
|
-
tableNamePrefix
|
|
11
|
-
})
|
|
12
|
+
create: ()=>storageOperations
|
|
12
13
|
});
|
|
13
14
|
}
|
|
14
15
|
});
|
package/ApiCoreSqlFeature.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApiCoreSqlFeature.js","sources":["../src/ApiCoreSqlFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { Knex } from \"knex\";\nimport { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreSql } from \"./createApiCoreSql.js\";\n\nexport interface ApiCoreSqlConfig {\n knex: Knex;\n tableNamePrefix?: string;\n}\n\n/**\n * Registers the SQL implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors ApiCoreDdbFeature.\n */\nexport const ApiCoreSqlFeature = createFeature<ApiCoreSqlConfig>({\n name: \"ApiCoreSql\",\n register(container, { knex, tableNamePrefix }) {\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: () =>
|
|
1
|
+
{"version":3,"file":"ApiCoreSqlFeature.js","sources":["../src/ApiCoreSqlFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { Knex } from \"knex\";\nimport { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreSql } from \"./createApiCoreSql.js\";\n\nexport interface ApiCoreSqlConfig {\n knex: Knex;\n tableNamePrefix?: string;\n}\n\n/**\n * Registers the SQL implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors ApiCoreDdbFeature.\n *\n * The storage operations are built once, here, and `create()` hands out the same object. It runs on\n * every request (ApiCoreFeature is per-request), and building per request created a new TableManager\n * each time: every one stayed in the global test registry, so a long-running server leaked one per\n * request, and each started with no verified tables. The operations hold no per-request state.\n */\nexport const ApiCoreSqlFeature = createFeature<ApiCoreSqlConfig>({\n name: \"ApiCoreSql\",\n register(container, { knex, tableNamePrefix }) {\n const storageOperations = createApiCoreSql({ knex, tableNamePrefix });\n\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: () => storageOperations\n });\n }\n});\n"],"names":["ApiCoreSqlFeature","createFeature","container","knex","tableNamePrefix","storageOperations","createApiCoreSql","ApiCoreStorageOperationsFactory"],"mappings":";;;AAmBO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,IAAI,EAAEC,eAAe,EAAE;QACzC,MAAMC,oBAAoBC,iBAAiB;YAAEH;YAAMC;QAAgB;QAEnEF,UAAU,gBAAgB,CAACK,iCAAiC;YACxD,QAAQ,IAAMF;QAClB;IACJ;AACJ"}
|
package/TableManager.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
|
+
type TableCreator = (table: Knex.CreateTableBuilder) => void;
|
|
2
3
|
interface ITableManager {
|
|
3
4
|
reset(): void;
|
|
4
5
|
resolve(tableName: string): string;
|
|
@@ -8,9 +9,25 @@ export declare class TableManager implements ITableManager {
|
|
|
8
9
|
private readonly knex;
|
|
9
10
|
private readonly prefix;
|
|
10
11
|
private readonly verified;
|
|
12
|
+
private readonly pending;
|
|
13
|
+
private readonly defined;
|
|
11
14
|
constructor(knex: Knex, prefix?: string);
|
|
15
|
+
/**
|
|
16
|
+
* Creates the declared tables of every manager in this process that uses `knex`. Deploy-time
|
|
17
|
+
* schema setup builds the storage operations (which declare their tables), then calls this.
|
|
18
|
+
* Managers of other knex instances (an earlier setup in a warm process) are left alone.
|
|
19
|
+
*/
|
|
20
|
+
static setupAll(knex: Knex): Promise<void>;
|
|
12
21
|
reset(): void;
|
|
22
|
+
/**
|
|
23
|
+
* Declares a table and returns the function that ensures it on first use. Declared tables are
|
|
24
|
+
* created together by `setup()` (deploy-time schema setup).
|
|
25
|
+
*/
|
|
26
|
+
define(tableName: string, creator: TableCreator): () => Promise<void>;
|
|
27
|
+
setup(): Promise<void>;
|
|
13
28
|
resolve(tableName: string): string;
|
|
14
29
|
ensure(tableName: string, creator: (table: Knex.CreateTableBuilder) => void): Promise<void>;
|
|
30
|
+
private ensureTable;
|
|
31
|
+
private createTable;
|
|
15
32
|
}
|
|
16
33
|
export {};
|
package/TableManager.js
CHANGED
|
@@ -1,25 +1,58 @@
|
|
|
1
|
+
import { isSqlSchemaManaged } from "./schemaManaged.js";
|
|
1
2
|
class TableManager {
|
|
2
3
|
constructor(knex, prefix = ""){
|
|
3
4
|
this.verified = new Set();
|
|
5
|
+
this.pending = new Map();
|
|
6
|
+
this.defined = new Map();
|
|
4
7
|
this.knex = knex;
|
|
5
8
|
this.prefix = prefix ? `${prefix}_` : "";
|
|
6
9
|
const g = globalThis;
|
|
7
10
|
const managers = g.__sqlTableManagers ??= [];
|
|
8
11
|
managers.push(this);
|
|
9
12
|
}
|
|
13
|
+
static async setupAll(knex) {
|
|
14
|
+
const managers = globalThis.__sqlTableManagers ?? [];
|
|
15
|
+
for (const manager of managers)if (manager instanceof TableManager && manager.knex === knex) await manager.setup();
|
|
16
|
+
}
|
|
10
17
|
reset() {
|
|
11
18
|
this.verified.clear();
|
|
19
|
+
this.pending.clear();
|
|
20
|
+
}
|
|
21
|
+
define(tableName, creator) {
|
|
22
|
+
this.defined.set(tableName, creator);
|
|
23
|
+
return ()=>this.ensure(tableName, creator);
|
|
24
|
+
}
|
|
25
|
+
async setup() {
|
|
26
|
+
for (const [tableName, creator] of this.defined)await this.ensureTable(this.resolve(tableName), creator);
|
|
12
27
|
}
|
|
13
28
|
resolve(tableName) {
|
|
14
29
|
return `${this.prefix}${tableName}`;
|
|
15
30
|
}
|
|
16
31
|
async ensure(tableName, creator) {
|
|
17
32
|
const resolved = this.resolve(tableName);
|
|
18
|
-
if (this.verified.has(resolved)) return;
|
|
33
|
+
if (this.verified.has(resolved) || isSqlSchemaManaged()) return;
|
|
34
|
+
const pending = this.pending.get(resolved);
|
|
35
|
+
if (pending) return pending;
|
|
36
|
+
const check = this.ensureTable(resolved, creator).finally(()=>{
|
|
37
|
+
if (this.pending.get(resolved) === check) this.pending.delete(resolved);
|
|
38
|
+
});
|
|
39
|
+
this.pending.set(resolved, check);
|
|
40
|
+
return check;
|
|
41
|
+
}
|
|
42
|
+
async ensureTable(resolved, creator) {
|
|
19
43
|
const exists = await this.knex.schema.hasTable(resolved);
|
|
20
|
-
if (!exists) await this.
|
|
44
|
+
if (!exists) await this.createTable(resolved, creator);
|
|
21
45
|
this.verified.add(resolved);
|
|
22
46
|
}
|
|
47
|
+
async createTable(resolved, creator) {
|
|
48
|
+
try {
|
|
49
|
+
await this.knex.schema.createTable(resolved, creator);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
const exists = await this.knex.schema.hasTable(resolved);
|
|
52
|
+
if (exists) return;
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
23
56
|
}
|
|
24
57
|
export { TableManager };
|
|
25
58
|
|
package/TableManager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TableManager.js","sources":["../src/TableManager.ts"],"sourcesContent":["import type { Knex } from \"knex\";\n\ninterface ITableManager {\n reset(): void;\n resolve(tableName: string): string;\n ensure(tableName: string, creator: (table: Knex.CreateTableBuilder) => void): Promise<void>;\n}\n\nexport class TableManager implements ITableManager {\n private readonly knex: Knex;\n private readonly prefix: string;\n private readonly verified = new Set<string>();\n\n constructor(knex: Knex, prefix: string = \"\") {\n this.knex = knex;\n this.prefix = prefix ? `${prefix}_` : \"\";\n\n const g = globalThis as Record<string, unknown>;\n const managers = (g.__sqlTableManagers ??= []) as ITableManager[];\n managers.push(this);\n }\n\n public reset(): void {\n this.verified.clear();\n }\n\n public resolve(tableName: string): string {\n return `${this.prefix}${tableName}`;\n }\n\n public async ensure(\n tableName: string,\n creator: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n const resolved = this.resolve(tableName);\n\n if (this.verified.has(resolved)) {\n return;\n }\n\n const exists = await this.knex.schema.hasTable(resolved);\n\n if (!exists) {\n await this.
|
|
1
|
+
{"version":3,"file":"TableManager.js","sources":["../src/TableManager.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { isSqlSchemaManaged } from \"./schemaManaged.js\";\n\ntype TableCreator = (table: Knex.CreateTableBuilder) => void;\n\ninterface ITableManager {\n reset(): void;\n resolve(tableName: string): string;\n ensure(tableName: string, creator: (table: Knex.CreateTableBuilder) => void): Promise<void>;\n}\n\nexport class TableManager implements ITableManager {\n private readonly knex: Knex;\n private readonly prefix: string;\n private readonly verified = new Set<string>();\n private readonly pending = new Map<string, Promise<void>>();\n /* Tables declared by the storage operations using this manager, for deploy-time setup. */\n private readonly defined = new Map<string, TableCreator>();\n\n constructor(knex: Knex, prefix: string = \"\") {\n this.knex = knex;\n this.prefix = prefix ? `${prefix}_` : \"\";\n\n const g = globalThis as Record<string, unknown>;\n const managers = (g.__sqlTableManagers ??= []) as ITableManager[];\n managers.push(this);\n }\n\n /**\n * Creates the declared tables of every manager in this process that uses `knex`. Deploy-time\n * schema setup builds the storage operations (which declare their tables), then calls this.\n * Managers of other knex instances (an earlier setup in a warm process) are left alone.\n */\n public static async setupAll(knex: Knex): Promise<void> {\n const managers = ((globalThis as Record<string, unknown>).__sqlTableManagers ??\n []) as ITableManager[];\n for (const manager of managers) {\n if (manager instanceof TableManager && manager.knex === knex) {\n await manager.setup();\n }\n }\n }\n\n public reset(): void {\n this.verified.clear();\n this.pending.clear();\n }\n\n /**\n * Declares a table and returns the function that ensures it on first use. Declared tables are\n * created together by `setup()` (deploy-time schema setup).\n */\n public define(tableName: string, creator: TableCreator): () => Promise<void> {\n this.defined.set(tableName, creator);\n return () => this.ensure(tableName, creator);\n }\n\n /* Creates every declared table that doesn't exist yet. Runs at deploy time. */\n public async setup(): Promise<void> {\n for (const [tableName, creator] of this.defined) {\n await this.ensureTable(this.resolve(tableName), creator);\n }\n }\n\n public resolve(tableName: string): string {\n return `${this.prefix}${tableName}`;\n }\n\n public async ensure(\n tableName: string,\n creator: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n const resolved = this.resolve(tableName);\n\n if (this.verified.has(resolved) || isSqlSchemaManaged()) {\n return;\n }\n\n // One TableManager serves every request, so concurrent first requests share a single\n // hasTable+createTable instead of racing into \"table already exists\". Cleared on failure so\n // a later call can retry.\n const pending = this.pending.get(resolved);\n if (pending) {\n return pending;\n }\n\n const check = this.ensureTable(resolved, creator).finally(() => {\n // Only remove our own entry: after reset() a newer check may own this table's slot.\n if (this.pending.get(resolved) === check) {\n this.pending.delete(resolved);\n }\n });\n this.pending.set(resolved, check);\n\n return check;\n }\n\n private async ensureTable(\n resolved: string,\n creator: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n const exists = await this.knex.schema.hasTable(resolved);\n\n if (!exists) {\n await this.createTable(resolved, creator);\n }\n\n this.verified.add(resolved);\n }\n\n private async createTable(\n resolved: string,\n creator: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n try {\n await this.knex.schema.createTable(resolved, creator);\n } catch (err) {\n // Another process (or connection) may have created it in the meantime. If it exists now,\n // that's success; otherwise the failure is real.\n const exists = await this.knex.schema.hasTable(resolved);\n if (exists) {\n return;\n }\n throw err;\n }\n }\n}\n"],"names":["TableManager","knex","prefix","Set","Map","g","globalThis","managers","manager","tableName","creator","resolved","isSqlSchemaManaged","pending","check","exists","err"],"mappings":";AAWO,MAAMA;IAQT,YAAYC,IAAU,EAAEC,SAAiB,EAAE,CAAE;aAL5B,QAAQ,GAAG,IAAIC;aACf,OAAO,GAAG,IAAIC;QACyD,KACvE,OAAO,GAAG,IAAIA;QAG3B,IAAI,CAAC,IAAI,GAAGH;QACZ,IAAI,CAAC,MAAM,GAAGC,SAAS,GAAGA,OAAO,CAAC,CAAC,GAAG;QAEtC,MAAMG,IAAIC;QACV,MAAMC,WAAYF,EAAE,kBAAkB,KAAK,EAAE;QAC7CE,SAAS,IAAI,CAAC,IAAI;IACtB;IAOA,aAAoB,SAASN,IAAU,EAAiB;QACpD,MAAMM,WAAaD,WAAuC,kBAAkB,IACxE,EAAE;QACN,KAAK,MAAME,WAAWD,SAClB,IAAIC,mBAAmBR,gBAAgBQ,QAAQ,IAAI,KAAKP,MACpD,MAAMO,QAAQ,KAAK;IAG/B;IAEO,QAAc;QACjB,IAAI,CAAC,QAAQ,CAAC,KAAK;QACnB,IAAI,CAAC,OAAO,CAAC,KAAK;IACtB;IAMO,OAAOC,SAAiB,EAAEC,OAAqB,EAAuB;QACzE,IAAI,CAAC,OAAO,CAAC,GAAG,CAACD,WAAWC;QAC5B,OAAO,IAAM,IAAI,CAAC,MAAM,CAACD,WAAWC;IACxC;IAGA,MAAa,QAAuB;QAChC,KAAK,MAAM,CAACD,WAAWC,QAAQ,IAAI,IAAI,CAAC,OAAO,CAC3C,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAACD,YAAYC;IAExD;IAEO,QAAQD,SAAiB,EAAU;QACtC,OAAO,GAAG,IAAI,CAAC,MAAM,GAAGA,WAAW;IACvC;IAEA,MAAa,OACTA,SAAiB,EACjBC,OAAiD,EACpC;QACb,MAAMC,WAAW,IAAI,CAAC,OAAO,CAACF;QAE9B,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAACE,aAAaC,sBAC/B;QAMJ,MAAMC,UAAU,IAAI,CAAC,OAAO,CAAC,GAAG,CAACF;QACjC,IAAIE,SACA,OAAOA;QAGX,MAAMC,QAAQ,IAAI,CAAC,WAAW,CAACH,UAAUD,SAAS,OAAO,CAAC;YAEtD,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAACC,cAAcG,OAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,CAACH;QAE5B;QACA,IAAI,CAAC,OAAO,CAAC,GAAG,CAACA,UAAUG;QAE3B,OAAOA;IACX;IAEA,MAAc,YACVH,QAAgB,EAChBD,OAAiD,EACpC;QACb,MAAMK,SAAS,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAACJ;QAE/C,IAAI,CAACI,QACD,MAAM,IAAI,CAAC,WAAW,CAACJ,UAAUD;QAGrC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAACC;IACtB;IAEA,MAAc,YACVA,QAAgB,EAChBD,OAAiD,EACpC;QACb,IAAI;YACA,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAACC,UAAUD;QACjD,EAAE,OAAOM,KAAK;YAGV,MAAMD,SAAS,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAACJ;YAC/C,IAAII,QACA;YAEJ,MAAMC;QACV;IACJ;AACJ"}
|
package/adminUsers/index.js
CHANGED
|
@@ -10,20 +10,20 @@ const userToRow = (user)=>({
|
|
|
10
10
|
const rowToUser = (row)=>JSON.parse(row.data);
|
|
11
11
|
const createStorageOperations = (params)=>{
|
|
12
12
|
const { knex, tableManager } = params;
|
|
13
|
-
const ensureTable =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
13
|
+
const ensureTable = tableManager.define(TABLE_NAME, (table)=>{
|
|
14
|
+
table.text("id").notNullable();
|
|
15
|
+
table.text("tenant").notNullable();
|
|
16
|
+
table.text("email").notNullable();
|
|
17
|
+
table.text("data").notNullable();
|
|
18
|
+
table.primary([
|
|
19
|
+
"tenant",
|
|
20
|
+
"id"
|
|
21
|
+
]);
|
|
22
|
+
table.unique([
|
|
23
|
+
"tenant",
|
|
24
|
+
"email"
|
|
25
|
+
]);
|
|
26
|
+
});
|
|
27
27
|
const query = ()=>knex(tableManager.resolve(TABLE_NAME));
|
|
28
28
|
return {
|
|
29
29
|
async getUser (params) {
|
|
@@ -54,9 +54,12 @@ const createStorageOperations = (params)=>{
|
|
|
54
54
|
const rows = await query().where("tenant", where.tenant);
|
|
55
55
|
let items = rows.map((row)=>rowToUser(row));
|
|
56
56
|
items = sortItems(items, sort);
|
|
57
|
-
const { id_in } = where;
|
|
58
|
-
|
|
59
|
-
|
|
57
|
+
const { id_in, teams_in } = where;
|
|
58
|
+
return items.filter((item)=>{
|
|
59
|
+
if (Array.isArray(id_in) && !id_in.includes(item.id)) return false;
|
|
60
|
+
if (Array.isArray(teams_in)) return (item.teams || []).some((team)=>teams_in.includes(team));
|
|
61
|
+
return true;
|
|
62
|
+
});
|
|
60
63
|
} catch (err) {
|
|
61
64
|
throw error.from(err, {
|
|
62
65
|
message: "Could not list users.",
|
package/adminUsers/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n AdminUser,\n AdminUsersStorageOperations,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst TABLE_NAME = \"webiny_core_admin_users\";\n\ninterface IAdminUserRow {\n id: string;\n tenant: string;\n email: string;\n data: string;\n}\n\nconst userToRow = (user: AdminUser): IAdminUserRow => {\n return {\n id: user.id,\n tenant: user.tenant,\n email: user.email,\n data: JSON.stringify(user)\n };\n};\n\nconst rowToUser = <TUser extends AdminUser = AdminUser>(row: IAdminUserRow): TUser => {\n return JSON.parse(row.data) as TUser;\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): AdminUsersStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureTable =
|
|
1
|
+
{"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n AdminUser,\n AdminUsersStorageOperations,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst TABLE_NAME = \"webiny_core_admin_users\";\n\ninterface IAdminUserRow {\n id: string;\n tenant: string;\n email: string;\n data: string;\n}\n\nconst userToRow = (user: AdminUser): IAdminUserRow => {\n return {\n id: user.id,\n tenant: user.tenant,\n email: user.email,\n data: JSON.stringify(user)\n };\n};\n\nconst rowToUser = <TUser extends AdminUser = AdminUser>(row: IAdminUserRow): TUser => {\n return JSON.parse(row.data) as TUser;\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): AdminUsersStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureTable = tableManager.define(TABLE_NAME, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"email\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"email\"]);\n });\n\n const query = () => {\n return knex<IAdminUserRow>(tableManager.resolve(TABLE_NAME));\n };\n\n return {\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n await ensureTable();\n\n const {\n where: { tenant, id, email }\n } = params;\n\n try {\n if (id) {\n const row = await query().where(\"tenant\", tenant).andWhere(\"id\", id).first();\n\n return row ? rowToUser<TUser>(row) : null;\n }\n\n const row = await query()\n .where(\"tenant\", tenant)\n .andWhere(\"email\", email as string)\n .first();\n\n return row ? rowToUser<TUser>(row) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n\n async listUsers<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUsersParams\n ): Promise<TUser[]> {\n await ensureTable();\n\n const { where, sort } = params;\n\n try {\n const rows = await query().where(\"tenant\", where.tenant);\n\n let items = rows.map(row => rowToUser<TUser>(row));\n\n items = sortItems(items, sort);\n\n const { id_in, teams_in } = where;\n\n return items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n },\n\n async createUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().insert(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async updateUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).update(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async deleteUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<void> {\n await ensureTable();\n\n try {\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete user.\",\n code: \"DELETE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n }\n };\n};\n"],"names":["TABLE_NAME","userToRow","user","JSON","rowToUser","row","createStorageOperations","params","knex","tableManager","ensureTable","table","query","tenant","id","email","err","WebinyError","where","sort","rows","items","sortItems","id_in","teams_in","item","Array","team"],"mappings":";;AAWA,MAAMA,aAAa;AASnB,MAAMC,YAAY,CAACC,OACR;QACH,IAAIA,KAAK,EAAE;QACX,QAAQA,KAAK,MAAM;QACnB,OAAOA,KAAK,KAAK;QACjB,MAAMC,KAAK,SAAS,CAACD;IACzB;AAGJ,MAAME,YAAY,CAAsCC,MAC7CF,KAAK,KAAK,CAACE,IAAI,IAAI;AAQvB,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,cAAcD,aAAa,MAAM,CAACT,YAAYW,CAAAA;QAChDA,MAAM,IAAI,CAAC,MAAM,WAAW;QAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;QAChCA,MAAM,IAAI,CAAC,SAAS,WAAW;QAC/BA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAE9BA,MAAM,OAAO,CAAC;YAAC;YAAU;SAAK;QAC9BA,MAAM,MAAM,CAAC;YAAC;YAAU;SAAQ;IACpC;IAEA,MAAMC,QAAQ,IACHJ,KAAoBC,aAAa,OAAO,CAACT;IAGpD,OAAO;QACH,MAAM,SACFO,MAAsC;YAEtC,MAAMG;YAE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J;QAEA,MAAM,YAAgD,EAClDd,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAML,MAAMJ,UAAUC;gBACtB,MAAMU,QAAQ,MAAM,CAACP;gBAErB,OAAOH;YACX,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDA,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAML,MAAMJ,UAAUC;gBACtB,MAAMU,QAAQ,KAAK,CAAC,UAAUV,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM,CAACG;gBAE1E,OAAOH;YACX,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDA,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAME,QAAQ,KAAK,CAAC,UAAUV,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM;YAC7E,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;IACJ;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const isConnectionError: (error: unknown) => boolean;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const CONNECTION_ERROR_CODES = new Set([
|
|
2
|
+
"ECONNRESET",
|
|
3
|
+
"ECONNREFUSED",
|
|
4
|
+
"EPIPE",
|
|
5
|
+
"ETIMEDOUT",
|
|
6
|
+
"EHOSTUNREACH",
|
|
7
|
+
"ENOTFOUND",
|
|
8
|
+
"EAI_AGAIN",
|
|
9
|
+
"08000",
|
|
10
|
+
"08001",
|
|
11
|
+
"08003",
|
|
12
|
+
"08004",
|
|
13
|
+
"08006",
|
|
14
|
+
"57P01",
|
|
15
|
+
"57P02",
|
|
16
|
+
"57P03",
|
|
17
|
+
"25006"
|
|
18
|
+
]);
|
|
19
|
+
const CONNECTION_ERROR_MESSAGE = /Connection terminated|Client has encountered a connection error|terminating connection|Connection ended unexpectedly|timeout exceeded when trying to connect|the database system is (starting up|shutting down|in recovery)|cannot execute [A-Z ]+ in a read-only transaction/i;
|
|
20
|
+
const isConnectionError = (error)=>{
|
|
21
|
+
if (!error || "object" != typeof error) return false;
|
|
22
|
+
const { code, message } = error;
|
|
23
|
+
if ("string" == typeof code && CONNECTION_ERROR_CODES.has(code)) return true;
|
|
24
|
+
return "string" == typeof message && CONNECTION_ERROR_MESSAGE.test(message);
|
|
25
|
+
};
|
|
26
|
+
export { isConnectionError };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=isConnectionError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connectionRetry/isConnectionError.js","sources":["../../src/connectionRetry/isConnectionError.ts"],"sourcesContent":["/**\n * Errors that mean the connection to Postgres was lost or the server can't take work right now, as\n * opposed to errors about the statement itself. On these, nothing that wasn't committed was kept,\n * so the work can be run again on a new connection.\n */\nconst CONNECTION_ERROR_CODES = new Set([\n // Node.js socket and DNS errors.\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"EHOSTUNREACH\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n // Postgres class 08: connection exception.\n \"08000\",\n \"08001\",\n \"08003\",\n \"08004\",\n \"08006\",\n // Postgres class 57P: the server is shutting down, crashed, or is still starting.\n \"57P01\",\n \"57P02\",\n \"57P03\",\n // read_only_sql_transaction: after a failover, the old writer restarts as a reader, and a stale DNS\n // entry can still point at it for a while.\n \"25006\"\n]);\n\nconst CONNECTION_ERROR_MESSAGE =\n /Connection terminated|Client has encountered a connection error|terminating connection|Connection ended unexpectedly|timeout exceeded when trying to connect|the database system is (starting up|shutting down|in recovery)|cannot execute [A-Z ]+ in a read-only transaction/i;\n\nexport const isConnectionError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code === \"string\" && CONNECTION_ERROR_CODES.has(code)) {\n return true;\n }\n return typeof message === \"string\" && CONNECTION_ERROR_MESSAGE.test(message);\n};\n"],"names":["CONNECTION_ERROR_CODES","Set","CONNECTION_ERROR_MESSAGE","isConnectionError","error","code","message"],"mappings":"AAKA,MAAMA,yBAAyB,IAAIC,IAAI;IAEnC;IACA;IACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IAGA;CACH;AAED,MAAMC,2BACF;AAEG,MAAMC,oBAAoB,CAACC;IAC9B,IAAI,CAACA,SAAS,AAAiB,YAAjB,OAAOA,OACjB,OAAO;IAEX,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAE,GAAGF;IAC1B,IAAI,AAAgB,YAAhB,OAAOC,QAAqBL,uBAAuB,GAAG,CAACK,OACvD,OAAO;IAEX,OAAO,AAAmB,YAAnB,OAAOC,WAAwBJ,yBAAyB,IAAI,CAACI;AACxE"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Knex } from "knex";
|
|
2
|
+
/**
|
|
3
|
+
* Makes a Postgres knex instance survive a lost connection (a database failover, a dropped proxy
|
|
4
|
+
* connection, a server restart) without failing the API request, where that is safe:
|
|
5
|
+
*
|
|
6
|
+
* - A transaction (`knex.transaction(async trx => …)`) that loses its connection before COMMIT is sent
|
|
7
|
+
* is run again: the server rolled it back, so nothing of it was kept.
|
|
8
|
+
* - A transaction that loses its connection during COMMIT may or may not have committed. Before
|
|
9
|
+
* COMMIT, the transaction reads its own ID; after the failure, the wrapper asks the server for that
|
|
10
|
+
* transaction's outcome (`pg_xact_status`) on a new connection. Committed: the result is returned
|
|
11
|
+
* as is, and the work is not repeated. Rolled back: the transaction is run again. Unknown: the
|
|
12
|
+
* error is thrown.
|
|
13
|
+
* - A read-only transaction that fails at COMMIT returns its result: there was nothing to commit.
|
|
14
|
+
* - A read outside a transaction (a SELECT) is run again.
|
|
15
|
+
*
|
|
16
|
+
* Retries wait 100 ms, 250 ms, 500 ms, 1 s, then every 2 s, until `maxRetryMs` has passed since the
|
|
17
|
+
* first failure; then the last error is thrown. Errors that aren't about the connection (a constraint
|
|
18
|
+
* violation, a syntax error, a timeout of the statement itself) are never retried.
|
|
19
|
+
*
|
|
20
|
+
* A transaction's callback is run again on a retry, so it must only change the database: a call to
|
|
21
|
+
* another service inside it would be repeated.
|
|
22
|
+
*
|
|
23
|
+
* Writes outside a transaction are not retried: their outcome can't be checked.
|
|
24
|
+
*/
|
|
25
|
+
export type PgConnectionRetryEventType =
|
|
26
|
+
/** A connection error; the operation runs again after `delayMs`. */
|
|
27
|
+
"retry"
|
|
28
|
+
/** COMMIT failed, but the server confirmed that the transaction committed: no retry needed. */
|
|
29
|
+
| "commitConfirmed"
|
|
30
|
+
/** COMMIT failed, and the server confirmed that the transaction was rolled back: it runs again. */
|
|
31
|
+
| "commitRolledBack"
|
|
32
|
+
/** COMMIT failed for a transaction that changed nothing: its result is returned. */
|
|
33
|
+
| "readOnlyCommitIgnored"
|
|
34
|
+
/** Retries ran out (time or an unknown transaction outcome): the error is thrown. */
|
|
35
|
+
| "gaveUp";
|
|
36
|
+
export interface IPgConnectionRetryEvent {
|
|
37
|
+
type: PgConnectionRetryEventType;
|
|
38
|
+
operation: "transaction" | "query";
|
|
39
|
+
/** Retries so far for this operation. */
|
|
40
|
+
attempt: number;
|
|
41
|
+
delayMs?: number;
|
|
42
|
+
error: unknown;
|
|
43
|
+
}
|
|
44
|
+
export interface IPgConnectionRetryOptions {
|
|
45
|
+
/** How long to keep retrying after an operation's first connection error. Default: 15,000 ms. */
|
|
46
|
+
maxRetryMs?: number;
|
|
47
|
+
onEvent?: (event: IPgConnectionRetryEvent) => void;
|
|
48
|
+
}
|
|
49
|
+
export declare const withPgConnectionRetry: (knex: Knex, options?: IPgConnectionRetryOptions) => Knex;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { isConnectionError } from "./isConnectionError.js";
|
|
2
|
+
const DELAYS_MS = [
|
|
3
|
+
100,
|
|
4
|
+
250,
|
|
5
|
+
500,
|
|
6
|
+
1000,
|
|
7
|
+
2000
|
|
8
|
+
];
|
|
9
|
+
const IN_PROGRESS_CHECKS = 5;
|
|
10
|
+
const RETRY_INSTALLED = Symbol.for("webiny.pgConnectionRetry");
|
|
11
|
+
const READ_STATEMENT = /^\s*(select|show|explain|set|with)\b/i;
|
|
12
|
+
const WRITE_KEYWORDS = /\b(insert\s+into|update\s+\S+\s+set|delete\s+from|merge\s+into|truncate|create|alter|drop|grant|revoke|copy|nextval|setval|pg_advisory_lock|pg_try_advisory_lock)\b/i;
|
|
13
|
+
const mayWrite = (sql)=>!READ_STATEMENT.test(sql) || WRITE_KEYWORDS.test(sql);
|
|
14
|
+
const READ_METHODS = new Set([
|
|
15
|
+
"select",
|
|
16
|
+
"first",
|
|
17
|
+
"pluck"
|
|
18
|
+
]);
|
|
19
|
+
const isReadOnlyBuilder = (builder)=>{
|
|
20
|
+
if ("string" == typeof builder._method) return READ_METHODS.has(builder._method);
|
|
21
|
+
if ("string" == typeof builder.sql) return /^\s*(select|show|explain)\b/i.test(builder.sql) && !mayWrite(builder.sql);
|
|
22
|
+
return false;
|
|
23
|
+
};
|
|
24
|
+
class StopRetrying {
|
|
25
|
+
constructor(error){
|
|
26
|
+
this.error = error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const sleep = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms));
|
|
30
|
+
const withPgConnectionRetry = (knex, options = {})=>{
|
|
31
|
+
const target = knex;
|
|
32
|
+
const clientName = String(knex.client.config?.client);
|
|
33
|
+
if (target[RETRY_INSTALLED] || ![
|
|
34
|
+
"pg",
|
|
35
|
+
"postgres",
|
|
36
|
+
"postgresql"
|
|
37
|
+
].includes(clientName)) return knex;
|
|
38
|
+
target[RETRY_INSTALLED] = true;
|
|
39
|
+
const maxRetryMs = options.maxRetryMs ?? 15000;
|
|
40
|
+
const emit = (event)=>{
|
|
41
|
+
try {
|
|
42
|
+
options.onEvent?.(event);
|
|
43
|
+
} catch {}
|
|
44
|
+
};
|
|
45
|
+
const retrying = async (operation, attempt)=>{
|
|
46
|
+
let firstFailureAt;
|
|
47
|
+
for(let attemptNumber = 0;; attemptNumber++)try {
|
|
48
|
+
return await attempt(attemptNumber);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (error instanceof StopRetrying) throw error.error;
|
|
51
|
+
if (!isConnectionError(error)) throw error;
|
|
52
|
+
firstFailureAt ??= Date.now();
|
|
53
|
+
const delayMs = DELAYS_MS[Math.min(attemptNumber, DELAYS_MS.length - 1)];
|
|
54
|
+
if (Date.now() - firstFailureAt + delayMs > maxRetryMs) {
|
|
55
|
+
emit({
|
|
56
|
+
type: "gaveUp",
|
|
57
|
+
operation,
|
|
58
|
+
attempt: attemptNumber,
|
|
59
|
+
error
|
|
60
|
+
});
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
emit({
|
|
64
|
+
type: "retry",
|
|
65
|
+
operation,
|
|
66
|
+
attempt: attemptNumber,
|
|
67
|
+
delayMs,
|
|
68
|
+
error
|
|
69
|
+
});
|
|
70
|
+
await sleep(delayMs);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const client = knex.client;
|
|
74
|
+
const originalRunner = client.runner;
|
|
75
|
+
client.runner = function(builder) {
|
|
76
|
+
const runner = originalRunner.call(this, builder);
|
|
77
|
+
if (!isReadOnlyBuilder(builder)) return runner;
|
|
78
|
+
const firstRun = runner.run.bind(runner);
|
|
79
|
+
runner.run = ()=>retrying("query", (attemptNumber)=>0 === attemptNumber ? firstRun() : originalRunner.call(client, builder).run());
|
|
80
|
+
return runner;
|
|
81
|
+
};
|
|
82
|
+
const originalTransaction = knex.transaction;
|
|
83
|
+
const transactionOutcome = async (xid, pid)=>{
|
|
84
|
+
for(let check = 0; check < IN_PROGRESS_CHECKS; check++){
|
|
85
|
+
const result = await knex.raw("SELECT pg_xact_status(?::xid8)::text AS status", [
|
|
86
|
+
xid
|
|
87
|
+
]);
|
|
88
|
+
const status = result.rows[0]?.status ?? null;
|
|
89
|
+
if ("in progress" !== status) return status;
|
|
90
|
+
if (null !== pid) await knex.raw(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity
|
|
91
|
+
WHERE pid = ? AND backend_xid = (?::xid8)::xid AND state LIKE 'idle in transaction%'`, [
|
|
92
|
+
pid,
|
|
93
|
+
xid
|
|
94
|
+
]);
|
|
95
|
+
await sleep(DELAYS_MS[Math.min(check, DELAYS_MS.length - 1)]);
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
};
|
|
99
|
+
const runTransactionOnce = async (callback, config, attemptNumber)=>{
|
|
100
|
+
const state = {
|
|
101
|
+
committing: false,
|
|
102
|
+
wrote: false,
|
|
103
|
+
xid: null,
|
|
104
|
+
pid: null,
|
|
105
|
+
result: void 0
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
return await originalTransaction.call(knex, async (trx)=>{
|
|
109
|
+
trx.on("query", (query)=>{
|
|
110
|
+
if (!state.wrote && "string" == typeof query.sql && mayWrite(query.sql)) state.wrote = true;
|
|
111
|
+
});
|
|
112
|
+
const result = await callback(trx);
|
|
113
|
+
state.result = result;
|
|
114
|
+
if (state.wrote) {
|
|
115
|
+
const ids = await trx.raw("SELECT pg_current_xact_id_if_assigned()::text AS xid, pg_backend_pid() AS pid");
|
|
116
|
+
state.xid = ids.rows[0]?.xid ?? null;
|
|
117
|
+
state.pid = ids.rows[0]?.pid ?? null;
|
|
118
|
+
}
|
|
119
|
+
state.committing = true;
|
|
120
|
+
return result;
|
|
121
|
+
}, config);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (!state.committing || !isConnectionError(error)) throw error;
|
|
124
|
+
if (!state.xid) {
|
|
125
|
+
emit({
|
|
126
|
+
type: "readOnlyCommitIgnored",
|
|
127
|
+
operation: "transaction",
|
|
128
|
+
attempt: attemptNumber,
|
|
129
|
+
error
|
|
130
|
+
});
|
|
131
|
+
return state.result;
|
|
132
|
+
}
|
|
133
|
+
const outcome = await transactionOutcome(state.xid, state.pid);
|
|
134
|
+
if ("committed" === outcome) {
|
|
135
|
+
emit({
|
|
136
|
+
type: "commitConfirmed",
|
|
137
|
+
operation: "transaction",
|
|
138
|
+
attempt: attemptNumber,
|
|
139
|
+
error
|
|
140
|
+
});
|
|
141
|
+
return state.result;
|
|
142
|
+
}
|
|
143
|
+
if ("aborted" === outcome) {
|
|
144
|
+
emit({
|
|
145
|
+
type: "commitRolledBack",
|
|
146
|
+
operation: "transaction",
|
|
147
|
+
attempt: attemptNumber,
|
|
148
|
+
error
|
|
149
|
+
});
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
emit({
|
|
153
|
+
type: "gaveUp",
|
|
154
|
+
operation: "transaction",
|
|
155
|
+
attempt: attemptNumber,
|
|
156
|
+
error
|
|
157
|
+
});
|
|
158
|
+
throw new StopRetrying(error);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
Object.defineProperty(knex, "transaction", {
|
|
162
|
+
configurable: true,
|
|
163
|
+
enumerable: true,
|
|
164
|
+
writable: false,
|
|
165
|
+
value: function(...args) {
|
|
166
|
+
const [callback, config] = args;
|
|
167
|
+
if ("function" != typeof callback) return originalTransaction.apply(knex, args);
|
|
168
|
+
return retrying("transaction", (attemptNumber)=>runTransactionOnce(callback, config, attemptNumber));
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
return knex;
|
|
172
|
+
};
|
|
173
|
+
export { withPgConnectionRetry };
|
|
174
|
+
|
|
175
|
+
//# sourceMappingURL=withPgConnectionRetry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connectionRetry/withPgConnectionRetry.js","sources":["../../src/connectionRetry/withPgConnectionRetry.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { isConnectionError } from \"./isConnectionError.js\";\n\n/**\n * Makes a Postgres knex instance survive a lost connection (a database failover, a dropped proxy\n * connection, a server restart) without failing the API request, where that is safe:\n *\n * - A transaction (`knex.transaction(async trx => …)`) that loses its connection before COMMIT is sent\n * is run again: the server rolled it back, so nothing of it was kept.\n * - A transaction that loses its connection during COMMIT may or may not have committed. Before\n * COMMIT, the transaction reads its own ID; after the failure, the wrapper asks the server for that\n * transaction's outcome (`pg_xact_status`) on a new connection. Committed: the result is returned\n * as is, and the work is not repeated. Rolled back: the transaction is run again. Unknown: the\n * error is thrown.\n * - A read-only transaction that fails at COMMIT returns its result: there was nothing to commit.\n * - A read outside a transaction (a SELECT) is run again.\n *\n * Retries wait 100 ms, 250 ms, 500 ms, 1 s, then every 2 s, until `maxRetryMs` has passed since the\n * first failure; then the last error is thrown. Errors that aren't about the connection (a constraint\n * violation, a syntax error, a timeout of the statement itself) are never retried.\n *\n * A transaction's callback is run again on a retry, so it must only change the database: a call to\n * another service inside it would be repeated.\n *\n * Writes outside a transaction are not retried: their outcome can't be checked.\n */\n\nexport type PgConnectionRetryEventType =\n /** A connection error; the operation runs again after `delayMs`. */\n | \"retry\"\n /** COMMIT failed, but the server confirmed that the transaction committed: no retry needed. */\n | \"commitConfirmed\"\n /** COMMIT failed, and the server confirmed that the transaction was rolled back: it runs again. */\n | \"commitRolledBack\"\n /** COMMIT failed for a transaction that changed nothing: its result is returned. */\n | \"readOnlyCommitIgnored\"\n /** Retries ran out (time or an unknown transaction outcome): the error is thrown. */\n | \"gaveUp\";\n\nexport interface IPgConnectionRetryEvent {\n type: PgConnectionRetryEventType;\n operation: \"transaction\" | \"query\";\n /** Retries so far for this operation. */\n attempt: number;\n delayMs?: number;\n error: unknown;\n}\n\nexport interface IPgConnectionRetryOptions {\n /** How long to keep retrying after an operation's first connection error. Default: 15,000 ms. */\n maxRetryMs?: number;\n onEvent?: (event: IPgConnectionRetryEvent) => void;\n}\n\nconst DELAYS_MS = [100, 250, 500, 1000, 2000];\n/** How often to ask again while the server still reports the transaction as in progress. */\nconst IN_PROGRESS_CHECKS = 5;\n\nconst RETRY_INSTALLED = Symbol.for(\"webiny.pgConnectionRetry\");\n\n/* Statements that can't change data, so a transaction made only of them has nothing to lose. */\nconst READ_STATEMENT = /^\\s*(select|show|explain|set|with)\\b/i;\n/* Anything in a statement that changes data or takes a session lock. */\nconst WRITE_KEYWORDS =\n /\\b(insert\\s+into|update\\s+\\S+\\s+set|delete\\s+from|merge\\s+into|truncate|create|alter|drop|grant|revoke|copy|nextval|setval|pg_advisory_lock|pg_try_advisory_lock)\\b/i;\n\nconst mayWrite = (sql: string): boolean => {\n return !READ_STATEMENT.test(sql) || WRITE_KEYWORDS.test(sql);\n};\n\nconst READ_METHODS = new Set([\"select\", \"first\", \"pluck\"]);\n\n/* A query builder or raw statement that only reads. */\nconst isReadOnlyBuilder = (builder: { _method?: unknown; sql?: unknown }): boolean => {\n if (typeof builder._method === \"string\") {\n return READ_METHODS.has(builder._method);\n }\n if (typeof builder.sql === \"string\") {\n return /^\\s*(select|show|explain)\\b/i.test(builder.sql) && !mayWrite(builder.sql);\n }\n return false;\n};\n\n/* Thrown inside an attempt to stop retrying; carries the error to throw. */\nclass StopRetrying {\n public constructor(public readonly error: unknown) {}\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\ntype TransactionCallback = (trx: Knex.Transaction) => Promise<unknown> | unknown;\n\ninterface IRunner {\n run(): Promise<unknown>;\n}\n\ninterface IClientWithRunner {\n runner(builder: unknown): IRunner;\n}\n\ninterface ITransactionState {\n /* COMMIT has been sent (or is about to be). */\n committing: boolean;\n /* A statement that may have changed data ran. */\n wrote: boolean;\n xid: string | null;\n pid: number | null;\n result: unknown;\n}\n\nexport const withPgConnectionRetry = (\n knex: Knex,\n options: IPgConnectionRetryOptions = {}\n): Knex => {\n const target = knex as Knex & { [RETRY_INSTALLED]?: boolean };\n const clientName = String((knex.client as { config?: { client?: unknown } }).config?.client);\n if (target[RETRY_INSTALLED] || ![\"pg\", \"postgres\", \"postgresql\"].includes(clientName)) {\n return knex;\n }\n target[RETRY_INSTALLED] = true;\n\n const maxRetryMs = options.maxRetryMs ?? 15_000;\n const emit = (event: IPgConnectionRetryEvent) => {\n try {\n options.onEvent?.(event);\n } catch {\n // A failing listener must not change the outcome of the query.\n }\n };\n\n /* Runs `attempt` until it succeeds, throws a non-connection error, or time runs out. */\n const retrying = async <T>(\n operation: IPgConnectionRetryEvent[\"operation\"],\n attempt: (attemptNumber: number) => Promise<T>\n ): Promise<T> => {\n let firstFailureAt: number | undefined;\n for (let attemptNumber = 0; ; attemptNumber++) {\n try {\n return await attempt(attemptNumber);\n } catch (error) {\n if (error instanceof StopRetrying) {\n throw error.error;\n }\n if (!isConnectionError(error)) {\n throw error;\n }\n firstFailureAt ??= Date.now();\n const delayMs = DELAYS_MS[Math.min(attemptNumber, DELAYS_MS.length - 1)];\n if (Date.now() - firstFailureAt + delayMs > maxRetryMs) {\n emit({ type: \"gaveUp\", operation, attempt: attemptNumber, error });\n throw error;\n }\n emit({ type: \"retry\", operation, attempt: attemptNumber, delayMs, error });\n await sleep(delayMs);\n }\n }\n };\n\n // Reads outside a transaction. Transactions run their queries on their own client object (knex\n // creates it from the client's prototype), so this only sees statements outside transactions.\n const client = knex.client as unknown as IClientWithRunner;\n const originalRunner = client.runner;\n client.runner = function (this: IClientWithRunner, builder: unknown): IRunner {\n const runner = originalRunner.call(this, builder);\n if (!isReadOnlyBuilder(builder as Parameters<typeof isReadOnlyBuilder>[0])) {\n return runner;\n }\n const firstRun = runner.run.bind(runner);\n runner.run = () => {\n return retrying(\"query\", attemptNumber => {\n return attemptNumber === 0\n ? firstRun()\n : originalRunner.call(client, builder).run();\n });\n };\n return runner;\n };\n\n const originalTransaction = knex.transaction;\n\n /* The outcome of a transaction whose COMMIT failed: \"committed\", \"aborted\" or null (unknown). */\n const transactionOutcome = async (xid: string, pid: number | null): Promise<string | null> => {\n for (let check = 0; check < IN_PROGRESS_CHECKS; check++) {\n // A read outside a transaction: retried on connection errors by the runner above.\n const result = await knex.raw<{ rows: { status: string | null }[] }>(\n \"SELECT pg_xact_status(?::xid8)::text AS status\",\n [xid]\n );\n const status = result.rows[0]?.status ?? null;\n if (status !== \"in progress\") {\n return status;\n }\n // The server still has the transaction open. If its session is idle (the COMMIT never\n // arrived), end the session: the transaction is rolled back, and the next check says so.\n if (pid !== null) {\n await knex.raw(\n `SELECT pg_terminate_backend(pid) FROM pg_stat_activity\n WHERE pid = ? AND backend_xid = (?::xid8)::xid AND state LIKE 'idle in transaction%'`,\n [pid, xid]\n );\n }\n await sleep(DELAYS_MS[Math.min(check, DELAYS_MS.length - 1)]);\n }\n return null;\n };\n\n const runTransactionOnce = async (\n callback: TransactionCallback,\n config: Knex.TransactionConfig | undefined,\n attemptNumber: number\n ): Promise<unknown> => {\n const state: ITransactionState = {\n committing: false,\n wrote: false,\n xid: null,\n pid: null,\n result: undefined\n };\n try {\n return await originalTransaction.call(\n knex,\n async (trx: Knex.Transaction) => {\n trx.on(\"query\", (query: { sql?: string }) => {\n if (!state.wrote && typeof query.sql === \"string\" && mayWrite(query.sql)) {\n state.wrote = true;\n }\n });\n const result = await callback(trx);\n state.result = result;\n if (state.wrote) {\n // The transaction's ID, if it has one (it gets one when it changes data), so\n // its outcome can be checked if COMMIT fails.\n const ids = await trx.raw<{ rows: { xid: string | null; pid: number }[] }>(\n \"SELECT pg_current_xact_id_if_assigned()::text AS xid, pg_backend_pid() AS pid\"\n );\n state.xid = ids.rows[0]?.xid ?? null;\n state.pid = ids.rows[0]?.pid ?? null;\n }\n state.committing = true;\n return result;\n },\n config\n );\n } catch (error) {\n if (!state.committing || !isConnectionError(error)) {\n // Before COMMIT, a connection error is retried by the caller: the server rolled the\n // transaction back. Other errors are thrown.\n throw error;\n }\n if (!state.xid) {\n emit({\n type: \"readOnlyCommitIgnored\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n return state.result;\n }\n const outcome = await transactionOutcome(state.xid, state.pid);\n if (outcome === \"committed\") {\n emit({\n type: \"commitConfirmed\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n return state.result;\n }\n if (outcome === \"aborted\") {\n emit({\n type: \"commitRolledBack\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n throw error;\n }\n emit({ type: \"gaveUp\", operation: \"transaction\", attempt: attemptNumber, error });\n throw new StopRetrying(error);\n }\n };\n\n Object.defineProperty(knex, \"transaction\", {\n configurable: true,\n enumerable: true,\n writable: false,\n value: function transaction(this: Knex, ...args: unknown[]) {\n const [callback, config] = args;\n if (typeof callback !== \"function\") {\n // No callback: the caller commits and rolls back by hand; nothing to retry.\n return (originalTransaction as (...a: unknown[]) => unknown).apply(knex, args);\n }\n return retrying(\"transaction\", attemptNumber => {\n return runTransactionOnce(\n callback as TransactionCallback,\n config as Knex.TransactionConfig | undefined,\n attemptNumber\n );\n });\n }\n });\n\n return knex;\n};\n"],"names":["DELAYS_MS","IN_PROGRESS_CHECKS","RETRY_INSTALLED","Symbol","READ_STATEMENT","WRITE_KEYWORDS","mayWrite","sql","READ_METHODS","Set","isReadOnlyBuilder","builder","StopRetrying","error","sleep","ms","Promise","resolve","setTimeout","withPgConnectionRetry","knex","options","target","clientName","String","maxRetryMs","emit","event","retrying","operation","attempt","firstFailureAt","attemptNumber","isConnectionError","Date","delayMs","Math","client","originalRunner","runner","firstRun","originalTransaction","transactionOutcome","xid","pid","check","result","status","runTransactionOnce","callback","config","state","undefined","trx","query","ids","outcome","Object","args"],"mappings":";AAsDA,MAAMA,YAAY;IAAC;IAAK;IAAK;IAAK;IAAM;CAAK;AAE7C,MAAMC,qBAAqB;AAE3B,MAAMC,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ACvB9B,KAAK;oBACD,MAAM;oBACN,WAAW;oBACX,SAASM;oBACTnB;gBACJ;gBACA,MAAMA;YACV;YACAa,KAAK;gBAAE,MAAM;gBAAU,WAAW;gBAAe,SAASM;gBAAenB;YAAM;YAC/E,MAAM,IAAID,aAAaC;QAC3B;IACJ;IAEA4C,OAAO,cAAc,CAACrC,MAAM,eAAe;QACvC,cAAc;QACd,YAAY;QACZ,UAAU;QACV,OAAO,SAAiC,GAAGsC,IAAe;YACtD,MAAM,CAACT,UAAUC,OAAO,GAAGQ;YAC3B,IAAI,AAAoB,cAApB,OAAOT,UAEP,OAAQR,oBAAqD,KAAK,CAACrB,MAAMsC;YAE7E,OAAO9B,SAAS,eAAeI,CAAAA,gBACpBgB,mBACHC,UACAC,QACAlB;QAGZ;IACJ;IAEA,OAAOZ;AACX"}
|
package/index.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
|
3
3
|
export { ApiCoreSqlFeature } from "./ApiCoreSqlFeature.js";
|
|
4
4
|
export type { ApiCoreSqlConfig } from "./ApiCoreSqlFeature.js";
|
|
5
5
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
6
|
+
export { TableManager } from "./TableManager.js";
|
|
7
|
+
export { isSqlSchemaManaged } from "./schemaManaged.js";
|
|
8
|
+
export * from "./connectionRetry/index.js";
|
|
6
9
|
export { SqlServiceManifestLoader } from "./serviceDiscovery/index.js";
|
|
7
10
|
export { KnexClient } from "./feature/KnexClient/index.js";
|
|
8
11
|
interface IRegisterApiCoreSqlExtension {
|
package/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { createRegisterExtensionPlugin } from "@webiny/handler";
|
|
2
2
|
import { KnexClient, KnexClientFeature } from "./feature/KnexClient/index.js";
|
|
3
|
+
export * from "./connectionRetry/index.js";
|
|
3
4
|
const registerSQLCore = ({ knex })=>createRegisterExtensionPlugin(async (context)=>{
|
|
4
5
|
KnexClientFeature.register(context.container, knex);
|
|
5
6
|
});
|
|
6
7
|
export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
7
8
|
export { ApiCoreSqlFeature } from "./ApiCoreSqlFeature.js";
|
|
8
9
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
10
|
+
export { TableManager } from "./TableManager.js";
|
|
11
|
+
export { isSqlSchemaManaged } from "./schemaManaged.js";
|
|
9
12
|
export { SqlServiceManifestLoader } from "./serviceDiscovery/index.js";
|
|
10
13
|
export { KnexClient, registerSQLCore };
|
|
11
14
|
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { createRegisterExtensionPlugin } from \"@webiny/handler\";\nimport type { Knex } from \"knex\";\nimport { KnexClientFeature } from \"./feature/KnexClient/index.js\";\n\nexport { createApiCoreSql } from \"./createApiCoreSql.js\";\nexport { ApiCoreSqlFeature } from \"./ApiCoreSqlFeature.js\";\nexport type { ApiCoreSqlConfig } from \"./ApiCoreSqlFeature.js\";\nexport { getSqlTablePrefix } from \"./getSqlTablePrefix.js\";\nexport { SqlServiceManifestLoader } from \"./serviceDiscovery/index.js\";\n\nexport { KnexClient } from \"./feature/KnexClient/index.js\";\n\ninterface IRegisterApiCoreSqlExtension {\n knex: Knex;\n}\n\nexport const registerSQLCore = ({ knex }: IRegisterApiCoreSqlExtension) => {\n return createRegisterExtensionPlugin(async context => {\n KnexClientFeature.register(context.container, knex);\n });\n};\n"],"names":["registerSQLCore","knex","createRegisterExtensionPlugin","context","KnexClientFeature"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { createRegisterExtensionPlugin } from \"@webiny/handler\";\nimport type { Knex } from \"knex\";\nimport { KnexClientFeature } from \"./feature/KnexClient/index.js\";\n\nexport { createApiCoreSql } from \"./createApiCoreSql.js\";\nexport { ApiCoreSqlFeature } from \"./ApiCoreSqlFeature.js\";\nexport type { ApiCoreSqlConfig } from \"./ApiCoreSqlFeature.js\";\nexport { getSqlTablePrefix } from \"./getSqlTablePrefix.js\";\nexport { TableManager } from \"./TableManager.js\";\nexport { isSqlSchemaManaged } from \"./schemaManaged.js\";\nexport * from \"./connectionRetry/index.js\";\nexport { SqlServiceManifestLoader } from \"./serviceDiscovery/index.js\";\n\nexport { KnexClient } from \"./feature/KnexClient/index.js\";\n\ninterface IRegisterApiCoreSqlExtension {\n knex: Knex;\n}\n\nexport const registerSQLCore = ({ knex }: IRegisterApiCoreSqlExtension) => {\n return createRegisterExtensionPlugin(async context => {\n KnexClientFeature.register(context.container, knex);\n });\n};\n"],"names":["registerSQLCore","knex","createRegisterExtensionPlugin","context","KnexClientFeature"],"mappings":";;;AAmBO,MAAMA,kBAAkB,CAAC,EAAEC,IAAI,EAAgC,GAC3DC,8BAA8B,OAAMC;QACvCC,kBAAkB,QAAQ,CAACD,QAAQ,SAAS,EAAEF;IAClD"}
|