@webiny/api-storage-pg 0.0.0-unstable.3fddf667ea → 0.0.0-unstable.48a4e5b6c1
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/createPgConnection.d.ts +7 -1
- package/createPgConnection.js +1 -1
- package/createPgConnection.js.map +1 -1
- package/createPgStorage.d.ts +5 -3
- package/createPgStorage.js +49 -10
- package/createPgStorage.js.map +1 -1
- package/createPgTenantStorages.d.ts +39 -0
- package/createPgTenantStorages.js +41 -0
- package/createPgTenantStorages.js.map +1 -0
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/package.json +12 -12
package/createPgConnection.d.ts
CHANGED
|
@@ -15,6 +15,12 @@ export interface CreatePgConnectionOptions {
|
|
|
15
15
|
* milliseconds; 0 turns retries off. Default: `WEBINY_PG_RETRY_MS`, else 15,000.
|
|
16
16
|
*/
|
|
17
17
|
retryMs?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Where the `WEBINY_PG_*` settings are read from. Default: `process.env`, the default storage's.
|
|
20
|
+
* An extra storage passes its own settings, under the same names, or `{}` to take only the
|
|
21
|
+
* explicit options: the default storage's settings must never fill in for it.
|
|
22
|
+
*/
|
|
23
|
+
env?: Record<string, string | undefined>;
|
|
18
24
|
}
|
|
19
25
|
/**
|
|
20
26
|
* A Knex client for Postgres, for a long-running process (the standalone server): Postgres, PGlite
|
|
@@ -22,6 +28,6 @@ export interface CreatePgConnectionOptions {
|
|
|
22
28
|
* env vars `<Infra.Postgres>` sets, with explicit options taking precedence. A connection string
|
|
23
29
|
* (`WEBINY_PG_CONNECTION_STRING` or `options.connection.connectionString`) is enough on its own:
|
|
24
30
|
* node-postgres reads host, port, user, password and database from it. On AWS Lambda, use
|
|
25
|
-
* `createLambdaPgConnection` (`@webiny/api-
|
|
31
|
+
* `createLambdaPgConnection` (`@webiny/api-composition-aws-pg`) instead.
|
|
26
32
|
*/
|
|
27
33
|
export declare function createPgConnection(options?: CreatePgConnectionOptions): Knex;
|
package/createPgConnection.js
CHANGED
|
@@ -7,7 +7,7 @@ const assertSet = (value, message)=>{
|
|
|
7
7
|
if (!value) throw new Error(message);
|
|
8
8
|
};
|
|
9
9
|
function createPgConnection(options = {}) {
|
|
10
|
-
const env = readPgConnectionEnv();
|
|
10
|
+
const env = readPgConnectionEnv(options.env);
|
|
11
11
|
const explicitConnection = options.connection || {};
|
|
12
12
|
const explicit = {
|
|
13
13
|
...definedOnly({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPgConnection.js","sources":["../src/createPgConnection.ts"],"sourcesContent":["import knex, { type Knex } from \"knex\";\nimport { withPgConnectionRetry } from \"@webiny/api-core-sql\";\nimport { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from \"./readPgConnectionEnv.js\";\nimport { applyToPgConnectionString } from \"./applyToPgConnectionString.js\";\n\nconst definedOnly = <T extends Record<string, unknown>>(values: T): Partial<T> => {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => !!value)) as Partial<T>;\n};\n\nconst assertSet = (value: unknown, message: string): void => {\n if (!value) {\n throw new Error(message);\n }\n};\n\nexport interface CreatePgConnectionOptions {\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n /**\n * Optional additional Knex connection config (SSL, pool size, etc.).\n * Overrides values from env vars when both are set.\n */\n connection?: Partial<Knex.PgConnectionConfig>;\n /**\n * How long to retry a read or transaction that lost its connection (failover, restart), in\n * milliseconds; 0 turns retries off. Default: `WEBINY_PG_RETRY_MS`, else 15,000.\n */\n retryMs?: number;\n}\n\n/**\n * A Knex client for Postgres, for a long-running process (the standalone server): Postgres, PGlite\n * (`<Infra.Pglite>`) or Aurora from a server. Connection parameters are read from the `WEBINY_PG_*`\n * env vars `<Infra.Postgres>` sets, with explicit options taking precedence. A connection string\n * (`WEBINY_PG_CONNECTION_STRING` or `options.connection.connectionString`) is enough on its own:\n * node-postgres reads host, port, user, password and database from it. On AWS Lambda, use\n * `createLambdaPgConnection` (`@webiny/api-
|
|
1
|
+
{"version":3,"file":"createPgConnection.js","sources":["../src/createPgConnection.ts"],"sourcesContent":["import knex, { type Knex } from \"knex\";\nimport { withPgConnectionRetry } from \"@webiny/api-core-sql\";\nimport { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from \"./readPgConnectionEnv.js\";\nimport { applyToPgConnectionString } from \"./applyToPgConnectionString.js\";\n\nconst definedOnly = <T extends Record<string, unknown>>(values: T): Partial<T> => {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => !!value)) as Partial<T>;\n};\n\nconst assertSet = (value: unknown, message: string): void => {\n if (!value) {\n throw new Error(message);\n }\n};\n\nexport interface CreatePgConnectionOptions {\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n /**\n * Optional additional Knex connection config (SSL, pool size, etc.).\n * Overrides values from env vars when both are set.\n */\n connection?: Partial<Knex.PgConnectionConfig>;\n /**\n * How long to retry a read or transaction that lost its connection (failover, restart), in\n * milliseconds; 0 turns retries off. Default: `WEBINY_PG_RETRY_MS`, else 15,000.\n */\n retryMs?: number;\n /**\n * Where the `WEBINY_PG_*` settings are read from. Default: `process.env`, the default storage's.\n * An extra storage passes its own settings, under the same names, or `{}` to take only the\n * explicit options: the default storage's settings must never fill in for it.\n */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * A Knex client for Postgres, for a long-running process (the standalone server): Postgres, PGlite\n * (`<Infra.Pglite>`) or Aurora from a server. Connection parameters are read from the `WEBINY_PG_*`\n * env vars `<Infra.Postgres>` sets, with explicit options taking precedence. A connection string\n * (`WEBINY_PG_CONNECTION_STRING` or `options.connection.connectionString`) is enough on its own:\n * node-postgres reads host, port, user, password and database from it. On AWS Lambda, use\n * `createLambdaPgConnection` (`@webiny/api-composition-aws-pg`) instead.\n */\nexport function createPgConnection(options: CreatePgConnectionOptions = {}): Knex {\n const env = readPgConnectionEnv(options.env);\n const explicitConnection = options.connection || {};\n // The connection parts the caller set: the options, then `options.connection`.\n const explicit = {\n ...definedOnly({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.database\n }),\n ...definedOnly({\n host: explicitConnection.host,\n port: explicitConnection.port,\n user: explicitConnection.user,\n // A password function can't go into a connection string.\n password:\n typeof explicitConnection.password === \"string\"\n ? explicitConnection.password\n : undefined,\n database: explicitConnection.database\n })\n };\n // Env first, then the explicit options, then `options.connection`: validated as Knex gets it.\n const connectionConfig: Knex.PgConnectionConfig = {\n ...env.connection,\n ...explicit,\n ...explicitConnection\n };\n // node-postgres reads a connection string over the separate parts, so the parts the caller set\n // go into the string too (the env's own parts don't: the string is the env's whole connection).\n if (connectionConfig.connectionString && Object.keys(explicit).length > 0) {\n connectionConfig.connectionString = applyToPgConnectionString(\n connectionConfig.connectionString,\n explicit\n );\n }\n\n // A connection string holds the whole connection; otherwise each part must be set.\n if (!connectionConfig.connectionString) {\n assertSet(\n connectionConfig.host,\n 'Postgres host is not set. Configure via <Infra.Postgres host=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.port,\n \"Postgres port is not set. Configure via <Infra.Postgres port={...} /> in webiny.config.\"\n );\n assertSet(\n connectionConfig.user,\n 'Postgres user is not set. Configure via <Infra.Postgres user=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.password,\n 'Postgres password is not set. Configure via <Infra.Postgres password=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.database,\n 'Postgres database is not set. Configure via <Infra.Postgres database=\"...\" /> in webiny.config.'\n );\n }\n\n const poolMax = env.poolMax;\n\n const client = knex({\n client: \"pg\",\n connection: connectionConfig,\n // knex's default minimum (2) must not exceed the maximum.\n ...(poolMax !== undefined ? { pool: { min: Math.min(2, poolMax), max: poolMax } } : {})\n });\n\n // Reads and transactions that lose their connection run again on a new one (see\n // withPgConnectionRetry); writes outside a transaction are not retried.\n const retryMs = options.retryMs ?? env.retryMs ?? DEFAULT_PG_RETRY_MS;\n if (retryMs > 0) {\n withPgConnectionRetry(client, { maxRetryMs: retryMs });\n }\n return client;\n}\n"],"names":["definedOnly","values","Object","value","assertSet","message","Error","createPgConnection","options","env","readPgConnectionEnv","explicitConnection","explicit","undefined","connectionConfig","applyToPgConnectionString","poolMax","client","knex","Math","retryMs","DEFAULT_PG_RETRY_MS","withPgConnectionRetry"],"mappings":";;;;AAKA,MAAMA,cAAc,CAAoCC,SAC7CC,OAAO,WAAW,CAACA,OAAO,OAAO,CAACD,QAAQ,MAAM,CAAC,CAAC,GAAGE,MAAM,GAAK,CAAC,CAACA;AAG7E,MAAMC,YAAY,CAACD,OAAgBE;IAC/B,IAAI,CAACF,OACD,MAAM,IAAIG,MAAMD;AAExB;AAkCO,SAASE,mBAAmBC,UAAqC,CAAC,CAAC;IACtE,MAAMC,MAAMC,oBAAoBF,QAAQ,GAAG;IAC3C,MAAMG,qBAAqBH,QAAQ,UAAU,IAAI,CAAC;IAElD,MAAMI,WAAW;QACb,GAAGZ,YAAY;YACX,MAAMQ,QAAQ,IAAI;YAClB,MAAMA,QAAQ,IAAI;YAClB,MAAMA,QAAQ,IAAI;YAClB,UAAUA,QAAQ,QAAQ;YAC1B,UAAUA,QAAQ,QAAQ;QAC9B,EAAE;QACF,GAAGR,YAAY;YACX,MAAMW,mBAAmB,IAAI;YAC7B,MAAMA,mBAAmB,IAAI;YAC7B,MAAMA,mBAAmB,IAAI;YAE7B,UACI,AAAuC,YAAvC,OAAOA,mBAAmB,QAAQ,GAC5BA,mBAAmB,QAAQ,GAC3BE;YACV,UAAUF,mBAAmB,QAAQ;QACzC,EAAE;IACN;IAEA,MAAMG,mBAA4C;QAC9C,GAAGL,IAAI,UAAU;QACjB,GAAGG,QAAQ;QACX,GAAGD,kBAAkB;IACzB;IAGA,IAAIG,iBAAiB,gBAAgB,IAAIZ,OAAO,IAAI,CAACU,UAAU,MAAM,GAAG,GACpEE,iBAAiB,gBAAgB,GAAGC,0BAChCD,iBAAiB,gBAAgB,EACjCF;IAKR,IAAI,CAACE,iBAAiB,gBAAgB,EAAE;QACpCV,UACIU,iBAAiB,IAAI,EACrB;QAEJV,UACIU,iBAAiB,IAAI,EACrB;QAEJV,UACIU,iBAAiB,IAAI,EACrB;QAEJV,UACIU,iBAAiB,QAAQ,EACzB;QAEJV,UACIU,iBAAiB,QAAQ,EACzB;IAER;IAEA,MAAME,UAAUP,IAAI,OAAO;IAE3B,MAAMQ,SAASC,KAAK;QAChB,QAAQ;QACR,YAAYJ;QAEZ,GAAIE,AAAYH,WAAZG,UAAwB;YAAE,MAAM;gBAAE,KAAKG,KAAK,GAAG,CAAC,GAAGH;gBAAU,KAAKA;YAAQ;QAAE,IAAI,CAAC,CAAC;IAC1F;IAIA,MAAMI,UAAUZ,QAAQ,OAAO,IAAIC,IAAI,OAAO,IAAIY;IAClD,IAAID,UAAU,GACVE,sBAAsBL,QAAQ;QAAE,YAAYG;IAAQ;IAExD,OAAOH;AACX"}
|
package/createPgStorage.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
|
-
import { type SqlStorage } from "@webiny/api-core-sql";
|
|
3
|
-
export interface CreatePgStorageParams {
|
|
2
|
+
import { type SqlStorage, type SqlStorageIdentityParams } from "@webiny/api-core-sql";
|
|
3
|
+
export interface CreatePgStorageParams extends SqlStorageIdentityParams {
|
|
4
4
|
/** The connection: `createPgConnection()` on a server, `createLambdaPgConnection()` on Lambda. */
|
|
5
5
|
knex: Knex;
|
|
6
6
|
tableNamePrefix?: string;
|
|
@@ -14,7 +14,9 @@ export interface CreatePgStorageParams {
|
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
16
|
* The Postgres SQL storage of the Webiny API, shared by every transport that runs it on Postgres
|
|
17
|
-
* (the standalone server and AWS Lambda): SQL core, websockets and audit logs.
|
|
17
|
+
* (the standalone server and AWS Lambda): SQL core, websockets and audit logs. It is the deploy's
|
|
18
|
+
* default storage, or, with an `id`, an extra storage that only the tenants naming it in
|
|
19
|
+
* `settings.storage` run on (see `SqlStorage.register`). Generic: it holds no
|
|
18
20
|
* CMS and no ACO. Those are modules the project adds with its extensions (`<HeadlessCmsPg />`,
|
|
19
21
|
* `<AcoPg />`), which run on what the storage registers: the connection, the table prefix and the
|
|
20
22
|
* schema-managed setting. Without the CMS module, its schema setup fails, naming it.
|
package/createPgStorage.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { RequestStorage } from "@webiny/api-core";
|
|
2
|
-
import { ApiCoreSqlFeature, SqlConnectionFeature, SqlSchemaSetupRunner, runSchemaSetupSteps, setSqlServiceManifestLoader } from "@webiny/api-core-sql";
|
|
2
|
+
import { ApiCoreSqlFeature, SqlConnectionFeature, SqlSchemaSetupRunner, createSqlRequestStorage, createSqlTenantStorageBackend, registerTenantStorageBackend, runSchemaSetupSteps, setSqlServiceManifestLoader } from "@webiny/api-core-sql";
|
|
3
|
+
import { TenantStorageId, createDefaultTenantStorageBackend } from "@webiny/api-core/features/tenancy/TenantStorages/index.js";
|
|
3
4
|
import { WebsocketsSqlFeature } from "@webiny/api-websockets-sql";
|
|
4
5
|
import { AuditLogsSqlFeature } from "@webiny/api-audit-logs-sql";
|
|
5
6
|
const REQUIRED_MODULES = [
|
|
@@ -8,20 +9,24 @@ const REQUIRED_MODULES = [
|
|
|
8
9
|
message: "The Postgres storage has no CMS storage: add <HeadlessCmsPg /> (from @webiny/api-headless-cms-pg/project) to webiny.config.tsx."
|
|
9
10
|
}
|
|
10
11
|
];
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
const PG_STORAGE_TYPE = "postgres";
|
|
13
|
+
const PG_DIALECT = "postgres";
|
|
14
|
+
const PG_STORAGE_LABEL = "Postgres";
|
|
15
|
+
const registerPgParts = (container)=>{
|
|
16
|
+
ApiCoreSqlFeature.register(container);
|
|
17
|
+
AuditLogsSqlFeature.register(container);
|
|
18
|
+
WebsocketsSqlFeature.register(container);
|
|
17
19
|
};
|
|
20
|
+
const PgRequestStorage = createSqlRequestStorage(registerPgParts);
|
|
18
21
|
const setupLockKey = (tableNamePrefix)=>`${tableNamePrefix ?? ""}webiny_schema_setup`;
|
|
19
22
|
class PgSchemaSetupRunner {
|
|
20
|
-
constructor(root, knex, tableNamePrefix, state){
|
|
23
|
+
constructor(root, knex, tableNamePrefix, state, storage, backendOn){
|
|
21
24
|
this.root = root;
|
|
22
25
|
this.knex = knex;
|
|
23
26
|
this.tableNamePrefix = tableNamePrefix;
|
|
24
27
|
this.state = state;
|
|
28
|
+
this.storage = storage;
|
|
29
|
+
this.backendOn = backendOn;
|
|
25
30
|
}
|
|
26
31
|
async run(params) {
|
|
27
32
|
const knex = params.knex ?? this.knex;
|
|
@@ -32,9 +37,11 @@ class PgSchemaSetupRunner {
|
|
|
32
37
|
return runSchemaSetupSteps({
|
|
33
38
|
root: this.root,
|
|
34
39
|
knex: trx,
|
|
40
|
+
dialect: PG_DIALECT,
|
|
35
41
|
tableNamePrefix: this.tableNamePrefix,
|
|
36
42
|
request: params.request,
|
|
37
|
-
required: REQUIRED_MODULES
|
|
43
|
+
required: REQUIRED_MODULES,
|
|
44
|
+
backend: this.backendOn?.(trx)
|
|
38
45
|
});
|
|
39
46
|
});
|
|
40
47
|
this.state.managed = true;
|
|
@@ -43,6 +50,10 @@ class PgSchemaSetupRunner {
|
|
|
43
50
|
}
|
|
44
51
|
class PgStorage {
|
|
45
52
|
constructor(params){
|
|
53
|
+
this.storageId = TenantStorageId.from(params.id);
|
|
54
|
+
this.id = this.storageId.toString();
|
|
55
|
+
this.label = params.label ?? PG_STORAGE_LABEL;
|
|
56
|
+
this.retired = true === params.retired;
|
|
46
57
|
this.knex = params.knex;
|
|
47
58
|
this.tableNamePrefix = params.tableNamePrefix;
|
|
48
59
|
this.state = {
|
|
@@ -50,8 +61,13 @@ class PgStorage {
|
|
|
50
61
|
};
|
|
51
62
|
}
|
|
52
63
|
register(container) {
|
|
64
|
+
if (this.storageId.isDefault()) return void this.registerAsDefault(container);
|
|
65
|
+
this.registerAsExtra(container);
|
|
66
|
+
}
|
|
67
|
+
registerAsDefault(container) {
|
|
53
68
|
SqlConnectionFeature.register(container, {
|
|
54
69
|
knex: this.knex,
|
|
70
|
+
dialect: PG_DIALECT,
|
|
55
71
|
tableNamePrefix: this.tableNamePrefix,
|
|
56
72
|
schemaManaged: ()=>this.state.managed
|
|
57
73
|
});
|
|
@@ -61,7 +77,30 @@ class PgStorage {
|
|
|
61
77
|
schemaManaged: ()=>this.state.managed
|
|
62
78
|
});
|
|
63
79
|
container.registerInstance(RequestStorage, PgRequestStorage);
|
|
64
|
-
container
|
|
80
|
+
registerTenantStorageBackend(container, createDefaultTenantStorageBackend({
|
|
81
|
+
type: PG_STORAGE_TYPE,
|
|
82
|
+
label: this.label
|
|
83
|
+
}));
|
|
84
|
+
container.registerInstance(SqlSchemaSetupRunner, new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id));
|
|
85
|
+
}
|
|
86
|
+
registerAsExtra(container) {
|
|
87
|
+
registerTenantStorageBackend(container, this.backendOn(this.knex, ()=>this.state.managed));
|
|
88
|
+
container.registerInstance(SqlSchemaSetupRunner, new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id, (knex)=>this.backendOn(knex, ()=>false)));
|
|
89
|
+
}
|
|
90
|
+
backendOn(knex, schemaManaged) {
|
|
91
|
+
return createSqlTenantStorageBackend({
|
|
92
|
+
id: this.id,
|
|
93
|
+
label: this.label,
|
|
94
|
+
type: PG_STORAGE_TYPE,
|
|
95
|
+
retired: this.retired,
|
|
96
|
+
connection: {
|
|
97
|
+
knex,
|
|
98
|
+
dialect: PG_DIALECT,
|
|
99
|
+
tableNamePrefix: this.tableNamePrefix,
|
|
100
|
+
schemaManaged
|
|
101
|
+
},
|
|
102
|
+
registerParts: registerPgParts
|
|
103
|
+
});
|
|
65
104
|
}
|
|
66
105
|
}
|
|
67
106
|
function createPgStorage(params) {
|
package/createPgStorage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPgStorage.js","sources":["../src/createPgStorage.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/di\";\nimport { RequestStorage } from \"@webiny/api-core\";\nimport {\n ApiCoreSqlFeature,\n runSchemaSetupSteps,\n setSqlServiceManifestLoader,\n SqlConnectionFeature,\n SqlSchemaSetupRunner,\n type SqlStorage\n} from \"@webiny/api-core-sql\";\nimport { WebsocketsSqlFeature } from \"@webiny/api-websockets-sql\";\nimport { AuditLogsSqlFeature } from \"@webiny/api-audit-logs-sql\";\n\nexport interface CreatePgStorageParams {\n /** The connection: `createPgConnection()` on a server, `createLambdaPgConnection()` on Lambda. */\n knex: Knex;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (at deploy time, by the schema-setup\n * event), so no part of the storage checks for or creates tables at runtime. Off by default:\n * the storage becomes schema-managed once its `SqlSchemaSetupRunner` ran, and until then checks\n * and creates each table on first use.\n */\n schemaManaged?: boolean;\n}\n\n/** What the API on Postgres can't run without: the CMS storage is a module the project adds. */\nconst REQUIRED_MODULES = [\n {\n name: \"cms\",\n message:\n \"The Postgres storage has no CMS storage: add <HeadlessCmsPg /> (from @webiny/api-headless-cms-pg/project) to webiny.config.tsx.\"\n }\n];\n\n/*\n * The storages of a request: SQL core (tenancy, security, users, key-value store), audit logs and\n * the websocket connection registry. Each runs on the connection and table settings in the root.\n */\nconst PgRequestStorage: RequestStorage.Interface = {\n register(container) {\n ApiCoreSqlFeature.register(container);\n AuditLogsSqlFeature.register(container);\n WebsocketsSqlFeature.register(container);\n }\n};\n\n/**\n * The advisory lock every schema setup of one storage takes. Keyed by the table prefix, so storages\n * of different prefixes in one database don't wait for each other.\n */\nconst setupLockKey = (tableNamePrefix?: string): string => {\n return `${tableNamePrefix ?? \"\"}webiny_schema_setup`;\n};\n\n/** Whether the storage's schema is set up. Shared by the storage's root settings and its runner. */\ninterface SchemaState {\n managed: boolean;\n}\n\n/*\n * It all runs in one transaction that first takes an advisory lock, so several processes starting\n * together run it one after another: the second finds everything in place. A failure rolls the\n * whole setup back. The parts that lock on their own (the CMS and the folder catalog) nest in this\n * transaction, so they don't wait for themselves.\n */\nclass PgSchemaSetupRunner implements SqlSchemaSetupRunner.Interface {\n public constructor(\n private readonly root: Container,\n private readonly knex: Knex,\n private readonly tableNamePrefix: string | undefined,\n private readonly state: SchemaState\n ) {}\n\n public async run(params: SqlSchemaSetupRunner.RunParams): Promise<string[]> {\n const knex = params.knex ?? this.knex;\n const done = await knex.transaction(async trx => {\n await trx.raw(\"SELECT pg_advisory_xact_lock(hashtext(?))\", [\n setupLockKey(this.tableNamePrefix)\n ]);\n return runSchemaSetupSteps({\n root: this.root,\n knex: trx,\n tableNamePrefix: this.tableNamePrefix,\n request: params.request,\n required: REQUIRED_MODULES\n });\n });\n this.state.managed = true;\n return done;\n }\n}\n\nclass PgStorage implements SqlStorage {\n public readonly knex: Knex;\n public readonly tableNamePrefix?: string;\n private readonly state: SchemaState;\n\n public constructor(params: CreatePgStorageParams) {\n this.knex = params.knex;\n this.tableNamePrefix = params.tableNamePrefix;\n this.state = { managed: params.schemaManaged === true };\n }\n\n /*\n * The root gets the connection and its settings, the schema setup runner, and service discovery\n * reads the manifests on the connection. Every storage is registered per request, by\n * `PgRequestStorage`.\n */\n public register(container: Container): void {\n SqlConnectionFeature.register(container, {\n knex: this.knex,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n setSqlServiceManifestLoader({\n knex: this.knex,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n container.registerInstance(RequestStorage, PgRequestStorage);\n container.registerInstance(\n SqlSchemaSetupRunner,\n new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state)\n );\n }\n}\n\n/**\n * The Postgres SQL storage of the Webiny API, shared by every transport that runs it on Postgres\n * (the standalone server and AWS Lambda): SQL core, websockets and audit logs. Generic: it holds no\n * CMS and no ACO. Those are modules the project adds with its extensions (`<HeadlessCmsPg />`,\n * `<AcoPg />`), which run on what the storage registers: the connection, the table prefix and the\n * schema-managed setting. Without the CMS module, its schema setup fails, naming it.\n *\n * In the root it registers only the connection and its settings, and its `SqlSchemaSetupRunner`;\n * its storages register in each request's container (`RequestStorage`).\n *\n * Identity is not part of it: each transport brings its own (self-hosted auth on the standalone\n * server, the project's identity provider on Lambda).\n */\nexport function createPgStorage(params: CreatePgStorageParams): SqlStorage {\n return new PgStorage(params);\n}\n"],"names":["REQUIRED_MODULES","PgRequestStorage","container","ApiCoreSqlFeature","AuditLogsSqlFeature","WebsocketsSqlFeature","setupLockKey","tableNamePrefix","PgSchemaSetupRunner","root","knex","state","params","done","trx","runSchemaSetupSteps","PgStorage","SqlConnectionFeature","setSqlServiceManifestLoader","RequestStorage","SqlSchemaSetupRunner","createPgStorage"],"mappings":";;;;AA4BA,MAAMA,mBAAmB;IACrB;QACI,MAAM;QACN,SACI;IACR;CACH;AAMD,MAAMC,mBAA6C;IAC/C,UAASC,SAAS;QACdC,kBAAkB,QAAQ,CAACD;QAC3BE,oBAAoB,QAAQ,CAACF;QAC7BG,qBAAqB,QAAQ,CAACH;IAClC;AACJ;AAMA,MAAMI,eAAe,CAACC,kBACX,GAAGA,mBAAmB,GAAG,mBAAmB,CAAC;AAcxD,MAAMC;IACF,YACqBC,IAAe,EACfC,IAAU,EACVH,eAAmC,EACnCI,KAAkB,CACrC;aAJmBF,IAAI,GAAJA;aACAC,IAAI,GAAJA;aACAH,eAAe,GAAfA;aACAI,KAAK,GAALA;IAClB;IAEH,MAAa,IAAIC,MAAsC,EAAqB;QACxE,MAAMF,OAAOE,OAAO,IAAI,IAAI,IAAI,CAAC,IAAI;QACrC,MAAMC,OAAO,MAAMH,KAAK,WAAW,CAAC,OAAMI;YACtC,MAAMA,IAAI,GAAG,CAAC,6CAA6C;gBACvDR,aAAa,IAAI,CAAC,eAAe;aACpC;YACD,OAAOS,oBAAoB;gBACvB,MAAM,IAAI,CAAC,IAAI;gBACf,MAAMD;gBACN,iBAAiB,IAAI,CAAC,eAAe;gBACrC,SAASF,OAAO,OAAO;gBACvB,UAAUZ;YACd;QACJ;QACA,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG;QACrB,OAAOa;IACX;AACJ;AAEA,MAAMG;IAKF,YAAmBJ,MAA6B,CAAE;QAC9C,IAAI,CAAC,IAAI,GAAGA,OAAO,IAAI;QACvB,IAAI,CAAC,eAAe,GAAGA,OAAO,eAAe;QAC7C,IAAI,CAAC,KAAK,GAAG;YAAE,SAASA,AAAyB,SAAzBA,OAAO,aAAa;QAAU;IAC1D;IAOO,SAASV,SAAoB,EAAQ;QACxCe,qBAAqB,QAAQ,CAACf,WAAW;YACrC,MAAM,IAAI,CAAC,IAAI;YACf,iBAAiB,IAAI,CAAC,eAAe;YACrC,eAAe,IAAM,IAAI,CAAC,KAAK,CAAC,OAAO;QAC3C;QACAgB,4BAA4B;YACxB,MAAM,IAAI,CAAC,IAAI;YACf,iBAAiB,IAAI,CAAC,eAAe;YACrC,eAAe,IAAM,IAAI,CAAC,KAAK,CAAC,OAAO;QAC3C;QACAhB,UAAU,gBAAgB,CAACiB,gBAAgBlB;QAC3CC,UAAU,gBAAgB,CACtBkB,sBACA,IAAIZ,oBAAoBN,WAAW,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,eAAe,EAAE,IAAI,CAAC,KAAK;IAEtF;AACJ;AAeO,SAASmB,gBAAgBT,MAA6B;IACzD,OAAO,IAAII,UAAUJ;AACzB"}
|
|
1
|
+
{"version":3,"file":"createPgStorage.js","sources":["../src/createPgStorage.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/di\";\nimport { RequestStorage } from \"@webiny/api-core\";\nimport {\n ApiCoreSqlFeature,\n createSqlRequestStorage,\n createSqlTenantStorageBackend,\n registerTenantStorageBackend,\n runSchemaSetupSteps,\n setSqlServiceManifestLoader,\n SqlConnectionFeature,\n type SqlDialect,\n SqlSchemaSetupRunner,\n type SqlStorage,\n type SqlStorageIdentityParams\n} from \"@webiny/api-core-sql\";\nimport {\n createDefaultTenantStorageBackend,\n TenantStorageId,\n type TenantStorageBackend\n} from \"@webiny/api-core/features/tenancy/TenantStorages/index.js\";\nimport { WebsocketsSqlFeature } from \"@webiny/api-websockets-sql\";\nimport { AuditLogsSqlFeature } from \"@webiny/api-audit-logs-sql\";\n\nexport interface CreatePgStorageParams extends SqlStorageIdentityParams {\n /** The connection: `createPgConnection()` on a server, `createLambdaPgConnection()` on Lambda. */\n knex: Knex;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (at deploy time, by the schema-setup\n * event), so no part of the storage checks for or creates tables at runtime. Off by default:\n * the storage becomes schema-managed once its `SqlSchemaSetupRunner` ran, and until then checks\n * and creates each table on first use.\n */\n schemaManaged?: boolean;\n}\n\n/** What the API on Postgres can't run without: the CMS storage is a module the project adds. */\nconst REQUIRED_MODULES = [\n {\n name: \"cms\",\n message:\n \"The Postgres storage has no CMS storage: add <HeadlessCmsPg /> (from @webiny/api-headless-cms-pg/project) to webiny.config.tsx.\"\n }\n];\n\n/** The storage's family, as `TenantStorages` lists it. */\nconst PG_STORAGE_TYPE = \"postgres\";\n/** The connection's database family, registered with it as `SqlDialect`. */\nconst PG_DIALECT: SqlDialect.Name = \"postgres\";\nconst PG_STORAGE_LABEL = \"Postgres\";\n\n/*\n * The storage's parts of a tenant scope: SQL core (tenancy, security, users, key-value store), audit\n * logs and the websocket connection registry. Each runs on the scope's connection and table settings:\n * the root's for the default storage, the scope's own for an extra one.\n */\nconst registerPgParts = (container: Container): void => {\n ApiCoreSqlFeature.register(container);\n AuditLogsSqlFeature.register(container);\n WebsocketsSqlFeature.register(container);\n};\n\nconst PgRequestStorage: RequestStorage.Interface = createSqlRequestStorage(registerPgParts);\n\n/**\n * The advisory lock every schema setup of one storage takes. Keyed by the table prefix, so storages\n * of different prefixes in one database don't wait for each other.\n */\nconst setupLockKey = (tableNamePrefix?: string): string => {\n return `${tableNamePrefix ?? \"\"}webiny_schema_setup`;\n};\n\n/** Whether the storage's schema is set up. Shared by the storage's root settings and its runner. */\ninterface SchemaState {\n managed: boolean;\n}\n\n/*\n * It all runs in one transaction that first takes an advisory lock, so several processes starting\n * together run it one after another: the second finds everything in place. A failure rolls the\n * whole setup back. The parts that lock on their own (the CMS and the folder catalog) nest in this\n * transaction, so they don't wait for themselves.\n */\nclass PgSchemaSetupRunner implements SqlSchemaSetupRunner.Interface {\n public constructor(\n private readonly root: Container,\n private readonly knex: Knex,\n private readonly tableNamePrefix: string | undefined,\n private readonly state: SchemaState,\n public readonly storage: string,\n /** An extra storage's backend on the setup's connection; none for the default storage. */\n private readonly backendOn?: (knex: Knex) => TenantStorageBackend.Interface\n ) {}\n\n public async run(params: SqlSchemaSetupRunner.RunParams): Promise<string[]> {\n const knex = params.knex ?? this.knex;\n const done = await knex.transaction(async trx => {\n await trx.raw(\"SELECT pg_advisory_xact_lock(hashtext(?))\", [\n setupLockKey(this.tableNamePrefix)\n ]);\n return runSchemaSetupSteps({\n root: this.root,\n knex: trx,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n request: params.request,\n required: REQUIRED_MODULES,\n backend: this.backendOn?.(trx)\n });\n });\n this.state.managed = true;\n return done;\n }\n}\n\nclass PgStorage implements SqlStorage {\n public readonly id: string;\n public readonly knex: Knex;\n private readonly storageId: TenantStorageId;\n public readonly tableNamePrefix?: string;\n private readonly label: string;\n private readonly retired: boolean;\n private readonly state: SchemaState;\n\n public constructor(params: CreatePgStorageParams) {\n this.storageId = TenantStorageId.from(params.id);\n this.id = this.storageId.toString();\n this.label = params.label ?? PG_STORAGE_LABEL;\n this.retired = params.retired === true;\n this.knex = params.knex;\n this.tableNamePrefix = params.tableNamePrefix;\n this.state = { managed: params.schemaManaged === true };\n }\n\n public register(container: Container): void {\n if (this.storageId.isDefault()) {\n this.registerAsDefault(container);\n return;\n }\n this.registerAsExtra(container);\n }\n\n /*\n * The root gets the connection and its settings, the schema setup runner, and service discovery\n * reads the manifests on the connection. Every storage is registered per scope, by\n * `PgRequestStorage`, which the default storage's backend registers.\n */\n private registerAsDefault(container: Container): void {\n SqlConnectionFeature.register(container, {\n knex: this.knex,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n setSqlServiceManifestLoader({\n knex: this.knex,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n container.registerInstance(RequestStorage, PgRequestStorage);\n registerTenantStorageBackend(\n container,\n createDefaultTenantStorageBackend({ type: PG_STORAGE_TYPE, label: this.label })\n );\n container.registerInstance(\n SqlSchemaSetupRunner,\n new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id)\n );\n }\n\n /*\n * The root gets only the storage's backend and its schema setup runner: the connection is\n * registered in each scope on the storage, never in the root, where it would replace the default\n * storage's. Service discovery stays on the default storage.\n */\n private registerAsExtra(container: Container): void {\n registerTenantStorageBackend(\n container,\n this.backendOn(this.knex, () => this.state.managed)\n );\n container.registerInstance(\n SqlSchemaSetupRunner,\n new PgSchemaSetupRunner(\n container,\n this.knex,\n this.tableNamePrefix,\n this.state,\n this.id,\n // The setup's connection is a transaction: nothing is set up yet.\n knex => this.backendOn(knex, () => false)\n )\n );\n }\n\n private backendOn(knex: Knex, schemaManaged: () => boolean): TenantStorageBackend.Interface {\n return createSqlTenantStorageBackend({\n id: this.id,\n label: this.label,\n type: PG_STORAGE_TYPE,\n retired: this.retired,\n connection: {\n knex,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged\n },\n registerParts: registerPgParts\n });\n }\n}\n\n/**\n * The Postgres SQL storage of the Webiny API, shared by every transport that runs it on Postgres\n * (the standalone server and AWS Lambda): SQL core, websockets and audit logs. It is the deploy's\n * default storage, or, with an `id`, an extra storage that only the tenants naming it in\n * `settings.storage` run on (see `SqlStorage.register`). Generic: it holds no\n * CMS and no ACO. Those are modules the project adds with its extensions (`<HeadlessCmsPg />`,\n * `<AcoPg />`), which run on what the storage registers: the connection, the table prefix and the\n * schema-managed setting. Without the CMS module, its schema setup fails, naming it.\n *\n * In the root it registers only the connection and its settings, and its `SqlSchemaSetupRunner`;\n * its storages register in each request's container (`RequestStorage`).\n *\n * Identity is not part of it: each transport brings its own (self-hosted auth on the standalone\n * server, the project's identity provider on Lambda).\n */\nexport function createPgStorage(params: CreatePgStorageParams): SqlStorage {\n return new PgStorage(params);\n}\n"],"names":["REQUIRED_MODULES","PG_STORAGE_TYPE","PG_DIALECT","PG_STORAGE_LABEL","registerPgParts","container","ApiCoreSqlFeature","AuditLogsSqlFeature","WebsocketsSqlFeature","PgRequestStorage","createSqlRequestStorage","setupLockKey","tableNamePrefix","PgSchemaSetupRunner","root","knex","state","storage","backendOn","params","done","trx","runSchemaSetupSteps","PgStorage","TenantStorageId","SqlConnectionFeature","setSqlServiceManifestLoader","RequestStorage","registerTenantStorageBackend","createDefaultTenantStorageBackend","SqlSchemaSetupRunner","schemaManaged","createSqlTenantStorageBackend","createPgStorage"],"mappings":";;;;;AAsCA,MAAMA,mBAAmB;IACrB;QACI,MAAM;QACN,SACI;IACR;CACH;AAGD,MAAMC,kBAAkB;AAExB,MAAMC,aAA8B;AACpC,MAAMC,mBAAmB;AAOzB,MAAMC,kBAAkB,CAACC;IACrBC,kBAAkB,QAAQ,CAACD;IAC3BE,oBAAoB,QAAQ,CAACF;IAC7BG,qBAAqB,QAAQ,CAACH;AAClC;AAEA,MAAMI,mBAA6CC,wBAAwBN;AAM3E,MAAMO,eAAe,CAACC,kBACX,GAAGA,mBAAmB,GAAG,mBAAmB,CAAC;AAcxD,MAAMC;IACF,YACqBC,IAAe,EACfC,IAAU,EACVH,eAAmC,EACnCI,KAAkB,EACnBC,OAAe,EAEdC,SAA0D,CAC7E;aAPmBJ,IAAI,GAAJA;aACAC,IAAI,GAAJA;aACAH,eAAe,GAAfA;aACAI,KAAK,GAALA;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
1
|
+
import type { Knex } from "knex";
|
|
2
|
+
import type { SqlStorage } from "@webiny/api-core-sql";
|
|
3
|
+
/** The env var the extra storages are read from. `webiny watch` and `serve` set it from the config. */
|
|
4
|
+
export declare const TENANT_STORAGES_ENV = "WEBINY_TENANT_STORAGES";
|
|
5
|
+
/** One extra storage in `WEBINY_TENANT_STORAGES`. */
|
|
6
|
+
export interface TenantStorageEnvEntry {
|
|
7
|
+
id: string;
|
|
8
|
+
label: string;
|
|
9
|
+
retired?: boolean;
|
|
10
|
+
/** The storage's family. Only `postgres` is read here. */
|
|
11
|
+
type: string;
|
|
12
|
+
/** The storage's connection, under the `WEBINY_PG_*` names `<Infra.Postgres>` uses. */
|
|
13
|
+
connection: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
type Env = Record<string, string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* The extra storages in `WEBINY_TENANT_STORAGES`, checked: a malformed value stops the API with a
|
|
18
|
+
* message naming the variable, rather than a connection error later. Unset or empty means none.
|
|
19
|
+
*/
|
|
20
|
+
export declare function readTenantStoragesEnv(env?: Env): TenantStorageEnvEntry[];
|
|
21
|
+
export interface CreatePgTenantStoragesParams {
|
|
22
|
+
/**
|
|
23
|
+
* The ids of the storages the build declares (`<Infra.TenantStorage.*>`). Each must be in the
|
|
24
|
+
* env, and the env may hold no other: a storage the build doesn't know would put tenants on a
|
|
25
|
+
* database nobody declared.
|
|
26
|
+
*/
|
|
27
|
+
ids: string[];
|
|
28
|
+
/** Where `WEBINY_TENANT_STORAGES` is read from. Default: `process.env`. */
|
|
29
|
+
env?: Env;
|
|
30
|
+
/** Builds a storage's connection from its settings. Default: `createPgConnection`. */
|
|
31
|
+
connect?: (connection: Record<string, string>) => Knex;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The extra Postgres storages of the standalone API, each with its own connection pool, for
|
|
35
|
+
* `createSqlApiHandler({ storages })`. Their connections are read from `WEBINY_TENANT_STORAGES` when
|
|
36
|
+
* the API starts; the default storage's `WEBINY_PG_*` settings never fill in for one.
|
|
37
|
+
*/
|
|
38
|
+
export declare function createPgTenantStorages(params: CreatePgTenantStoragesParams): SqlStorage[];
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createPgConnection } from "./createPgConnection.js";
|
|
2
|
+
import { createPgStorage } from "./createPgStorage.js";
|
|
3
|
+
const TENANT_STORAGES_ENV = "WEBINY_TENANT_STORAGES";
|
|
4
|
+
const isRecord = (value)=>"object" == typeof value && null !== value && !Array.isArray(value);
|
|
5
|
+
const isStringRecord = (value)=>isRecord(value) && Object.values(value).every((item)=>"string" == typeof item);
|
|
6
|
+
function readTenantStoragesEnv(env = process.env) {
|
|
7
|
+
const raw = env[TENANT_STORAGES_ENV];
|
|
8
|
+
if (!raw) return [];
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = JSON.parse(raw);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
throw new Error(`${TENANT_STORAGES_ENV} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}.`);
|
|
14
|
+
}
|
|
15
|
+
if (!Array.isArray(parsed)) throw new Error(`${TENANT_STORAGES_ENV} must be a JSON list of storages.`);
|
|
16
|
+
return parsed.map((entry, index)=>{
|
|
17
|
+
const valid = isRecord(entry) && "string" == typeof entry.id && entry.id.length > 0 && "string" == typeof entry.label && "string" == typeof entry.type && (void 0 === entry.retired || "boolean" == typeof entry.retired) && isStringRecord(entry.connection);
|
|
18
|
+
if (!valid) throw new Error(`${TENANT_STORAGES_ENV}[${index}] must have a string "id", "label" and "type", an optional boolean "retired", and a "connection" of string settings.`);
|
|
19
|
+
return entry;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function createPgTenantStorages(params) {
|
|
23
|
+
const entries = readTenantStoragesEnv(params.env);
|
|
24
|
+
const connect = params.connect ?? ((connection)=>createPgConnection({
|
|
25
|
+
env: connection
|
|
26
|
+
}));
|
|
27
|
+
for (const id of params.ids)if (!entries.some((entry)=>entry.id === id)) throw new Error(`Storage "${id}" is declared in webiny.config, but ${TENANT_STORAGES_ENV} has no connection for it. \`webiny watch\` and \`webiny-standalone serve\` set it from the config; a server started otherwise needs it in its environment.`);
|
|
28
|
+
return entries.map((entry)=>{
|
|
29
|
+
if (!params.ids.includes(entry.id)) throw new Error(`${TENANT_STORAGES_ENV} has storage "${entry.id}", which webiny.config doesn't declare. Declare it with <Infra.TenantStorage.*> and build again.`);
|
|
30
|
+
if ("postgres" !== entry.type) throw new Error(`Storage "${entry.id}" in ${TENANT_STORAGES_ENV} is of type "${entry.type}"; the standalone API runs extra storages on Postgres only.`);
|
|
31
|
+
return createPgStorage({
|
|
32
|
+
id: entry.id,
|
|
33
|
+
label: entry.label,
|
|
34
|
+
retired: true === entry.retired,
|
|
35
|
+
knex: connect(entry.connection)
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
export { TENANT_STORAGES_ENV, createPgTenantStorages, readTenantStoragesEnv };
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=createPgTenantStorages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createPgTenantStorages.js","sources":["../src/createPgTenantStorages.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { SqlStorage } from \"@webiny/api-core-sql\";\nimport { createPgConnection } from \"./createPgConnection.js\";\nimport { createPgStorage } from \"./createPgStorage.js\";\n\n/** The env var the extra storages are read from. `webiny watch` and `serve` set it from the config. */\nexport const TENANT_STORAGES_ENV = \"WEBINY_TENANT_STORAGES\";\n\n/** One extra storage in `WEBINY_TENANT_STORAGES`. */\nexport interface TenantStorageEnvEntry {\n id: string;\n label: string;\n retired?: boolean;\n /** The storage's family. Only `postgres` is read here. */\n type: string;\n /** The storage's connection, under the `WEBINY_PG_*` names `<Infra.Postgres>` uses. */\n connection: Record<string, string>;\n}\n\ntype Env = Record<string, string | undefined>;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst isStringRecord = (value: unknown): value is Record<string, string> => {\n return isRecord(value) && Object.values(value).every(item => typeof item === \"string\");\n};\n\n/**\n * The extra storages in `WEBINY_TENANT_STORAGES`, checked: a malformed value stops the API with a\n * message naming the variable, rather than a connection error later. Unset or empty means none.\n */\nexport function readTenantStoragesEnv(env: Env = process.env): TenantStorageEnvEntry[] {\n const raw = env[TENANT_STORAGES_ENV];\n if (!raw) {\n return [];\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new Error(\n `${TENANT_STORAGES_ENV} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}.`\n );\n }\n if (!Array.isArray(parsed)) {\n throw new Error(`${TENANT_STORAGES_ENV} must be a JSON list of storages.`);\n }\n\n return parsed.map((entry, index) => {\n const valid =\n isRecord(entry) &&\n typeof entry.id === \"string\" &&\n entry.id.length > 0 &&\n typeof entry.label === \"string\" &&\n typeof entry.type === \"string\" &&\n (entry.retired === undefined || typeof entry.retired === \"boolean\") &&\n isStringRecord(entry.connection);\n if (!valid) {\n throw new Error(\n `${TENANT_STORAGES_ENV}[${index}] must have a string \"id\", \"label\" and \"type\", an optional boolean \"retired\", and a \"connection\" of string settings.`\n );\n }\n return entry as unknown as TenantStorageEnvEntry;\n });\n}\n\nexport interface CreatePgTenantStoragesParams {\n /**\n * The ids of the storages the build declares (`<Infra.TenantStorage.*>`). Each must be in the\n * env, and the env may hold no other: a storage the build doesn't know would put tenants on a\n * database nobody declared.\n */\n ids: string[];\n /** Where `WEBINY_TENANT_STORAGES` is read from. Default: `process.env`. */\n env?: Env;\n /** Builds a storage's connection from its settings. Default: `createPgConnection`. */\n connect?: (connection: Record<string, string>) => Knex;\n}\n\n/**\n * The extra Postgres storages of the standalone API, each with its own connection pool, for\n * `createSqlApiHandler({ storages })`. Their connections are read from `WEBINY_TENANT_STORAGES` when\n * the API starts; the default storage's `WEBINY_PG_*` settings never fill in for one.\n */\nexport function createPgTenantStorages(params: CreatePgTenantStoragesParams): SqlStorage[] {\n const entries = readTenantStoragesEnv(params.env);\n const connect =\n params.connect ??\n ((connection: Record<string, string>) => createPgConnection({ env: connection }));\n\n for (const id of params.ids) {\n if (!entries.some(entry => entry.id === id)) {\n throw new Error(\n `Storage \"${id}\" is declared in webiny.config, but ${TENANT_STORAGES_ENV} has no connection for it. \\`webiny watch\\` and \\`webiny-standalone serve\\` set it from the config; a server started otherwise needs it in its environment.`\n );\n }\n }\n\n return entries.map(entry => {\n if (!params.ids.includes(entry.id)) {\n throw new Error(\n `${TENANT_STORAGES_ENV} has storage \"${entry.id}\", which webiny.config doesn't declare. Declare it with <Infra.TenantStorage.*> and build again.`\n );\n }\n if (entry.type !== \"postgres\") {\n throw new Error(\n `Storage \"${entry.id}\" in ${TENANT_STORAGES_ENV} is of type \"${entry.type}\"; the standalone API runs extra storages on Postgres only.`\n );\n }\n return createPgStorage({\n id: entry.id,\n label: entry.label,\n retired: entry.retired === true,\n knex: connect(entry.connection)\n });\n });\n}\n"],"names":["TENANT_STORAGES_ENV","isRecord","value","Array","isStringRecord","Object","item","readTenantStoragesEnv","env","process","raw","parsed","JSON","error","Error","String","entry","index","valid","undefined","createPgTenantStorages","params","entries","connect","connection","createPgConnection","id","createPgStorage"],"mappings":";;AAMO,MAAMA,sBAAsB;AAenC,MAAMC,WAAW,CAACC,QACP,AAAiB,YAAjB,OAAOA,SAAsBA,AAAU,SAAVA,SAAkB,CAACC,MAAM,OAAO,CAACD;AAGzE,MAAME,iBAAiB,CAACF,QACbD,SAASC,UAAUG,OAAO,MAAM,CAACH,OAAO,KAAK,CAACI,CAAAA,OAAQ,AAAgB,YAAhB,OAAOA;AAOjE,SAASC,sBAAsBC,MAAWC,QAAQ,GAAG;IACxD,MAAMC,MAAMF,GAAG,CAACR,oBAAoB;IACpC,IAAI,CAACU,KACD,OAAO,EAAE;IAGb,IAAIC;IACJ,IAAI;QACAA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AEgB,MAAM,EAAE,CAAC,gGAAgG,CAAC;QAGzJ,IAAIA,AAAe,eAAfA,MAAM,IAAI,EACV,MAAM,IAAIF,MACN,CAAC,SAAS,EAAEE,MAAM,EAAE,CAAC,KAAK,EAAEhB,oBAAoB,aAAa,EAAEgB,MAAM,IAAI,CAAC,2DAA2D,CAAC;QAG9I,OAAOW,gBAAgB;YACnB,IAAIX,MAAM,EAAE;YACZ,OAAOA,MAAM,KAAK;YAClB,SAASA,AAAkB,SAAlBA,MAAM,OAAO;YACtB,MAAMO,QAAQP,MAAM,UAAU;QAClC;IACJ;AACJ"}
|
package/index.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export { applyToPgConnectionString, pgConnectionStringPassword } from "./applyTo
|
|
|
6
6
|
export type { PgConnectionStringValues } from "./applyToPgConnectionString.js";
|
|
7
7
|
export { readPgConnectionEnv, DEFAULT_PG_RETRY_MS } from "./readPgConnectionEnv.js";
|
|
8
8
|
export type { PgConnectionEnv } from "./readPgConnectionEnv.js";
|
|
9
|
+
export { createPgTenantStorages, readTenantStoragesEnv, TENANT_STORAGES_ENV } from "./createPgTenantStorages.js";
|
|
10
|
+
export type { CreatePgTenantStoragesParams, TenantStorageEnvEntry } from "./createPgTenantStorages.js";
|
package/index.js
CHANGED
|
@@ -2,3 +2,4 @@ export { createPgStorage } from "./createPgStorage.js";
|
|
|
2
2
|
export { createPgConnection } from "./createPgConnection.js";
|
|
3
3
|
export { applyToPgConnectionString, pgConnectionStringPassword } from "./applyToPgConnectionString.js";
|
|
4
4
|
export { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from "./readPgConnectionEnv.js";
|
|
5
|
+
export { TENANT_STORAGES_ENV, createPgTenantStorages, readTenantStoragesEnv } from "./createPgTenantStorages.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webiny/api-storage-pg",
|
|
3
|
-
"version": "0.0.0-unstable.
|
|
3
|
+
"version": "0.0.0-unstable.48a4e5b6c1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"exports": {
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
],
|
|
19
19
|
"license": "MIT",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@webiny/api-audit-logs-sql": "0.0.0-unstable.
|
|
22
|
-
"@webiny/api-core": "0.0.0-unstable.
|
|
23
|
-
"@webiny/api-core-sql": "0.0.0-unstable.
|
|
24
|
-
"@webiny/api-websockets-sql": "0.0.0-unstable.
|
|
21
|
+
"@webiny/api-audit-logs-sql": "0.0.0-unstable.48a4e5b6c1",
|
|
22
|
+
"@webiny/api-core": "0.0.0-unstable.48a4e5b6c1",
|
|
23
|
+
"@webiny/api-core-sql": "0.0.0-unstable.48a4e5b6c1",
|
|
24
|
+
"@webiny/api-websockets-sql": "0.0.0-unstable.48a4e5b6c1",
|
|
25
25
|
"@webiny/stdlib": "0.0.21",
|
|
26
26
|
"knex": "3.3.0",
|
|
27
27
|
"pg": "8.23.1"
|
|
@@ -30,15 +30,15 @@
|
|
|
30
30
|
"@webiny/di": "^2.0.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@electric-sql/pglite": "0.5.
|
|
34
|
-
"@electric-sql/pglite-socket": "0.2.
|
|
35
|
-
"@webiny/api-audit-logs": "0.0.0-unstable.
|
|
36
|
-
"@webiny/api-websockets": "0.0.0-unstable.
|
|
37
|
-
"@webiny/build-tools": "0.0.0-unstable.
|
|
33
|
+
"@electric-sql/pglite": "0.5.17",
|
|
34
|
+
"@electric-sql/pglite-socket": "0.2.20",
|
|
35
|
+
"@webiny/api-audit-logs": "0.0.0-unstable.48a4e5b6c1",
|
|
36
|
+
"@webiny/api-websockets": "0.0.0-unstable.48a4e5b6c1",
|
|
37
|
+
"@webiny/build-tools": "0.0.0-unstable.48a4e5b6c1",
|
|
38
38
|
"@webiny/di": "2.0.0",
|
|
39
|
-
"rimraf": "6.1.
|
|
39
|
+
"rimraf": "6.1.4",
|
|
40
40
|
"typescript": "7.0.2",
|
|
41
|
-
"vitest": "5.
|
|
41
|
+
"vitest": "5.1.1"
|
|
42
42
|
},
|
|
43
43
|
"adio": {
|
|
44
44
|
"ignore": {
|