@webiny/api-core-sql 6.6.0-alpha.10 → 6.6.0-alpha.11

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.
Files changed (66) hide show
  1. package/TableManager.d.ts +23 -20
  2. package/TableManager.js +22 -35
  3. package/TableManager.js.map +1 -1
  4. package/connection/SqlConnectionFeature.d.ts +28 -0
  5. package/connection/SqlConnectionFeature.js +26 -0
  6. package/connection/SqlConnectionFeature.js.map +1 -0
  7. package/connection/index.d.ts +2 -0
  8. package/connection/index.js +1 -0
  9. package/coreStorage/CoreSqlSchemaSetup.d.ts +18 -0
  10. package/coreStorage/CoreSqlSchemaSetup.js +35 -0
  11. package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
  12. package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
  13. package/coreStorage/SqlApiCoreStorageOperationsFactory.js +32 -0
  14. package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
  15. package/coreStorage/feature.d.ts +13 -0
  16. package/coreStorage/feature.js +13 -0
  17. package/coreStorage/feature.js.map +1 -0
  18. package/coreStorage/index.d.ts +1 -0
  19. package/coreStorage/index.js +1 -0
  20. package/createApiCoreSql.d.ts +13 -1
  21. package/createApiCoreSql.js +8 -8
  22. package/createApiCoreSql.js.map +1 -1
  23. package/index.d.ts +14 -4
  24. package/index.js +8 -3
  25. package/index.js.map +1 -1
  26. package/package.json +6 -6
  27. package/schemaConfig/abstractions.d.ts +22 -0
  28. package/schemaConfig/abstractions.js +5 -0
  29. package/schemaConfig/abstractions.js.map +1 -0
  30. package/schemaConfig/index.d.ts +1 -0
  31. package/schemaConfig/index.js +1 -0
  32. package/schemaMemory/ensureTable.d.ts +28 -0
  33. package/schemaMemory/ensureTable.js +43 -0
  34. package/schemaMemory/ensureTable.js.map +1 -0
  35. package/schemaMemory/getConnectionKey.d.ts +8 -0
  36. package/schemaMemory/getConnectionKey.js +15 -0
  37. package/schemaMemory/getConnectionKey.js.map +1 -0
  38. package/schemaMemory/getSchemaMemory.d.ts +37 -0
  39. package/schemaMemory/getSchemaMemory.js +53 -0
  40. package/schemaMemory/getSchemaMemory.js.map +1 -0
  41. package/schemaSetup/abstractions.d.ts +67 -0
  42. package/schemaSetup/abstractions.js +6 -0
  43. package/schemaSetup/abstractions.js.map +1 -0
  44. package/schemaSetup/index.d.ts +4 -0
  45. package/schemaSetup/index.js +2 -0
  46. package/schemaSetup/runSchemaSetupSteps.d.ts +34 -0
  47. package/schemaSetup/runSchemaSetupSteps.js +35 -0
  48. package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
  49. package/serviceDiscovery/SqlServiceManifestLoader.js +3 -6
  50. package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
  51. package/serviceDiscovery/SqlServiceManifestWriter.d.ts +16 -0
  52. package/serviceDiscovery/SqlServiceManifestWriter.js +27 -0
  53. package/serviceDiscovery/SqlServiceManifestWriter.js.map +1 -0
  54. package/serviceDiscovery/index.d.ts +1 -0
  55. package/serviceDiscovery/index.js +1 -0
  56. package/serviceDiscovery/serviceManifestsTable.d.ts +13 -0
  57. package/serviceDiscovery/serviceManifestsTable.js +8 -0
  58. package/serviceDiscovery/serviceManifestsTable.js.map +1 -0
  59. package/storage/types.d.ts +22 -0
  60. package/storage/types.js +0 -0
  61. package/ApiCoreSqlFeature.d.ts +0 -18
  62. package/ApiCoreSqlFeature.js +0 -18
  63. package/ApiCoreSqlFeature.js.map +0 -1
  64. package/schemaManaged.d.ts +0 -8
  65. package/schemaManaged.js +0 -4
  66. package/schemaManaged.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaConfig/abstractions.js","sources":["../../src/schemaConfig/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface ISqlSchemaConfig {\n /**\n * Whether the schema was set up before the API took traffic (the storage's schema setup ran).\n * When it is, storage code never checks for or creates tables at runtime: no catalog queries\n * and no DDL on a cold start. When it isn't, each table is checked and created on first use.\n */\n isManaged(): boolean;\n /**\n * The prefix of every table the storage uses. Modules registered after the storage (the\n * Postgres CMS and folder catalog) name their tables with it.\n */\n readonly tableNamePrefix?: string;\n}\n\n/**\n * How the SQL storage finds its tables, set by the storage that registers it. Optional for the\n * code that only reads `isManaged()`: when it isn't registered, tables are checked and created on\n * first use.\n */\nexport const SqlSchemaConfig = createAbstraction<ISqlSchemaConfig>(\"Db/Sql/SchemaConfig\");\n\nexport namespace SqlSchemaConfig {\n export type Interface = ISqlSchemaConfig;\n}\n"],"names":["SqlSchemaConfig","createAbstraction"],"mappings":";AAqBO,MAAMA,kBAAkBC,kBAAoC"}
