@webiny/api-core-sql 0.0.0-unstable.5387e5f7c8 → 0.0.0-unstable.676006d08e
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/TableManager.d.ts +30 -12
- package/TableManager.js +34 -30
- package/TableManager.js.map +1 -1
- package/adminUsers/index.d.ts +3 -0
- package/adminUsers/index.js +74 -19
- package/adminUsers/index.js.map +1 -1
- package/connection/SqlConnectionFeature.d.ts +32 -0
- package/connection/SqlConnectionFeature.js +30 -0
- package/connection/SqlConnectionFeature.js.map +1 -0
- package/connection/index.d.ts +2 -0
- package/connection/index.js +1 -0
- 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/coreStorage/CoreSqlSchemaSetup.d.ts +18 -0
- package/coreStorage/CoreSqlSchemaSetup.js +36 -0
- package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js +33 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.d.ts +18 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.js +36 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.js.map +1 -0
- package/coreStorage/SqlTenantStorageReadiness.d.ts +19 -0
- package/coreStorage/SqlTenantStorageReadiness.js +48 -0
- package/coreStorage/SqlTenantStorageReadiness.js.map +1 -0
- package/coreStorage/feature.d.ts +14 -0
- package/coreStorage/feature.js +17 -0
- package/coreStorage/feature.js.map +1 -0
- package/coreStorage/index.d.ts +1 -0
- package/coreStorage/index.js +1 -0
- package/createApiCoreSql.d.ts +19 -1
- package/createApiCoreSql.js +12 -10
- package/createApiCoreSql.js.map +1 -1
- package/feature/SqlDialect/abstractions.d.ts +15 -0
- package/feature/SqlDialect/abstractions.js +5 -0
- package/feature/SqlDialect/abstractions.js.map +1 -0
- package/feature/SqlDialect/index.d.ts +2 -0
- package/feature/SqlDialect/index.js +1 -0
- package/index.d.ts +26 -4
- package/index.js +18 -4
- package/index.js.map +1 -1
- package/keyValueStore/index.js +160 -21
- package/keyValueStore/index.js.map +1 -1
- package/package.json +9 -8
- package/schemaConfig/abstractions.d.ts +22 -0
- package/schemaConfig/abstractions.js +5 -0
- package/schemaConfig/abstractions.js.map +1 -0
- package/schemaConfig/index.d.ts +1 -0
- package/schemaConfig/index.js +1 -0
- package/schemaMemory/ensureTable.d.ts +35 -0
- package/schemaMemory/ensureTable.js +46 -0
- package/schemaMemory/ensureTable.js.map +1 -0
- package/schemaMemory/getConnectionKey.d.ts +8 -0
- package/schemaMemory/getConnectionKey.js +15 -0
- package/schemaMemory/getConnectionKey.js.map +1 -0
- package/schemaMemory/getSchemaMemory.d.ts +37 -0
- package/schemaMemory/getSchemaMemory.js +53 -0
- package/schemaMemory/getSchemaMemory.js.map +1 -0
- package/schemaSetup/abstractions.d.ts +79 -0
- package/schemaSetup/abstractions.js +6 -0
- package/schemaSetup/abstractions.js.map +1 -0
- package/schemaSetup/index.d.ts +6 -0
- package/schemaSetup/index.js +3 -0
- package/schemaSetup/runSchemaSetupSteps.d.ts +43 -0
- package/schemaSetup/runSchemaSetupSteps.js +39 -0
- package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
- package/schemaSetup/runSqlSchemaSetups.d.ts +22 -0
- package/schemaSetup/runSqlSchemaSetups.js +24 -0
- package/schemaSetup/runSqlSchemaSetups.js.map +1 -0
- package/scopeStorage/abstractions.d.ts +19 -0
- package/scopeStorage/abstractions.js +5 -0
- package/scopeStorage/abstractions.js.map +1 -0
- package/scopeStorage/index.d.ts +3 -0
- package/scopeStorage/index.js +2 -0
- package/scopeStorage/isPostgresScope.d.ts +14 -0
- package/scopeStorage/isPostgresScope.js +8 -0
- package/scopeStorage/isPostgresScope.js.map +1 -0
- package/security/index.d.ts +3 -0
- package/security/index.js +68 -47
- package/security/index.js.map +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.d.ts +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.js +3 -8
- package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
- package/serviceDiscovery/SqlServiceManifestWriter.d.ts +16 -0
- package/serviceDiscovery/SqlServiceManifestWriter.js +27 -0
- package/serviceDiscovery/SqlServiceManifestWriter.js.map +1 -0
- package/serviceDiscovery/index.d.ts +1 -0
- package/serviceDiscovery/index.js +1 -0
- package/serviceDiscovery/serviceManifestsTable.d.ts +13 -0
- package/serviceDiscovery/serviceManifestsTable.js +8 -0
- package/serviceDiscovery/serviceManifestsTable.js.map +1 -0
- package/storage/sqlTenantStorage.d.ts +44 -0
- package/storage/sqlTenantStorage.js +32 -0
- package/storage/sqlTenantStorage.js.map +1 -0
- package/storage/types.d.ts +31 -0
- package/storage/types.js +0 -0
- package/tenancy/index.js +59 -17
- package/tenancy/index.js.map +1 -1
- package/ApiCoreSqlFeature.d.ts +0 -18
- package/ApiCoreSqlFeature.js +0 -18
- package/ApiCoreSqlFeature.js.map +0 -1
package/TableManager.d.ts
CHANGED
|
@@ -1,19 +1,37 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
import { type TableCreator, type TableUpgrade } from "./schemaMemory/ensureTable.js";
|
|
3
|
+
export interface TableManagerOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The schema was set up before the API took traffic (see `SqlSchemaConfig`): `ensure()` then
|
|
6
|
+
* never checks for or creates a table. `setup()` still creates them. A function when it can
|
|
7
|
+
* change (a server turns it on once its schema setup at start ran): read on every `ensure()`.
|
|
8
|
+
*/
|
|
9
|
+
schemaManaged?: boolean | (() => boolean);
|
|
6
10
|
}
|
|
7
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The tables of one SQL storage part (core, audit logs, login) on one connection. Built wherever the
|
|
13
|
+
* storage is built, which is once per request: it holds no state of its own. What it learns (which
|
|
14
|
+
* tables exist) is kept for the process, in one memory per connection and table prefix, so a new
|
|
15
|
+
* instance doesn't check a table again and a long-running server keeps one entry per connection, not
|
|
16
|
+
* one per request.
|
|
17
|
+
*/
|
|
18
|
+
export declare class TableManager {
|
|
8
19
|
private readonly knex;
|
|
9
20
|
private readonly prefix;
|
|
10
|
-
private readonly
|
|
11
|
-
private readonly
|
|
12
|
-
|
|
21
|
+
private readonly schemaManaged;
|
|
22
|
+
private readonly defined;
|
|
23
|
+
private memoryOfTables?;
|
|
24
|
+
constructor(knex: Knex, prefix?: string, options?: TableManagerOptions);
|
|
25
|
+
/** Forgets which tables this connection has (test setups drop all tables between tests). */
|
|
13
26
|
reset(): void;
|
|
27
|
+
/**
|
|
28
|
+
* Declares a table and returns the function that ensures it on first use. Declared tables are
|
|
29
|
+
* created together by `setup()` (schema setup). `upgrade` brings a table that already existed up
|
|
30
|
+
* to date, for example with an index added after it was created.
|
|
31
|
+
*/
|
|
32
|
+
define(tableName: string, creator: TableCreator, upgrade?: TableUpgrade): () => Promise<void>;
|
|
33
|
+
setup(): Promise<void>;
|
|
14
34
|
resolve(tableName: string): string;
|
|
15
|
-
ensure(tableName: string, creator:
|
|
16
|
-
private
|
|
17
|
-
private createTable;
|
|
35
|
+
ensure(tableName: string, creator: TableCreator, upgrade?: TableUpgrade): Promise<void>;
|
|
36
|
+
private get memory();
|
|
18
37
|
}
|
|
19
|
-
export {};
|
package/TableManager.js
CHANGED
|
@@ -1,44 +1,48 @@
|
|
|
1
|
+
import { getSchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
2
|
+
import { getConnectionKey } from "./schemaMemory/getConnectionKey.js";
|
|
3
|
+
import { createTableIfMissing, ensureTable, recordTable } from "./schemaMemory/ensureTable.js";
|
|
1
4
|
class TableManager {
|
|
2
|
-
constructor(knex, prefix = ""){
|
|
3
|
-
this.
|
|
4
|
-
this.pending = new Map();
|
|
5
|
+
constructor(knex, prefix = "", options = {}){
|
|
6
|
+
this.defined = new Map();
|
|
5
7
|
this.knex = knex;
|
|
6
8
|
this.prefix = prefix ? `${prefix}_` : "";
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
managers.push(this);
|
|
9
|
+
const schemaManaged = options.schemaManaged;
|
|
10
|
+
this.schemaManaged = "function" == typeof schemaManaged ? schemaManaged : ()=>true === schemaManaged;
|
|
10
11
|
}
|
|
11
12
|
reset() {
|
|
12
|
-
this.
|
|
13
|
-
|
|
13
|
+
this.memory.reset();
|
|
14
|
+
}
|
|
15
|
+
define(tableName, creator, upgrade) {
|
|
16
|
+
this.defined.set(tableName, {
|
|
17
|
+
creator,
|
|
18
|
+
upgrade
|
|
19
|
+
});
|
|
20
|
+
return ()=>this.ensure(tableName, creator, upgrade);
|
|
21
|
+
}
|
|
22
|
+
async setup() {
|
|
23
|
+
for (const [tableName, { creator, upgrade }] of this.defined){
|
|
24
|
+
const resolved = this.resolve(tableName);
|
|
25
|
+
const generation = this.memory.generation;
|
|
26
|
+
await createTableIfMissing(this.knex, resolved, creator, upgrade);
|
|
27
|
+
if (this.memory.generation === generation) recordTable(this.knex, this.memory, resolved);
|
|
28
|
+
}
|
|
14
29
|
}
|
|
15
30
|
resolve(tableName) {
|
|
16
31
|
return `${this.prefix}${tableName}`;
|
|
17
32
|
}
|
|
18
|
-
async ensure(tableName, creator) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
33
|
+
async ensure(tableName, creator, upgrade) {
|
|
34
|
+
if (this.schemaManaged()) return;
|
|
35
|
+
await ensureTable({
|
|
36
|
+
knex: this.knex,
|
|
37
|
+
memory: this.memory,
|
|
38
|
+
tableName: this.resolve(tableName),
|
|
39
|
+
create: creator,
|
|
40
|
+
upgrade
|
|
25
41
|
});
|
|
26
|
-
this.pending.set(resolved, check);
|
|
27
|
-
return check;
|
|
28
|
-
}
|
|
29
|
-
async ensureTable(resolved, creator) {
|
|
30
|
-
const exists = await this.knex.schema.hasTable(resolved);
|
|
31
|
-
if (!exists) await this.createTable(resolved, creator);
|
|
32
|
-
this.verified.add(resolved);
|
|
33
42
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
} catch (err) {
|
|
38
|
-
const exists = await this.knex.schema.hasTable(resolved);
|
|
39
|
-
if (exists) return;
|
|
40
|
-
throw err;
|
|
41
|
-
}
|
|
43
|
+
get memory() {
|
|
44
|
+
this.memoryOfTables ??= getSchemaMemory(`core.sql.tables:${getConnectionKey(this.knex)}:${this.prefix}`);
|
|
45
|
+
return this.memoryOfTables;
|
|
42
46
|
}
|
|
43
47
|
}
|
|
44
48
|
export { TableManager };
|
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
|
|
1
|
+
{"version":3,"file":"TableManager.js","sources":["../src/TableManager.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { getSchemaMemory, type ISchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nimport { getConnectionKey } from \"./schemaMemory/getConnectionKey.js\";\nimport {\n createTableIfMissing,\n ensureTable,\n recordTable,\n type TableCreator,\n type TableUpgrade\n} from \"./schemaMemory/ensureTable.js\";\n\ninterface DefinedTable {\n creator: TableCreator;\n upgrade?: TableUpgrade;\n}\n\nexport interface TableManagerOptions {\n /**\n * The schema was set up before the API took traffic (see `SqlSchemaConfig`): `ensure()` then\n * never checks for or creates a table. `setup()` still creates them. A function when it can\n * change (a server turns it on once its schema setup at start ran): read on every `ensure()`.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\n/**\n * The tables of one SQL storage part (core, audit logs, login) on one connection. Built wherever the\n * storage is built, which is once per request: it holds no state of its own. What it learns (which\n * tables exist) is kept for the process, in one memory per connection and table prefix, so a new\n * instance doesn't check a table again and a long-running server keeps one entry per connection, not\n * one per request.\n */\nexport class TableManager {\n private readonly knex: Knex;\n private readonly prefix: string;\n private readonly schemaManaged: () => boolean;\n /* Tables declared by the storage operations using this manager, for schema setup. */\n private readonly defined = new Map<string, DefinedTable>();\n private memoryOfTables?: ISchemaMemory;\n\n constructor(knex: Knex, prefix: string = \"\", options: TableManagerOptions = {}) {\n this.knex = knex;\n this.prefix = prefix ? `${prefix}_` : \"\";\n const schemaManaged = options.schemaManaged;\n this.schemaManaged =\n typeof schemaManaged === \"function\" ? schemaManaged : () => schemaManaged === true;\n }\n\n /** Forgets which tables this connection has (test setups drop all tables between tests). */\n public reset(): void {\n this.memory.reset();\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()` (schema setup). `upgrade` brings a table that already existed up\n * to date, for example with an index added after it was created.\n */\n public define(\n tableName: string,\n creator: TableCreator,\n upgrade?: TableUpgrade\n ): () => Promise<void> {\n this.defined.set(tableName, { creator, upgrade });\n return () => this.ensure(tableName, creator, upgrade);\n }\n\n /* Creates every declared table that doesn't exist yet. Runs at schema setup. */\n public async setup(): Promise<void> {\n for (const [tableName, { creator, upgrade }] of this.defined) {\n const resolved = this.resolve(tableName);\n // Nothing checked before a reset is recorded after it (as in `ensureTable`).\n const generation = this.memory.generation;\n await createTableIfMissing(this.knex, resolved, creator, upgrade);\n if (this.memory.generation === generation) {\n recordTable(this.knex, this.memory, resolved);\n }\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: TableCreator,\n upgrade?: TableUpgrade\n ): Promise<void> {\n if (this.schemaManaged()) {\n return;\n }\n await ensureTable({\n knex: this.knex,\n memory: this.memory,\n tableName: this.resolve(tableName),\n create: creator,\n upgrade\n });\n }\n\n /* Made on first use: a schema-managed manager never needs it. */\n private get memory(): ISchemaMemory {\n this.memoryOfTables ??= getSchemaMemory(\n `core.sql.tables:${getConnectionKey(this.knex)}:${this.prefix}`\n );\n return this.memoryOfTables;\n }\n}\n"],"names":["TableManager","knex","prefix","options","Map","schemaManaged","tableName","creator","upgrade","resolved","generation","createTableIfMissing","recordTable","ensureTable","getSchemaMemory","getConnectionKey"],"mappings":";;;AAgCO,MAAMA;IAQT,YAAYC,IAAU,EAAEC,SAAiB,EAAE,EAAEC,UAA+B,CAAC,CAAC,CAAE;QAJG,KAClE,OAAO,GAAG,IAAIC;QAI3B,IAAI,CAAC,IAAI,GAAGH;QACZ,IAAI,CAAC,MAAM,GAAGC,SAAS,GAAGA,OAAO,CAAC,CAAC,GAAG;QACtC,MAAMG,gBAAgBF,QAAQ,aAAa;QAC3C,IAAI,CAAC,aAAa,GACd,AAAyB,cAAzB,OAAOE,gBAA+BA,gBAAgB,IAAMA,AAAkB,SAAlBA;IACpE;IAGO,QAAc;QACjB,IAAI,CAAC,MAAM,CAAC,KAAK;IACrB;IAOO,OACHC,SAAiB,EACjBC,OAAqB,EACrBC,OAAsB,EACH;QACnB,IAAI,CAAC,OAAO,CAAC,GAAG,CAACF,WAAW;YAAEC;YAASC;QAAQ;QAC/C,OAAO,IAAM,IAAI,CAAC,MAAM,CAACF,WAAWC,SAASC;IACjD;IAGA,MAAa,QAAuB;QAChC,KAAK,MAAM,CAACF,WAAW,EAAEC,OAAO,EAAEC,OAAO,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAE;YAC1D,MAAMC,WAAW,IAAI,CAAC,OAAO,CAACH;YAE9B,MAAMI,aAAa,IAAI,CAAC,MAAM,CAAC,UAAU;YACzC,MAAMC,qBAAqB,IAAI,CAAC,IAAI,EAAEF,UAAUF,SAASC;YACzD,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,KAAKE,YAC3BE,YAAY,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAEH;QAE5C;IACJ;IAEO,QAAQH,SAAiB,EAAU;QACtC,OAAO,GAAG,IAAI,CAAC,MAAM,GAAGA,WAAW;IACvC;IAEA,MAAa,OACTA,SAAiB,EACjBC,OAAqB,EACrBC,OAAsB,EACT;QACb,IAAI,IAAI,CAAC,aAAa,IAClB;QAEJ,MAAMK,YAAY;YACd,MAAM,IAAI,CAAC,IAAI;YACf,QAAQ,IAAI,CAAC,MAAM;YACnB,WAAW,IAAI,CAAC,OAAO,CAACP;YACxB,QAAQC;YACRC;QACJ;IACJ;IAGA,IAAY,SAAwB;QAChC,IAAI,CAAC,cAAc,KAAKM,gBACpB,CAAC,gBAAgB,EAAEC,iBAAiB,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE;QAEnE,OAAO,IAAI,CAAC,cAAc;IAC9B;AACJ"}
|
package/adminUsers/index.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
2
|
import type { AdminUsersStorageOperations } from "@webiny/api-core/types/users.js";
|
|
3
|
+
import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
|
|
3
4
|
import type { TableManager } from "../TableManager.js";
|
|
4
5
|
interface CreateStorageOperationsParams {
|
|
5
6
|
knex: Knex;
|
|
6
7
|
tableManager: TableManager;
|
|
8
|
+
/** The tenant the storage acts on: its scope's. */
|
|
9
|
+
scopeTenant: ScopeTenant.Interface;
|
|
7
10
|
}
|
|
8
11
|
export declare const createStorageOperations: (params: CreateStorageOperationsParams) => AdminUsersStorageOperations;
|
|
9
12
|
export {};
|
package/adminUsers/index.js
CHANGED
|
@@ -9,26 +9,41 @@ const userToRow = (user)=>({
|
|
|
9
9
|
});
|
|
10
10
|
const rowToUser = (row)=>JSON.parse(row.data);
|
|
11
11
|
const createStorageOperations = (params)=>{
|
|
12
|
-
const { knex, tableManager } = params;
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
]);
|
|
12
|
+
const { knex, tableManager, scopeTenant } = params;
|
|
13
|
+
const inScope = (user)=>({
|
|
14
|
+
...user,
|
|
15
|
+
tenant: scopeTenant.getId()
|
|
26
16
|
});
|
|
17
|
+
const idIndexName = `${tableManager.resolve(TABLE_NAME)}_id_index`;
|
|
18
|
+
const ensureTable = tableManager.define(TABLE_NAME, (table)=>{
|
|
19
|
+
table.text("id").notNullable();
|
|
20
|
+
table.text("tenant").notNullable();
|
|
21
|
+
table.text("email").notNullable();
|
|
22
|
+
table.text("data").notNullable();
|
|
23
|
+
table.primary([
|
|
24
|
+
"tenant",
|
|
25
|
+
"id"
|
|
26
|
+
]);
|
|
27
|
+
table.unique([
|
|
28
|
+
"tenant",
|
|
29
|
+
"email"
|
|
30
|
+
]);
|
|
31
|
+
table.index([
|
|
32
|
+
"id"
|
|
33
|
+
], idIndexName);
|
|
34
|
+
}, async (knex, tableName)=>{
|
|
35
|
+
await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??)", [
|
|
36
|
+
idIndexName,
|
|
37
|
+
tableName,
|
|
38
|
+
"id"
|
|
39
|
+
]);
|
|
40
|
+
});
|
|
27
41
|
const query = ()=>knex(tableManager.resolve(TABLE_NAME));
|
|
28
42
|
return {
|
|
29
43
|
async getUser (params) {
|
|
30
44
|
await ensureTable();
|
|
31
|
-
const { where: {
|
|
45
|
+
const { where: { id, email } } = params;
|
|
46
|
+
const tenant = scopeTenant.getId();
|
|
32
47
|
try {
|
|
33
48
|
if (id) {
|
|
34
49
|
const row = await query().where("tenant", tenant).andWhere("id", id).first();
|
|
@@ -47,16 +62,53 @@ const createStorageOperations = (params)=>{
|
|
|
47
62
|
});
|
|
48
63
|
}
|
|
49
64
|
},
|
|
65
|
+
async getUserAcrossTenants (params) {
|
|
66
|
+
const { id, tenants } = params;
|
|
67
|
+
if (0 === tenants.length) return [];
|
|
68
|
+
await ensureTable();
|
|
69
|
+
try {
|
|
70
|
+
const rows = await query().where("id", id).whereIn("tenant", tenants);
|
|
71
|
+
return rows.map((row)=>rowToUser(row));
|
|
72
|
+
} catch (err) {
|
|
73
|
+
throw error.from(err, {
|
|
74
|
+
message: "Could not load user across tenants.",
|
|
75
|
+
code: "GET_ADMIN_USER_ACROSS_TENANTS_ERROR",
|
|
76
|
+
data: {
|
|
77
|
+
id,
|
|
78
|
+
tenants
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
async listUserRecords (params) {
|
|
84
|
+
await ensureTable();
|
|
85
|
+
const { id } = params;
|
|
86
|
+
try {
|
|
87
|
+
const rows = await query().where("id", id);
|
|
88
|
+
return rows.map((row)=>rowToUser(row));
|
|
89
|
+
} catch (err) {
|
|
90
|
+
throw error.from(err, {
|
|
91
|
+
message: "Could not list user records.",
|
|
92
|
+
code: "LIST_ADMIN_USER_RECORDS_ERROR",
|
|
93
|
+
data: {
|
|
94
|
+
id
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
},
|
|
50
99
|
async listUsers (params) {
|
|
51
100
|
await ensureTable();
|
|
52
101
|
const { where, sort } = params;
|
|
53
102
|
try {
|
|
54
|
-
const rows = await query().where("tenant",
|
|
103
|
+
const rows = await query().where("tenant", scopeTenant.getId());
|
|
55
104
|
let items = rows.map((row)=>rowToUser(row));
|
|
56
105
|
items = sortItems(items, sort);
|
|
57
|
-
const { id_in } = where;
|
|
58
|
-
|
|
59
|
-
|
|
106
|
+
const { id_in, teams_in } = where;
|
|
107
|
+
return items.filter((item)=>{
|
|
108
|
+
if (Array.isArray(id_in) && !id_in.includes(item.id)) return false;
|
|
109
|
+
if (Array.isArray(teams_in)) return (item.teams || []).some((team)=>teams_in.includes(team));
|
|
110
|
+
return true;
|
|
111
|
+
});
|
|
60
112
|
} catch (err) {
|
|
61
113
|
throw error.from(err, {
|
|
62
114
|
message: "Could not list users.",
|
|
@@ -65,6 +117,7 @@ const createStorageOperations = (params)=>{
|
|
|
65
117
|
}
|
|
66
118
|
},
|
|
67
119
|
async createUser ({ user }) {
|
|
120
|
+
user = inScope(user);
|
|
68
121
|
await ensureTable();
|
|
69
122
|
try {
|
|
70
123
|
const row = userToRow(user);
|
|
@@ -81,6 +134,7 @@ const createStorageOperations = (params)=>{
|
|
|
81
134
|
}
|
|
82
135
|
},
|
|
83
136
|
async updateUser ({ user }) {
|
|
137
|
+
user = inScope(user);
|
|
84
138
|
await ensureTable();
|
|
85
139
|
try {
|
|
86
140
|
const row = userToRow(user);
|
|
@@ -97,6 +151,7 @@ const createStorageOperations = (params)=>{
|
|
|
97
151
|
}
|
|
98
152
|
},
|
|
99
153
|
async deleteUser ({ user }) {
|
|
154
|
+
user = inScope(user);
|
|
100
155
|
await ensureTable();
|
|
101
156
|
try {
|
|
102
157
|
await query().where("tenant", user.tenant).andWhere("id", user.id).delete();
|
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 = () => {\n return tableManager.ensure(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\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 } = where;\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n return items;\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","Array","item"],"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,cAAc,IACTD,aAAa,MAAM,CAACT,YAAYW,CAAAA;YACnCA,MAAM,IAAI,CAAC,MAAM,WAAW;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MAAM,QAAQ,CAACE,KAAK,EAAE;gBAGtD,OAAOJ;YACX,EAAE,OAAOL,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;gBACV;YACJ;QACJ;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"}
|
|
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 StorageOperationsGetUserAcrossTenantsParams,\n StorageOperationsGetUserParams,\n StorageOperationsListUserRecordsParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\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 /** The tenant the storage acts on: its scope's. */\n scopeTenant: ScopeTenant.Interface;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): AdminUsersStorageOperations => {\n const { knex, tableManager, scopeTenant } = params;\n\n /** The user with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends AdminUser>(user: T): T => {\n return { ...user, tenant: scopeTenant.getId() };\n };\n\n // The user→tenant index: finds every tenant's record of one user.\n const idIndexName = `${tableManager.resolve(TABLE_NAME)}_id_index`;\n\n const ensureTable = tableManager.define(\n TABLE_NAME,\n 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 table.index([\"id\"], idIndexName);\n },\n async (knex, tableName) => {\n // Tables created before the index existed.\n await knex.raw(\"CREATE INDEX IF NOT EXISTS ?? ON ?? (??)\", [\n idIndexName,\n tableName,\n \"id\"\n ]);\n }\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: { id, email }\n } = params;\n const tenant = scopeTenant.getId();\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 // Cross-tenant by design: one user's records in the given tenants, not the scope's tenant.\n async getUserAcrossTenants<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserAcrossTenantsParams\n ): Promise<TUser[]> {\n const { id, tenants } = params;\n if (tenants.length === 0) {\n return [];\n }\n\n await ensureTable();\n\n try {\n const rows = await query().where(\"id\", id).whereIn(\"tenant\", tenants);\n\n return rows.map(row => rowToUser<TUser>(row));\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user across tenants.\",\n code: \"GET_ADMIN_USER_ACROSS_TENANTS_ERROR\",\n data: { id, tenants }\n });\n }\n },\n\n // Cross-tenant by design: every tenant's record of one user.\n async listUserRecords<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUserRecordsParams\n ): Promise<TUser[]> {\n await ensureTable();\n\n const { id } = params;\n\n try {\n const rows = await query().where(\"id\", id);\n\n return rows.map(row => rowToUser<TUser>(row));\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list user records.\",\n code: \"LIST_ADMIN_USER_RECORDS_ERROR\",\n data: { id }\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\", scopeTenant.getId());\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 user = inScope(user);\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 user = inScope(user);\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 user = inScope(user);\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","scopeTenant","inScope","idIndexName","ensureTable","table","tableName","query","id","email","tenant","err","WebinyError","tenants","rows","where","sort","items","sortItems","id_in","teams_in","item","Array","team"],"mappings":";;AAcA,MAAMA,aAAa;AASnB,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YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDA,IAAI,EAGP;YACGA,OAAOS,QAAQT;YACf,MAAMW;YAEN,IAAI;gBACA,MAAMG,QAAQ,KAAK,CAAC,UAAUd,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM;YAC7E,EAAE,OAAOkB,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAElB;oBAAK;gBACjB;YACJ;QACJ;IACJ;AACJ"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Knex } from "knex";
|
|
2
|
+
import { SqlDialect } from "../feature/SqlDialect/index.js";
|
|
3
|
+
export interface SqlConnectionConfig {
|
|
4
|
+
knex: Knex;
|
|
5
|
+
/** The connection's database family, registered as `SqlDialect`. */
|
|
6
|
+
dialect: SqlDialect.Name;
|
|
7
|
+
tableNamePrefix?: string;
|
|
8
|
+
/**
|
|
9
|
+
* The schema was set up before the API took traffic (the storage's schema setup ran), so no
|
|
10
|
+
* storage code checks for or creates tables at runtime. Off by default: tables are created on
|
|
11
|
+
* first use. A function when it can change: a server turns it on once its setup at start ran.
|
|
12
|
+
*/
|
|
13
|
+
schemaManaged?: boolean | (() => boolean);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A SQL storage's connection (`KnexClient`), its database family (`SqlDialect`) and its settings,
|
|
17
|
+
* the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every storage part registered
|
|
18
|
+
* in a tenant scope, and every module on the storage (the Postgres CMS, the folder catalog), runs on
|
|
19
|
+
* these.
|
|
20
|
+
*
|
|
21
|
+
* The default storage registers it in the root container, once per process. It holds no feature's
|
|
22
|
+
* storage, not even the tenant registry's: those register in each tenant scope (`RequestStorage`).
|
|
23
|
+
*/
|
|
24
|
+
export declare const SqlConnectionFeature: {
|
|
25
|
+
name: string;
|
|
26
|
+
register(container: import("@webiny/di").Container, context: SqlConnectionConfig): void;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Points service discovery at the manifests table of a connection. The loader is a static global of
|
|
30
|
+
* the process, not a DI registration, so a storage sets it once, when it registers in the root.
|
|
31
|
+
*/
|
|
32
|
+
export declare const setSqlServiceManifestLoader: (config: Omit<SqlConnectionConfig, "dialect">) => void;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/api";
|
|
2
|
+
import { ServiceDiscovery } from "@webiny/api-core/features/serviceDiscovery/index.js";
|
|
3
|
+
import { KnexClientFeature } from "../feature/KnexClient/index.js";
|
|
4
|
+
import { SqlDialect } from "../feature/SqlDialect/index.js";
|
|
5
|
+
import { SqlSchemaConfig } from "../schemaConfig/index.js";
|
|
6
|
+
import { SqlServiceManifestLoader } from "../serviceDiscovery/index.js";
|
|
7
|
+
import { TableManager } from "../TableManager.js";
|
|
8
|
+
const isManaged = (schemaManaged)=>"function" == typeof schemaManaged ? schemaManaged() : true === schemaManaged;
|
|
9
|
+
const SqlConnectionFeature = createFeature({
|
|
10
|
+
name: "SqlConnection",
|
|
11
|
+
register (container, { knex, dialect, tableNamePrefix, schemaManaged = false }) {
|
|
12
|
+
KnexClientFeature.register(container, knex);
|
|
13
|
+
container.registerInstance(SqlDialect, {
|
|
14
|
+
name: dialect
|
|
15
|
+
});
|
|
16
|
+
container.registerInstance(SqlSchemaConfig, {
|
|
17
|
+
isManaged: ()=>isManaged(schemaManaged),
|
|
18
|
+
tableNamePrefix
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
const setSqlServiceManifestLoader = (config)=>{
|
|
23
|
+
const tableManager = new TableManager(config.knex, config.tableNamePrefix, {
|
|
24
|
+
schemaManaged: ()=>isManaged(config.schemaManaged)
|
|
25
|
+
});
|
|
26
|
+
ServiceDiscovery.setLoader(new SqlServiceManifestLoader(config.knex, tableManager));
|
|
27
|
+
};
|
|
28
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=SqlConnectionFeature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection/SqlConnectionFeature.js","sources":["../../src/connection/SqlConnectionFeature.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { createFeature } from \"@webiny/feature/api\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { KnexClientFeature } from \"~/feature/KnexClient/index.js\";\nimport { SqlDialect } from \"~/feature/SqlDialect/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\nimport { SqlServiceManifestLoader } from \"~/serviceDiscovery/index.js\";\nimport { TableManager } from \"~/TableManager.js\";\n\nexport interface SqlConnectionConfig {\n knex: Knex;\n /** The connection's database family, registered as `SqlDialect`. */\n dialect: SqlDialect.Name;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (the storage's schema setup ran), so no\n * storage code checks for or creates tables at runtime. Off by default: tables are created on\n * first use. A function when it can change: a server turns it on once its setup at start ran.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\nconst isManaged = (schemaManaged: SqlConnectionConfig[\"schemaManaged\"]): boolean => {\n return typeof schemaManaged === \"function\" ? schemaManaged() : schemaManaged === true;\n};\n\n/**\n * A SQL storage's connection (`KnexClient`), its database family (`SqlDialect`) and its settings,\n * the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every storage part registered\n * in a tenant scope, and every module on the storage (the Postgres CMS, the folder catalog), runs on\n * these.\n *\n * The default storage registers it in the root container, once per process. It holds no feature's\n * storage, not even the tenant registry's: those register in each tenant scope (`RequestStorage`).\n */\nexport const SqlConnectionFeature = createFeature<SqlConnectionConfig>({\n name: \"SqlConnection\",\n register(container, { knex, dialect, tableNamePrefix, schemaManaged = false }) {\n KnexClientFeature.register(container, knex);\n container.registerInstance(SqlDialect, { name: dialect });\n container.registerInstance(SqlSchemaConfig, {\n isManaged: () => isManaged(schemaManaged),\n tableNamePrefix\n });\n }\n});\n\n/**\n * Points service discovery at the manifests table of a connection. The loader is a static global of\n * the process, not a DI registration, so a storage sets it once, when it registers in the root.\n */\nexport const setSqlServiceManifestLoader = (config: Omit<SqlConnectionConfig, \"dialect\">): void => {\n const tableManager = new TableManager(config.knex, config.tableNamePrefix, {\n schemaManaged: () => isManaged(config.schemaManaged)\n });\n ServiceDiscovery.setLoader(new SqlServiceManifestLoader(config.knex, tableManager));\n};\n"],"names":["isManaged","schemaManaged","SqlConnectionFeature","createFeature","container","knex","dialect","tableNamePrefix","KnexClientFeature","SqlDialect","SqlSchemaConfig","setSqlServiceManifestLoader","config","tableManager","TableManager","ServiceDiscovery","SqlServiceManifestLoader"],"mappings":";;;;;;;AAsBA,MAAMA,YAAY,CAACC,gBACR,AAAyB,cAAzB,OAAOA,gBAA+BA,kBAAkBA,AAAkB,SAAlBA;AAY5D,MAAMC,uBAAuBC,cAAmC;IACnE,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,IAAI,EAAEC,OAAO,EAAEC,eAAe,EAAEN,gBAAgB,KAAK,EAAE;QACzEO,kBAAkB,QAAQ,CAACJ,WAAWC;QACtCD,UAAU,gBAAgB,CAACK,YAAY;YAAE,MAAMH;QAAQ;QACvDF,UAAU,gBAAgB,CAACM,iBAAiB;YACxC,WAAW,IAAMV,UAAUC;YAC3BM;QACJ;IACJ;AACJ;AAMO,MAAMI,8BAA8B,CAACC;IACxC,MAAMC,eAAe,IAAIC,aAAaF,OAAO,IAAI,EAAEA,OAAO,eAAe,EAAE;QACvE,eAAe,IAAMZ,UAAUY,OAAO,aAAa;IACvD;IACAG,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBJ,OAAO,IAAI,EAAEC;AACzE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader } from "./SqlConnectionFeature.js";
|
|
@@ -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;
|