@@ -0,0 +1 @@
1
+ export { SqlSchemaConfig } from "./abstractions.js";
@@ -0,0 +1 @@
1
+ export { SqlSchemaConfig } from "./abstractions.js";
@@ -0,0 +1,28 @@
1
+ import type { Knex } from "knex";
2
+ import type { ISchemaMemory } from "./getSchemaMemory.js";
3
+ export type TableCreator = (table: Knex.CreateTableBuilder) => void;
4
+ export interface EnsureTableParams {
5
+ /** The connection or transaction to check and create the table on. */
6
+ knex: Knex;
7
+ /** What the process knows about the tables this one belongs to. */
8
+ memory: ISchemaMemory;
9
+ tableName: string;
10
+ create: TableCreator;
11
+ }
12
+ /**
13
+ * Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,
14
+ * and concurrent callers on the same handle wait for one check. What a transaction creates is
15
+ * remembered only by `recordTable` after it commits, never here, and nothing started before the
16
+ * memory was reset is recorded after it.
17
+ */
18
+ export declare function ensureTable(params: EnsureTableParams): Promise<void>;
19
+ /**
20
+ * Records that the table exists, unless `knex` is a transaction: it can still roll back, and the
21
+ * table with it, so only a committed table is known.
22
+ */
23
+ export declare function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void;
24
+ /**
25
+ * Creates the table if it doesn't exist. Another process (or connection) may create it between the
26
+ * check and the create: if it exists after a failed create, that's success.
27
+ */
28
+ export declare function createTableIfMissing(knex: Knex, tableName: string, create: TableCreator): Promise<void>;
@@ -0,0 +1,43 @@
1
+ const inFlight = new Map();
2
+ const transactionIds = new WeakMap();
3
+ let lastTransactionId = 0;
4
+ const handleOf = (knex)=>{
5
+ if (!knex.isTransaction) return "connection";
6
+ let id = transactionIds.get(knex);
7
+ if (void 0 === id) {
8
+ lastTransactionId += 1;
9
+ id = lastTransactionId;
10
+ transactionIds.set(knex, id);
11
+ }
12
+ return `trx${id}`;
13
+ };
14
+ function ensureTable(params) {
15
+ const { knex, memory, tableName, create } = params;
16
+ if (memory.known.has(tableName)) return Promise.resolve();
17
+ const generation = memory.generation;
18
+ const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;
19
+ const pending = inFlight.get(key);
20
+ if (pending) return pending;
21
+ const check = createTableIfMissing(knex, tableName, create).then(()=>{
22
+ if (memory.generation === generation) recordTable(knex, memory, tableName);
23
+ }).finally(()=>{
24
+ if (inFlight.get(key) === check) inFlight.delete(key);
25
+ });
26
+ inFlight.set(key, check);
27
+ return check;
28
+ }
29
+ function recordTable(knex, memory, tableName) {
30
+ if (!knex.isTransaction) memory.known.add(tableName);
31
+ }
32
+ async function createTableIfMissing(knex, tableName, create) {
33
+ if (await knex.schema.hasTable(tableName)) return;
34
+ try {
35
+ await knex.schema.createTable(tableName, create);
36
+ } catch (error) {
37
+ if (await knex.schema.hasTable(tableName)) return;
38
+ throw error;
39
+ }
40
+ }
41
+ export { createTableIfMissing, ensureTable, recordTable };
42
+
43
+ //# sourceMappingURL=ensureTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/ensureTable.js","sources":["../../src/schemaMemory/ensureTable.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { ISchemaMemory } from \"./getSchemaMemory.js\";\n\nexport type TableCreator = (table: Knex.CreateTableBuilder) => void;\n\nexport interface EnsureTableParams {\n /** The connection or transaction to check and create the table on. */\n knex: Knex;\n /** What the process knows about the tables this one belongs to. */\n memory: ISchemaMemory;\n tableName: string;\n create: TableCreator;\n}\n\n/*\n * Checks in flight, per memory, table and handle, so concurrent first uses share one\n * hasTable+createTable instead of racing into \"table already exists\".\n */\nconst inFlight = new Map<string, Promise<void>>();\n\nconst transactionIds = new WeakMap<object, number>();\nlet lastTransactionId = 0;\n\n/*\n * Which handle a check runs on. A transaction shares its connection's key (`getConnectionKey`), but\n * a table it creates is visible to others only once it commits, and is gone if it rolls back. So a\n * check in a transaction is shared only with checks in that same transaction.\n */\nconst handleOf = (knex: Knex): string => {\n if (!knex.isTransaction) {\n return \"connection\";\n }\n let id = transactionIds.get(knex);\n if (id === undefined) {\n lastTransactionId += 1;\n id = lastTransactionId;\n transactionIds.set(knex, id);\n }\n return `trx${id}`;\n};\n\n/**\n * Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,\n * and concurrent callers on the same handle wait for one check. What a transaction creates is\n * remembered only by `recordTable` after it commits, never here, and nothing started before the\n * memory was reset is recorded after it.\n */\nexport function ensureTable(params: EnsureTableParams): Promise<void> {\n const { knex, memory, tableName, create } = params;\n if (memory.known.has(tableName)) {\n return Promise.resolve();\n }\n\n const generation = memory.generation;\n const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;\n const pending = inFlight.get(key);\n if (pending) {\n return pending;\n }\n\n const check: Promise<void> = createTableIfMissing(knex, tableName, create)\n .then(() => {\n if (memory.generation === generation) {\n recordTable(knex, memory, tableName);\n }\n })\n .finally(() => {\n if (inFlight.get(key) === check) {\n inFlight.delete(key);\n }\n });\n inFlight.set(key, check);\n return check;\n}\n\n/**\n * Records that the table exists, unless `knex` is a transaction: it can still roll back, and the\n * table with it, so only a committed table is known.\n */\nexport function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void {\n if (!knex.isTransaction) {\n memory.known.add(tableName);\n }\n}\n\n/**\n * Creates the table if it doesn't exist. Another process (or connection) may create it between the\n * check and the create: if it exists after a failed create, that's success.\n */\nexport async function createTableIfMissing(\n knex: Knex,\n tableName: string,\n create: TableCreator\n): Promise<void> {\n if (await knex.schema.hasTable(tableName)) {\n return;\n }\n try {\n await knex.schema.createTable(tableName, create);\n } catch (error) {\n if (await knex.schema.hasTable(tableName)) {\n return;\n }\n throw error;\n }\n}\n"],"names":["inFlight","Map","transactionIds","WeakMap","lastTransactionId","handleOf","knex","id","undefined","ensureTable","params","memory","tableName","create","Promise","generation","key","pending","check","createTableIfMissing","recordTable","error"],"mappings":"AAkBA,MAAMA,WAAW,IAAIC;AAErB,MAAMC,iBAAiB,IAAIC;AAC3B,IAAIC,oBAAoB;AAOxB,MAAMC,WAAW,CAACC;IACd,IAAI,CAACA,KAAK,aAAa,EACnB,OAAO;IAEX,IAAIC,KAAKL,eAAe,GAAG,CAACI;IAC5B,IAAIC,AAAOC,WAAPD,IAAkB;QAClBH,qBAAqB;QACrBG,KAAKH;QACLF,eAAe,GAAG,CAACI,MAAMC;IAC7B;IACA,OAAO,CAAC,GAAG,EAAEA,IAAI;AACrB;AAQO,SAASE,YAAYC,MAAyB;IACjD,MAAM,EAAEJ,IAAI,EAAEK,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGH;IAC5C,IAAIC,OAAO,KAAK,CAAC,GAAG,CAACC,YACjB,OAAOE,QAAQ,OAAO;IAG1B,MAAMC,aAAaJ,OAAO,UAAU;IACpC,MAAMK,MAAM,GAAGL,OAAO,GAAG,CAAC,CAAC,EAAEI,WAAW,CAAC,EAAEH,UAAU,CAAC,EAAEP,SAASC,OAAO;IACxE,MAAMW,UAAUjB,SAAS,GAAG,CAACgB;IAC7B,IAAIC,SACA,OAAOA;IAGX,MAAMC,QAAuBC,qBAAqBb,MAAMM,WAAWC,QAC9D,IAAI,CAAC;QACF,IAAIF,OAAO,UAAU,KAAKI,YACtBK,YAAYd,MAAMK,QAAQC;IAElC,GACC,OAAO,CAAC;QACL,IAAIZ,SAAS,GAAG,CAACgB,SAASE,OACtBlB,SAAS,MAAM,CAACgB;IAExB;IACJhB,SAAS,GAAG,CAACgB,KAAKE;IAClB,OAAOA;AACX;AAMO,SAASE,YAAYd,IAAU,EAAEK,MAAqB,EAAEC,SAAiB;IAC5E,IAAI,CAACN,KAAK,aAAa,EACnBK,OAAO,KAAK,CAAC,GAAG,CAACC;AAEzB;AAMO,eAAeO,qBAClBb,IAAU,EACVM,SAAiB,EACjBC,MAAoB;IAEpB,IAAI,MAAMP,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;IAEJ,IAAI;QACA,MAAMN,KAAK,MAAM,CAAC,WAAW,CAACM,WAAWC;IAC7C,EAAE,OAAOQ,OAAO;QACZ,IAAI,MAAMf,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;QAEJ,MAAMS;IACV;AACJ"}
@@ -0,0 +1,8 @@
1
+ import type { Knex } from "knex";
2
+ /**
3
+ * A short id for the database a Knex instance connects to, for keys of the process's schema memory
4
+ * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:
5
+ * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances
6
+ * built separately get different ids, even for the same database.
7
+ */
8
+ export declare function getConnectionKey(knex: Knex): string;
@@ -0,0 +1,15 @@
1
+ const keys = new WeakMap();
2
+ let next = 0;
3
+ function getConnectionKey(knex) {
4
+ const identity = knex.client?.config ?? knex;
5
+ let key = keys.get(identity);
6
+ if (!key) {
7
+ next += 1;
8
+ key = `db${next}`;
9
+ keys.set(identity, key);
10
+ }
11
+ return key;
12
+ }
13
+ export { getConnectionKey };
14
+
15
+ //# sourceMappingURL=getConnectionKey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getConnectionKey.js","sources":["../../src/schemaMemory/getConnectionKey.ts"],"sourcesContent":["import type { Knex } from \"knex\";\n\nconst keys = new WeakMap<object, string>();\nlet next = 0;\n\n/**\n * A short id for the database a Knex instance connects to, for keys of the process's schema memory\n * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:\n * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances\n * built separately get different ids, even for the same database.\n */\nexport function getConnectionKey(knex: Knex): string {\n const identity: object = knex.client?.config ?? knex;\n let key = keys.get(identity);\n if (!key) {\n next += 1;\n key = `db${next}`;\n keys.set(identity, key);\n }\n return key;\n}\n"],"names":["keys","WeakMap","next","getConnectionKey","knex","identity","key"],"mappings":"AAEA,MAAMA,OAAO,IAAIC;AACjB,IAAIC,OAAO;AAQJ,SAASC,iBAAiBC,IAAU;IACvC,MAAMC,WAAmBD,KAAK,MAAM,EAAE,UAAUA;IAChD,IAAIE,MAAMN,KAAK,GAAG,CAACK;IACnB,IAAI,CAACC,KAAK;QACNJ,QAAQ;QACRI,MAAM,CAAC,EAAE,EAAEJ,MAAM;QACjBF,KAAK,GAAG,CAACK,UAAUC;IACvB;IACA,OAAOA;AACX"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What this process knows about some tables: whether they were created, and a set of names it has
3
+ * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the
4
+ * instance that learned it. The Postgres CMS and folder catalog are registered per request (they
5
+ * come with the project's extensions), so each request builds new instances: what they learn about
6
+ * the tables must live here, for the process.
7
+ */
8
+ export interface ISchemaMemory {
9
+ /** What the memory is of: the key it was asked for with. */
10
+ readonly key: string;
11
+ /**
12
+ * Runs `create` once per process; callers at the same time wait for the same run. A failed run is
13
+ * forgotten, so the next call tries again.
14
+ */
15
+ once(create: () => Promise<void>): Promise<void>;
16
+ /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */
17
+ isReady(): boolean;
18
+ /** Records that the tables exist (created in a caller's transaction that has committed). */
19
+ markReady(): void;
20
+ /** Names this process has checked (tables, tenants). */
21
+ readonly known: Set<string>;
22
+ /**
23
+ * Goes up on every `reset()`. Work that started before a reset must not record what it learned
24
+ * after it: compare the value taken at the start with the current one.
25
+ */
26
+ readonly generation: number;
27
+ /** Forgets everything (test setups drop all tables between tests). */
28
+ reset(): void;
29
+ }
30
+ /**
31
+ * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on
32
+ * first use, with `onReset` run whenever it is reset; later callers get the same one.
33
+ *
34
+ * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and
35
+ * call `reset()` on every entry reset it too.
36
+ */
37
+ export declare function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory;
@@ -0,0 +1,53 @@
1
+ class SchemaMemory {
2
+ constructor(key, onReset){
3
+ this.key = key;
4
+ this.onReset = onReset;
5
+ this.known = new Set();
6
+ this.ready = false;
7
+ this.currentGeneration = 0;
8
+ }
9
+ once(create) {
10
+ if (this.ready) return Promise.resolve();
11
+ if (this.pending) return this.pending;
12
+ const generation = this.currentGeneration;
13
+ const run = create().then(()=>{
14
+ if (this.currentGeneration === generation) this.ready = true;
15
+ }, (error)=>{
16
+ if (this.pending === run) this.pending = void 0;
17
+ throw error;
18
+ });
19
+ this.pending = run;
20
+ return run;
21
+ }
22
+ get generation() {
23
+ return this.currentGeneration;
24
+ }
25
+ isReady() {
26
+ return this.ready;
27
+ }
28
+ markReady() {
29
+ this.ready = true;
30
+ }
31
+ reset() {
32
+ this.currentGeneration += 1;
33
+ this.pending = void 0;
34
+ this.ready = false;
35
+ this.known.clear();
36
+ this.onReset?.();
37
+ }
38
+ }
39
+ const memories = new Map();
40
+ function getSchemaMemory(key, onReset) {
41
+ let memory = memories.get(key);
42
+ if (!memory) {
43
+ memory = new SchemaMemory(key, onReset);
44
+ memories.set(key, memory);
45
+ const g = globalThis;
46
+ const managers = g.__sqlTableManagers ??= [];
47
+ managers.push(memory);
48
+ }
49
+ return memory;
50
+ }
51
+ export { getSchemaMemory };
52
+
53
+ //# sourceMappingURL=getSchemaMemory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getSchemaMemory.js","sources":["../../src/schemaMemory/getSchemaMemory.ts"],"sourcesContent":["/**\n * What this process knows about some tables: whether they were created, and a set of names it has\n * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the\n * instance that learned it. The Postgres CMS and folder catalog are registered per request (they\n * come with the project's extensions), so each request builds new instances: what they learn about\n * the tables must live here, for the process.\n */\nexport interface ISchemaMemory {\n /** What the memory is of: the key it was asked for with. */\n readonly key: string;\n /**\n * Runs `create` once per process; callers at the same time wait for the same run. A failed run is\n * forgotten, so the next call tries again.\n */\n once(create: () => Promise<void>): Promise<void>;\n /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */\n isReady(): boolean;\n /** Records that the tables exist (created in a caller's transaction that has committed). */\n markReady(): void;\n /** Names this process has checked (tables, tenants). */\n readonly known: Set<string>;\n /**\n * Goes up on every `reset()`. Work that started before a reset must not record what it learned\n * after it: compare the value taken at the start with the current one.\n */\n readonly generation: number;\n /** Forgets everything (test setups drop all tables between tests). */\n reset(): void;\n}\n\nclass SchemaMemory implements ISchemaMemory {\n public readonly known = new Set<string>();\n private pending?: Promise<void>;\n private ready = false;\n private currentGeneration = 0;\n\n public constructor(\n public readonly key: string,\n private readonly onReset?: () => void\n ) {}\n\n public once(create: () => Promise<void>): Promise<void> {\n if (this.ready) {\n return Promise.resolve();\n }\n if (this.pending) {\n return this.pending;\n }\n // A run that ends after a reset() must neither mark the tables ready nor clear a newer run.\n const generation = this.currentGeneration;\n const run: Promise<void> = create().then(\n () => {\n if (this.currentGeneration === generation) {\n this.ready = true;\n }\n },\n error => {\n if (this.pending === run) {\n this.pending = undefined;\n }\n throw error;\n }\n );\n this.pending = run;\n return run;\n }\n\n public get generation(): number {\n return this.currentGeneration;\n }\n\n public isReady(): boolean {\n return this.ready;\n }\n\n public markReady(): void {\n this.ready = true;\n }\n\n public reset(): void {\n this.currentGeneration += 1;\n this.pending = undefined;\n this.ready = false;\n this.known.clear();\n this.onReset?.();\n }\n}\n\nconst memories = new Map<string, SchemaMemory>();\n\n/**\n * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on\n * first use, with `onReset` run whenever it is reset; later callers get the same one.\n *\n * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and\n * call `reset()` on every entry reset it too.\n */\nexport function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory {\n let memory = memories.get(key);\n if (!memory) {\n memory = new SchemaMemory(key, onReset);\n memories.set(key, memory);\n const g = globalThis as Record<string, unknown>;\n const managers = (g.__sqlTableManagers ??= []) as ISchemaMemory[];\n managers.push(memory);\n }\n return memory;\n}\n"],"names":["SchemaMemory","key","onReset","Set","create","Promise","generation","run","error","undefined","memories","Map","getSchemaMemory","memory","g","globalThis","managers"],"mappings":"AA8BA,MAAMA;IAMF,YACoBC,GAAW,EACVC,OAAoB,CACvC;aAFkBD,GAAG,GAAHA;aACCC,OAAO,GAAPA;aAPL,KAAK,GAAG,IAAIC;aAEpB,KAAK,GAAG;aACR,iBAAiB,GAAG;IAKzB;IAEI,KAAKC,MAA2B,EAAiB;QACpD,IAAI,IAAI,CAAC,KAAK,EACV,OAAOC,QAAQ,OAAO;QAE1B,IAAI,IAAI,CAAC,OAAO,EACZ,OAAO,IAAI,CAAC,OAAO;QAGvB,MAAMC,aAAa,IAAI,CAAC,iBAAiB;QACzC,MAAMC,MAAqBH,SAAS,IAAI,CACpC;YACI,IAAI,IAAI,CAAC,iBAAiB,KAAKE,YAC3B,IAAI,CAAC,KAAK,GAAG;QAErB,GACAE,CAAAA;YACI,IAAI,IAAI,CAAC,OAAO,KAAKD,KACjB,IAAI,CAAC,OAAO,GAAGE;YAEnB,MAAMD;QACV;QAEJ,IAAI,CAAC,OAAO,GAAGD;QACf,OAAOA;IACX;IAEA,IAAW,aAAqB;QAC5B,OAAO,IAAI,CAAC,iBAAiB;IACjC;IAEO,UAAmB;QACtB,OAAO,IAAI,CAAC,KAAK;IACrB;IAEO,YAAkB;QACrB,IAAI,CAAC,KAAK,GAAG;IACjB;IAEO,QAAc;QACjB,IAAI,CAAC,iBAAiB,IAAI;QAC1B,IAAI,CAAC,OAAO,GAAGE;QACf,IAAI,CAAC,KAAK,GAAG;QACb,IAAI,CAAC,KAAK,CAAC,KAAK;QAChB,IAAI,CAAC,OAAO;IAChB;AACJ;AAEA,MAAMC,WAAW,IAAIC;AASd,SAASC,gBAAgBX,GAAW,EAAEC,OAAoB;IAC7D,IAAIW,SAASH,SAAS,GAAG,CAACT;IAC1B,IAAI,CAACY,QAAQ;QACTA,SAAS,IAAIb,aAAaC,KAAKC;QAC/BQ,SAAS,GAAG,CAACT,KAAKY;QAClB,MAAMC,IAAIC;QACV,MAAMC,WAAYF,EAAE,kBAAkB,KAAK,EAAE;QAC7CE,SAAS,IAAI,CAACH;IAClB;IACA,OAAOA;AACX"}
@@ -0,0 +1,67 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ export interface ISqlSchemaSetup {
4
+ /**
5
+ * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports
6
+ * the steps it ran by these names, and can check that a module it needs registered its step.
7
+ */
8
+ readonly name: string;
9
+ /**
10
+ * Brings the step's tables, indexes and functions up to date, whatever the schema-managed
11
+ * setting. Safe to run again: what already exists is kept. It never drops a table or a column,
12
+ * but a step may migrate in place. The Postgres CMS, for one, adds columns
13
+ * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger
14
+ * functions, replaces the old count triggers and rebuilds the count rows from the search table
15
+ * once. The database user that runs setup needs the rights for that.
16
+ */
17
+ setup(): Promise<void>;
18
+ }
19
+ /**
20
+ * One step of the schema setup. Every part that owns tables registers its own step in a request's
21
+ * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and
22
+ * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).
23
+ * The setup runner runs every step it finds, so it doesn't need to know which modules exist.
24
+ */
25
+ export declare const SqlSchemaSetup: import("@webiny/di").Abstraction<ISqlSchemaSetup>;
26
+ export declare namespace SqlSchemaSetup {
27
+ type Interface = ISqlSchemaSetup;
28
+ }
29
+ /**
30
+ * What a request registers, as the transport builds every request's container: its storages (every
31
+ * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its
32
+ * container with it, so it sets up exactly the tables the API uses, with their settings.
33
+ */
34
+ export interface ISqlSchemaSetupRequest {
35
+ register(container: Container): Promise<void>;
36
+ }
37
+ export interface SqlSchemaSetupRunParams {
38
+ /** Registers a request's parts in the setup's container. */
39
+ request: ISqlSchemaSetupRequest;
40
+ /**
41
+ * The connection to set the schema up on. Defaults to the storage's. The caller closes it.
42
+ * On Lambda, setup goes to the database's writer, not through the proxy the API uses.
43
+ */
44
+ knex?: Knex;
45
+ }
46
+ export interface ISqlSchemaSetupRunner {
47
+ /**
48
+ * Creates every table, index and function the API uses: opens the setup's transaction (on
49
+ * Postgres, behind an advisory lock), builds a container on it the way a request's is built,
50
+ * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every
51
+ * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it
52
+ * ran.
53
+ */
54
+ run(params: SqlSchemaSetupRunParams): Promise<string[]>;
55
+ }
56
+ /**
57
+ * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:
58
+ * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain
59
+ * transaction on SQLite) and which modules it can't run without. The transport runs it before the
60
+ * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.
61
+ */
62
+ export declare const SqlSchemaSetupRunner: import("@webiny/di").Abstraction<ISqlSchemaSetupRunner>;
63
+ export declare namespace SqlSchemaSetupRunner {
64
+ type Interface = ISqlSchemaSetupRunner;
65
+ type Request = ISqlSchemaSetupRequest;
66
+ type RunParams = SqlSchemaSetupRunParams;
67
+ }
@@ -0,0 +1,6 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const SqlSchemaSetup = createAbstraction("Db/Sql/SchemaSetup");
3
+ const SqlSchemaSetupRunner = createAbstraction("Db/Sql/SchemaSetupRunner");
4
+ export { SqlSchemaSetup, SqlSchemaSetupRunner };
5
+
6
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/abstractions.js","sources":["../../src/schemaSetup/abstractions.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface ISqlSchemaSetup {\n /**\n * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports\n * the steps it ran by these names, and can check that a module it needs registered its step.\n */\n readonly name: string;\n /**\n * Brings the step's tables, indexes and functions up to date, whatever the schema-managed\n * setting. Safe to run again: what already exists is kept. It never drops a table or a column,\n * but a step may migrate in place. The Postgres CMS, for one, adds columns\n * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger\n * functions, replaces the old count triggers and rebuilds the count rows from the search table\n * once. The database user that runs setup needs the rights for that.\n */\n setup(): Promise<void>;\n}\n\n/**\n * One step of the schema setup. Every part that owns tables registers its own step in a request's\n * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and\n * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).\n * The setup runner runs every step it finds, so it doesn't need to know which modules exist.\n */\nexport const SqlSchemaSetup = createAbstraction<ISqlSchemaSetup>(\"Db/Sql/SchemaSetup\");\n\nexport namespace SqlSchemaSetup {\n export type Interface = ISqlSchemaSetup;\n}\n\n/**\n * What a request registers, as the transport builds every request's container: its storages (every\n * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its\n * container with it, so it sets up exactly the tables the API uses, with their settings.\n */\nexport interface ISqlSchemaSetupRequest {\n register(container: Container): Promise<void>;\n}\n\nexport interface SqlSchemaSetupRunParams {\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /**\n * The connection to set the schema up on. Defaults to the storage's. The caller closes it.\n * On Lambda, setup goes to the database's writer, not through the proxy the API uses.\n */\n knex?: Knex;\n}\n\nexport interface ISqlSchemaSetupRunner {\n /**\n * Creates every table, index and function the API uses: opens the setup's transaction (on\n * Postgres, behind an advisory lock), builds a container on it the way a request's is built,\n * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every\n * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it\n * ran.\n */\n run(params: SqlSchemaSetupRunParams): Promise<string[]>;\n}\n\n/**\n * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:\n * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain\n * transaction on SQLite) and which modules it can't run without. The transport runs it before the\n * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.\n */\nexport const SqlSchemaSetupRunner = createAbstraction<ISqlSchemaSetupRunner>(\n \"Db/Sql/SchemaSetupRunner\"\n);\n\nexport namespace SqlSchemaSetupRunner {\n export type Interface = ISqlSchemaSetupRunner;\n export type Request = ISqlSchemaSetupRequest;\n export type RunParams = SqlSchemaSetupRunParams;\n}\n"],"names":["SqlSchemaSetup","createAbstraction","SqlSchemaSetupRunner"],"mappings":";AA2BO,MAAMA,iBAAiBC,kBAAmC;AA0C1D,MAAMC,uBAAuBD,kBAChC"}
@@ -0,0 +1,4 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export type { ISqlSchemaSetupRequest, SqlSchemaSetupRunParams } from "./abstractions.js";
3
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
4
+ export type { RequiredSqlSchemaSetup, RunSchemaSetupStepsParams } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,2 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,34 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ import { type ISqlSchemaSetupRequest } from "./abstractions.js";
4
+ export interface RequiredSqlSchemaSetup {
5
+ /** The step's name (`SqlSchemaSetup.name`). */
6
+ name: string;
7
+ /** The error when no step of that name is registered: what to add to the project. */
8
+ message: string;
9
+ }
10
+ export interface RunSchemaSetupStepsParams {
11
+ /** The root container the storage is registered in. The setup's container is its child. */
12
+ root: Container;
13
+ /** The setup's connection: a transaction the runner opened. */
14
+ knex: Knex;
15
+ tableNamePrefix?: string;
16
+ /** Registers a request's parts in the setup's container. */
17
+ request: ISqlSchemaSetupRequest;
18
+ /** Steps the storage can't run without (a module the project must add). */
19
+ required?: RequiredSqlSchemaSetup[];
20
+ }
21
+ /**
22
+ * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds
23
+ * a container on the setup's connection the way a request's is built, and runs every schema setup
24
+ * step in it.
25
+ *
26
+ * The container is a child of the root, so it has what a request has (the logger, the storages'
27
+ * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:
28
+ * every storage the request registers runs on it, including the ones built while the request
29
+ * registers and the modules' singletons, which are built in the container that registers them.
30
+ *
31
+ * Checks `required` before running anything, so a missing module fails before any DDL. Returns the
32
+ * names of the steps it ran, in order.
33
+ */
34
+ export declare function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]>;
@@ -0,0 +1,35 @@
1
+ import { SqlConnectionFeature } from "../connection/SqlConnectionFeature.js";
2
+ import { SqlSchemaSetup } from "./abstractions.js";
3
+ async function runSchemaSetupSteps(params) {
4
+ const { root, knex, tableNamePrefix, request, required = [] } = params;
5
+ const container = root.createChildContainer();
6
+ SqlConnectionFeature.register(container, {
7
+ knex,
8
+ tableNamePrefix,
9
+ schemaManaged: false
10
+ });
11
+ await request.register(container);
12
+ const steps = resolveSteps(container, required);
13
+ for (const step of required)if (!steps.some((item)=>item.name === step.name)) throw new Error(step.message);
14
+ const done = [];
15
+ for (const step of steps){
16
+ await step.setup();
17
+ done.push(step.name);
18
+ }
19
+ return done;
20
+ }
21
+ function resolveSteps(container, required) {
22
+ try {
23
+ return container.resolveAll(SqlSchemaSetup);
24
+ } catch (error) {
25
+ if (!required.length) throw error;
26
+ const cause = error instanceof Error ? error.message : String(error);
27
+ const needs = required.map((step)=>step.message).join(" ");
28
+ throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {
29
+ cause: error
30
+ });
31
+ }
32
+ }
33
+ export { runSchemaSetupSteps };
34
+
35
+ //# sourceMappingURL=runSchemaSetupSteps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/runSchemaSetupSteps.js","sources":["../../src/schemaSetup/runSchemaSetupSteps.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { SqlConnectionFeature } from \"~/connection/SqlConnectionFeature.js\";\nimport { SqlSchemaSetup, type ISqlSchemaSetupRequest } from \"./abstractions.js\";\n\nexport interface RequiredSqlSchemaSetup {\n /** The step's name (`SqlSchemaSetup.name`). */\n name: string;\n /** The error when no step of that name is registered: what to add to the project. */\n message: string;\n}\n\nexport interface RunSchemaSetupStepsParams {\n /** The root container the storage is registered in. The setup's container is its child. */\n root: Container;\n /** The setup's connection: a transaction the runner opened. */\n knex: Knex;\n tableNamePrefix?: string;\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /** Steps the storage can't run without (a module the project must add). */\n required?: RequiredSqlSchemaSetup[];\n}\n\n/**\n * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds\n * a container on the setup's connection the way a request's is built, and runs every schema setup\n * step in it.\n *\n * The container is a child of the root, so it has what a request has (the logger, the storages'\n * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:\n * every storage the request registers runs on it, including the ones built while the request\n * registers and the modules' singletons, which are built in the container that registers them.\n *\n * Checks `required` before running anything, so a missing module fails before any DDL. Returns the\n * names of the steps it ran, in order.\n */\nexport async function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]> {\n const { root, knex, tableNamePrefix, request, required = [] } = params;\n\n const container = root.createChildContainer();\n SqlConnectionFeature.register(container, { knex, tableNamePrefix, schemaManaged: false });\n await request.register(container);\n\n const steps = resolveSteps(container, required);\n for (const step of required) {\n if (!steps.some(item => item.name === step.name)) {\n throw new Error(step.message);\n }\n }\n\n const done: string[] = [];\n for (const step of steps) {\n await step.setup();\n done.push(step.name);\n }\n return done;\n}\n\n/**\n * Builds the steps. A step whose module needs another one that is missing (the folder catalog needs\n * the CMS's table names) can't be built, and that fails before any step has a name to check. So\n * the failure says which modules the storage needs, with the cause.\n */\nfunction resolveSteps(container: Container, required: RequiredSqlSchemaSetup[]) {\n try {\n return container.resolveAll(SqlSchemaSetup);\n } catch (error) {\n if (!required.length) {\n throw error;\n }\n const cause = error instanceof Error ? error.message : String(error);\n const needs = required.map(step => step.message).join(\" \");\n throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {\n cause: error\n });\n }\n}\n"],"names":["runSchemaSetupSteps","params","root","knex","tableNamePrefix","request","required","container","SqlConnectionFeature","steps","resolveSteps","step","item","Error","done","SqlSchemaSetup","error","cause","String","needs"],"mappings":";;AAqCO,eAAeA,oBAAoBC,MAAiC;IACvE,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,eAAe,EAAEC,OAAO,EAAEC,WAAW,EAAE,EAAE,GAAGL;IAEhE,MAAMM,YAAYL,KAAK,oBAAoB;IAC3CM,qBAAqB,QAAQ,CAACD,WAAW;QAAEJ;QAAMC;QAAiB,eAAe;IAAM;IACvF,MAAMC,QAAQ,QAAQ,CAACE;IAEvB,MAAME,QAAQC,aAAaH,WAAWD;IACtC,KAAK,MAAMK,QAAQL,SACf,IAAI,CAACG,MAAM,IAAI,CAACG,CAAAA,OAAQA,KAAK,IAAI,KAAKD,KAAK,IAAI,GAC3C,MAAM,IAAIE,MAAMF,KAAK,OAAO;IAIpC,MAAMG,OAAiB,EAAE;IACzB,KAAK,MAAMH,QAAQF,MAAO;QACtB,MAAME,KAAK,KAAK;QAChBG,KAAK,IAAI,CAACH,KAAK,IAAI;IACvB;IACA,OAAOG;AACX;AAOA,SAASJ,aAAaH,SAAoB,EAAED,QAAkC;IAC1E,IAAI;QACA,OAAOC,UAAU,UAAU,CAACQ;IAChC,EAAE,OAAOC,OAAO;QACZ,IAAI,CAACV,SAAS,MAAM,EAChB,MAAMU;QAEV,MAAMC,QAAQD,iBAAiBH,QAAQG,MAAM,OAAO,GAAGE,OAAOF;QAC9D,MAAMG,QAAQb,SAAS,GAAG,CAACK,CAAAA,OAAQA,KAAK,OAAO,EAAE,IAAI,CAAC;QACtD,MAAM,IAAIE,MAAM,CAAC,wCAAwC,EAAEI,MAAM,GAAG,EAAEE,OAAO,EAAE;YAC3E,OAAOH;QACX;IACJ;AACJ"}
@@ -1,16 +1,13 @@
1
- const TABLE_NAME = "webiny_service_manifests";
1
+ import { SERVICE_MANIFESTS_TABLE, defineServiceManifestsTable } from "./serviceManifestsTable.js";
2
2
  class SqlServiceManifestLoader {
3
3
  constructor(knex, tableManager){
4
4
  this.knex = knex;
5
5
  this.tableManager = tableManager;
6
- this.ensureTable = tableManager.define(TABLE_NAME, (table)=>{
7
- table.text("name").primary().notNullable();
8
- table.text("manifest").notNullable();
9
- });
6
+ this.ensureTable = defineServiceManifestsTable(tableManager);
10
7
  }
11
8
  async load() {
12
9
  await this.ensureTable();
13
- const rows = await this.knex(this.tableManager.resolve(TABLE_NAME)).select("name", "manifest");
10
+ const rows = await this.knex(this.tableManager.resolve(SERVICE_MANIFESTS_TABLE)).select("name", "manifest");
14
11
  if (!rows.length) return;
15
12
  return rows.map((row)=>({
16
13
  name: row.name,
@@ -1 +1 @@
1
- {"version":3,"file":"serviceDiscovery/SqlServiceManifestLoader.js","sources":["../../src/serviceDiscovery/SqlServiceManifestLoader.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { IServiceManifestLoader } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport type { TableManager } from \"~/TableManager.js\";\n\nconst TABLE_NAME = \"webiny_service_manifests\";\n\ninterface IServiceManifestRow {\n name: string;\n manifest: string;\n}\n\nexport class SqlServiceManifestLoader implements IServiceManifestLoader {\n private readonly knex: Knex;\n private readonly tableManager: TableManager;\n private readonly ensureTable: () => Promise<void>;\n\n constructor(knex: Knex, tableManager: TableManager) {\n this.knex = knex;\n this.tableManager = tableManager;\n this.ensureTable = tableManager.define(TABLE_NAME, table => {\n table.text(\"name\").primary().notNullable();\n table.text(\"manifest\").notNullable();\n });\n }\n\n async load() {\n await this.ensureTable();\n\n const rows = await this.knex<IServiceManifestRow>(\n this.tableManager.resolve(TABLE_NAME)\n ).select(\"name\", \"manifest\");\n\n if (!rows.length) {\n return undefined;\n }\n\n return rows.map(row => ({\n name: row.name,\n manifest: JSON.parse(row.manifest)\n }));\n }\n}\n"],"names":["TABLE_NAME","SqlServiceManifestLoader","knex","tableManager","table","rows","row","JSON"],"mappings":"AAIA,MAAMA,aAAa;AAOZ,MAAMC;IAKT,YAAYC,IAAU,EAAEC,YAA0B,CAAE;QAChD,IAAI,CAAC,IAAI,GAAGD;QACZ,IAAI,CAAC,YAAY,GAAGC;QACpB,IAAI,CAAC,WAAW,GAAGA,aAAa,MAAM,CAACH,YAAYI,CAAAA;YAC/CA,MAAM,IAAI,CAAC,QAAQ,OAAO,GAAG,WAAW;YACxCA,MAAM,IAAI,CAAC,YAAY,WAAW;QACtC;IACJ;IAEA,MAAM,OAAO;QACT,MAAM,IAAI,CAAC,WAAW;QAEtB,MAAMC,OAAO,MAAM,IAAI,CAAC,IAAI,CACxB,IAAI,CAAC,YAAY,CAAC,OAAO,CAACL,aAC5B,MAAM,CAAC,QAAQ;QAEjB,IAAI,CAACK,KAAK,MAAM,EACZ;QAGJ,OAAOA,KAAK,GAAG,CAACC,CAAAA,MAAQ;gBACpB,MAAMA,IAAI,IAAI;gBACd,UAAUC,KAAK,KAAK,CAACD,IAAI,QAAQ;YACrC;IACJ;AACJ"}
1
+ {"version":3,"file":"serviceDiscovery/SqlServiceManifestLoader.js","sources":["../../src/serviceDiscovery/SqlServiceManifestLoader.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { IServiceManifestLoader } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport {\n defineServiceManifestsTable,\n SERVICE_MANIFESTS_TABLE,\n type IServiceManifestRow\n} from \"./serviceManifestsTable.js\";\n\nexport class SqlServiceManifestLoader implements IServiceManifestLoader {\n private readonly knex: Knex;\n private readonly tableManager: TableManager;\n private readonly ensureTable: () => Promise<void>;\n\n constructor(knex: Knex, tableManager: TableManager) {\n this.knex = knex;\n this.tableManager = tableManager;\n this.ensureTable = defineServiceManifestsTable(tableManager);\n }\n\n async load() {\n await this.ensureTable();\n\n const rows = await this.knex<IServiceManifestRow>(\n this.tableManager.resolve(SERVICE_MANIFESTS_TABLE)\n ).select(\"name\", \"manifest\");\n\n if (!rows.length) {\n return undefined;\n }\n\n return rows.map(row => ({\n name: row.name,\n manifest: JSON.parse(row.manifest)\n }));\n }\n}\n"],"names":["SqlServiceManifestLoader","knex","tableManager","defineServiceManifestsTable","rows","SERVICE_MANIFESTS_TABLE","row","JSON"],"mappings":";AASO,MAAMA;IAKT,YAAYC,IAAU,EAAEC,YAA0B,CAAE;QAChD,IAAI,CAAC,IAAI,GAAGD;QACZ,IAAI,CAAC,YAAY,GAAGC;QACpB,IAAI,CAAC,WAAW,GAAGC,4BAA4BD;IACnD;IAEA,MAAM,OAAO;QACT,MAAM,IAAI,CAAC,WAAW;QAEtB,MAAME,OAAO,MAAM,IAAI,CAAC,IAAI,CACxB,IAAI,CAAC,YAAY,CAAC,OAAO,CAACC,0BAC5B,MAAM,CAAC,QAAQ;QAEjB,IAAI,CAACD,KAAK,MAAM,EACZ;QAGJ,OAAOA,KAAK,GAAG,CAACE,CAAAA,MAAQ;gBACpB,MAAMA,IAAI,IAAI;gBACd,UAAUC,KAAK,KAAK,CAACD,IAAI,QAAQ;YACrC;IACJ;AACJ"}
@@ -0,0 +1,16 @@
1
+ import type { Knex } from "knex";
2
+ import type { IServiceManifest } from "@webiny/api-core/features/serviceDiscovery/index.js";
3
+ import type { TableManager } from "../TableManager.js";
4
+ /**
5
+ * Writes service manifests where `SqlServiceManifestLoader` reads them. A deployment calls it with
6
+ * the manifests of the services it deployed: each one replaces the stored manifest of the same name,
7
+ * and services it doesn't pass keep theirs (the admin deploy writes `admin` alone, after the api
8
+ * deploy wrote `core`, `api` and `scheduler`).
9
+ */
10
+ export declare class SqlServiceManifestWriter {
11
+ private readonly knex;
12
+ private readonly tableManager;
13
+ private readonly ensureTable;
14
+ constructor(knex: Knex, tableManager: TableManager);
15
+ write(manifests: IServiceManifest[]): Promise<void>;
16
+ }
@@ -0,0 +1,27 @@
1
+ import { SERVICE_MANIFESTS_TABLE, defineServiceManifestsTable } from "./serviceManifestsTable.js";
2
+ class SqlServiceManifestWriter {
3
+ constructor(knex, tableManager){
4
+ this.knex = knex;
5
+ this.tableManager = tableManager;
6
+ this.ensureTable = defineServiceManifestsTable(tableManager);
7
+ }
8
+ async write(manifests) {
9
+ const rows = new Map();
10
+ for (const item of manifests){
11
+ if (!item || "string" != typeof item.name || !item.name) throw new Error("A service manifest needs a `name`.");
12
+ if (!item.manifest || "object" != typeof item.manifest) throw new Error(`The service manifest "${item.name}" needs a \`manifest\` object.`);
13
+ rows.set(item.name, {
14
+ name: item.name,
15
+ manifest: JSON.stringify(item.manifest)
16
+ });
17
+ }
18
+ if (!rows.size) return;
19
+ await this.ensureTable();
20
+ await this.knex(this.tableManager.resolve(SERVICE_MANIFESTS_TABLE)).insert([
21
+ ...rows.values()
22
+ ]).onConflict("name").merge();
23
+ }
24
+ }
25
+ export { SqlServiceManifestWriter };
26
+
27
+ //# sourceMappingURL=SqlServiceManifestWriter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serviceDiscovery/SqlServiceManifestWriter.js","sources":["../../src/serviceDiscovery/SqlServiceManifestWriter.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { IServiceManifest } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport {\n defineServiceManifestsTable,\n SERVICE_MANIFESTS_TABLE,\n type IServiceManifestRow\n} from \"./serviceManifestsTable.js\";\n\n/**\n * Writes service manifests where `SqlServiceManifestLoader` reads them. A deployment calls it with\n * the manifests of the services it deployed: each one replaces the stored manifest of the same name,\n * and services it doesn't pass keep theirs (the admin deploy writes `admin` alone, after the api\n * deploy wrote `core`, `api` and `scheduler`).\n */\nexport class SqlServiceManifestWriter {\n private readonly knex: Knex;\n private readonly tableManager: TableManager;\n private readonly ensureTable: () => Promise<void>;\n\n constructor(knex: Knex, tableManager: TableManager) {\n this.knex = knex;\n this.tableManager = tableManager;\n this.ensureTable = defineServiceManifestsTable(tableManager);\n }\n\n async write(manifests: IServiceManifest[]): Promise<void> {\n // The input comes from a deployment's invocation payload, so it's checked before it's stored.\n const rows = new Map<string, IServiceManifestRow>();\n for (const item of manifests) {\n if (!item || typeof item.name !== \"string\" || !item.name) {\n throw new Error(\"A service manifest needs a `name`.\");\n }\n if (!item.manifest || typeof item.manifest !== \"object\") {\n throw new Error(`The service manifest \"${item.name}\" needs a \\`manifest\\` object.`);\n }\n // One row per name: Postgres refuses an upsert that touches the same row twice.\n rows.set(item.name, { name: item.name, manifest: JSON.stringify(item.manifest) });\n }\n\n if (!rows.size) {\n return;\n }\n\n await this.ensureTable();\n\n await this.knex<IServiceManifestRow>(this.tableManager.resolve(SERVICE_MANIFESTS_TABLE))\n .insert([...rows.values()])\n .onConflict(\"name\")\n .merge();\n }\n}\n"],"names":["SqlServiceManifestWriter","knex","tableManager","defineServiceManifestsTable","manifests","rows","Map","item","Error","JSON","SERVICE_MANIFESTS_TABLE"],"mappings":";AAeO,MAAMA;IAKT,YAAYC,IAAU,EAAEC,YAA0B,CAAE;QAChD,IAAI,CAAC,IAAI,GAAGD;QACZ,IAAI,CAAC,YAAY,GAAGC;QACpB,IAAI,CAAC,WAAW,GAAGC,4BAA4BD;IACnD;IAEA,MAAM,MAAME,SAA6B,EAAiB;QAEtD,MAAMC,OAAO,IAAIC;QACjB,KAAK,MAAMC,QAAQH,UAAW;YAC1B,IAAI,CAACG,QAAQ,AAAqB,YAArB,OAAOA,KAAK,IAAI,IAAiB,CAACA,KAAK,IAAI,EACpD,MAAM,IAAIC,MAAM;YAEpB,IAAI,CAACD,KAAK,QAAQ,IAAI,AAAyB,YAAzB,OAAOA,KAAK,QAAQ,EACtC,MAAM,IAAIC,MAAM,CAAC,sBAAsB,EAAED,KAAK,IAAI,CAAC,8BAA8B,CAAC;YAGtFF,KAAK,GAAG,CAACE,KAAK,IAAI,EAAE;gBAAE,MAAMA,KAAK,IAAI;gBAAE,UAAUE,KAAK,SAAS,CAACF,KAAK,QAAQ;YAAE;QACnF;QAEA,IAAI,CAACF,KAAK,IAAI,EACV;QAGJ,MAAM,IAAI,CAAC,WAAW;QAEtB,MAAM,IAAI,CAAC,IAAI,CAAsB,IAAI,CAAC,YAAY,CAAC,OAAO,CAACK,0BAC1D,MAAM,CAAC;eAAIL,KAAK,MAAM;SAAG,EACzB,UAAU,CAAC,QACX,KAAK;IACd;AACJ"}
@@ -1 +1,2 @@
1
1
  export { SqlServiceManifestLoader } from "./SqlServiceManifestLoader.js";
2
+ export { SqlServiceManifestWriter } from "./SqlServiceManifestWriter.js";
@@ -1 +1,2 @@
1
1
  export { SqlServiceManifestLoader } from "./SqlServiceManifestLoader.js";
2
+ export { SqlServiceManifestWriter } from "./SqlServiceManifestWriter.js";
@@ -0,0 +1,13 @@
1
+ import type { TableManager } from "../TableManager.js";
2
+ /** Service manifests, one row per service (`core`, `api`, `admin`, …), read by service discovery. */
3
+ export declare const SERVICE_MANIFESTS_TABLE = "webiny_service_manifests";
4
+ export interface IServiceManifestRow {
5
+ name: string;
6
+ /** The manifest, as JSON. */
7
+ manifest: string;
8
+ }
9
+ /**
10
+ * Declares the manifests table on `tableManager` and returns the function that ensures it on first
11
+ * use. The loader and the writer both declare it here, so they can't disagree on its shape.
12
+ */
13
+ export declare const defineServiceManifestsTable: (tableManager: TableManager) => (() => Promise<void>);
@@ -0,0 +1,8 @@
1
+ const SERVICE_MANIFESTS_TABLE = "webiny_service_manifests";
2
+ const defineServiceManifestsTable = (tableManager)=>tableManager.define(SERVICE_MANIFESTS_TABLE, (table)=>{
3
+ table.text("name").primary().notNullable();
4
+ table.text("manifest").notNullable();
5
+ });
6
+ export { SERVICE_MANIFESTS_TABLE, defineServiceManifestsTable };
7
+
8
+ //# sourceMappingURL=serviceManifestsTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serviceDiscovery/serviceManifestsTable.js","sources":["../../src/serviceDiscovery/serviceManifestsTable.ts"],"sourcesContent":["import type { TableManager } from \"~/TableManager.js\";\n\n/** Service manifests, one row per service (`core`, `api`, `admin`, …), read by service discovery. */\nexport const SERVICE_MANIFESTS_TABLE = \"webiny_service_manifests\";\n\nexport interface IServiceManifestRow {\n name: string;\n /** The manifest, as JSON. */\n manifest: string;\n}\n\n/**\n * Declares the manifests table on `tableManager` and returns the function that ensures it on first\n * use. The loader and the writer both declare it here, so they can't disagree on its shape.\n */\nexport const defineServiceManifestsTable = (tableManager: TableManager): (() => Promise<void>) => {\n return tableManager.define(SERVICE_MANIFESTS_TABLE, table => {\n table.text(\"name\").primary().notNullable();\n table.text(\"manifest\").notNullable();\n });\n};\n"],"names":["SERVICE_MANIFESTS_TABLE","defineServiceManifestsTable","tableManager","table"],"mappings":"AAGO,MAAMA,0BAA0B;AAYhC,MAAMC,8BAA8B,CAACC,eACjCA,aAAa,MAAM,CAACF,yBAAyBG,CAAAA;QAChDA,MAAM,IAAI,CAAC,QAAQ,OAAO,GAAG,WAAW;QACxCA,MAAM,IAAI,CAAC,YAAY,WAAW;IACtC"}
@@ -0,0 +1,22 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ /**
4
+ * The SQL storage of the Webiny API, built from a connection (`createSqliteStorage`,
5
+ * `createPgStorage`) and handed to a transport (the standalone server, AWS Lambda). It holds no
6
+ * engine settings beyond its own; modules with settings (the Postgres CMS) come with the project's
7
+ * extensions.
8
+ */
9
+ export interface SqlStorage {
10
+ /** The connection the storage runs on. */
11
+ readonly knex: Knex;
12
+ /** The prefix of every table the storage uses. */
13
+ readonly tableNamePrefix?: string;
14
+ /**
15
+ * Registers the storage in the transport's root container, once per process: the connection and
16
+ * its settings (`SqlConnectionFeature`), a `RequestStorage` that registers the storages (core,
17
+ * audit logs, websockets) in each request's container, and its `SqlSchemaSetupRunner`. The
18
+ * transport runs the setup before the API takes traffic; once it ran, the storage is
19
+ * schema-managed: no part checks for or creates tables at runtime.
20
+ */
21
+ register(container: Container): void;
22
+ }
File without changes
@@ -1,18 +0,0 @@
1
- import type { Knex } from "knex";
2
- export interface ApiCoreSqlConfig {
3
- knex: Knex;
4
- tableNamePrefix?: string;
5
- }
6
- /**
7
- * Registers the SQL implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register
8
- * resolves + builds it. Mirrors ApiCoreDdbFeature.
9
- *
10
- * The storage operations are built once, here, and `create()` hands out the same object. It runs on
11
- * every request (ApiCoreFeature is per-request), and building per request created a new TableManager
12
- * each time: every one stayed in the global test registry, so a long-running server leaked one per
13
- * request, and each started with no verified tables. The operations hold no per-request state.
14
- */
15
- export declare const ApiCoreSqlFeature: {
16
- name: string;
17
- register(container: import("@webiny/di").Container, context: ApiCoreSqlConfig): void;
18
- };
@@ -1,18 +0,0 @@
1
- import { createFeature } from "@webiny/feature/api";
2
- import { ApiCoreStorageOperationsFactory } from "@webiny/api-core";
3
- import { createApiCoreSql } from "./createApiCoreSql.js";
4
- const ApiCoreSqlFeature = createFeature({
5
- name: "ApiCoreSql",
6
- register (container, { knex, tableNamePrefix }) {
7
- const storageOperations = createApiCoreSql({
8
- knex,
9
- tableNamePrefix
10
- });
11
- container.registerInstance(ApiCoreStorageOperationsFactory, {
12
- create: ()=>storageOperations
13
- });
14
- }
15
- });
16
- export { ApiCoreSqlFeature };
17
-
18
- //# sourceMappingURL=ApiCoreSqlFeature.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ApiCoreSqlFeature.js","sources":["../src/ApiCoreSqlFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { Knex } from \"knex\";\nimport { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreSql } from \"./createApiCoreSql.js\";\n\nexport interface ApiCoreSqlConfig {\n knex: Knex;\n tableNamePrefix?: string;\n}\n\n/**\n * Registers the SQL implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors ApiCoreDdbFeature.\n *\n * The storage operations are built once, here, and `create()` hands out the same object. It runs on\n * every request (ApiCoreFeature is per-request), and building per request created a new TableManager\n * each time: every one stayed in the global test registry, so a long-running server leaked one per\n * request, and each started with no verified tables. The operations hold no per-request state.\n */\nexport const ApiCoreSqlFeature = createFeature<ApiCoreSqlConfig>({\n name: \"ApiCoreSql\",\n register(container, { knex, tableNamePrefix }) {\n const storageOperations = createApiCoreSql({ knex, tableNamePrefix });\n\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: () => storageOperations\n });\n }\n});\n"],"names":["ApiCoreSqlFeature","createFeature","container","knex","tableNamePrefix","storageOperations","createApiCoreSql","ApiCoreStorageOperationsFactory"],"mappings":";;;AAmBO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,IAAI,EAAEC,eAAe,EAAE;QACzC,MAAMC,oBAAoBC,iBAAiB;YAAEH;YAAMC;QAAgB;QAEnEF,UAAU,gBAAgB,CAACK,iCAAiC;YACxD,QAAQ,IAAMF;QAClB;IACJ;AACJ"}