@venizia/ignis-kernel 0.4.8-5 → 0.4.8-7

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 (69) hide show
  1. package/dist/esm/base/applications/common/types/application.d.ts +3 -4
  2. package/dist/esm/base/applications/common/types/application.js.map +1 -1
  3. package/dist/esm/base/applications/rest.d.ts +13 -7
  4. package/dist/esm/base/applications/rest.js +52 -7
  5. package/dist/esm/base/applications/rest.js.map +1 -1
  6. package/dist/esm/base/applications/router-factory.d.ts +27 -0
  7. package/dist/esm/base/applications/router-factory.js +28 -0
  8. package/dist/esm/base/applications/router-factory.js.map +1 -0
  9. package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +6 -4
  10. package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
  11. package/dist/esm/base/auth/authenticate/common/types/service.d.ts +1 -1
  12. package/dist/esm/base/auth/authenticate/common/types/service.js.map +1 -1
  13. package/dist/esm/base/controllers/factory/controller.js +5 -2
  14. package/dist/esm/base/controllers/factory/controller.js.map +1 -1
  15. package/dist/esm/base/controllers/factory/crud/readable.js +2 -1
  16. package/dist/esm/base/controllers/factory/crud/readable.js.map +1 -1
  17. package/dist/esm/base/controllers/factory/definition.d.ts +3 -3
  18. package/dist/esm/base/controllers/factory/definition.js +3 -3
  19. package/dist/esm/base/controllers/factory/definition.js.map +1 -1
  20. package/dist/esm/base/controllers/rest/abstract.js +5 -0
  21. package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
  22. package/dist/esm/base/datasources/abstract.d.ts +69 -2
  23. package/dist/esm/base/datasources/abstract.js +186 -1
  24. package/dist/esm/base/datasources/abstract.js.map +1 -1
  25. package/dist/esm/base/datasources/common/types.d.ts +60 -1
  26. package/dist/esm/base/datasources/common/types.js +14 -0
  27. package/dist/esm/base/datasources/common/types.js.map +1 -1
  28. package/dist/esm/base/datasources/opening-handles.d.ts +8 -0
  29. package/dist/esm/base/datasources/opening-handles.js +8 -0
  30. package/dist/esm/base/datasources/opening-handles.js.map +1 -0
  31. package/dist/esm/base/metadata/persistents.js +20 -1
  32. package/dist/esm/base/metadata/persistents.js.map +1 -1
  33. package/dist/esm/base/middlewares/app-error/app-error.middleware.js +12 -1
  34. package/dist/esm/base/middlewares/app-error/app-error.middleware.js.map +1 -1
  35. package/dist/esm/base/middlewares/app-error/common/types.d.ts +10 -8
  36. package/dist/esm/base/middlewares/app-error/common/types.js.map +1 -1
  37. package/dist/esm/base/middlewares/app-error/database.handler.js +14 -14
  38. package/dist/esm/base/middlewares/app-error/database.handler.js.map +1 -1
  39. package/dist/esm/base/middlewares/app-error/index.d.ts +2 -0
  40. package/dist/esm/base/middlewares/app-error/index.js +1 -0
  41. package/dist/esm/base/middlewares/app-error/index.js.map +1 -1
  42. package/dist/esm/base/middlewares/app-error/postgres-errors.d.ts +20 -0
  43. package/dist/esm/base/middlewares/app-error/postgres-errors.js +74 -0
  44. package/dist/esm/base/middlewares/app-error/postgres-errors.js.map +1 -0
  45. package/dist/esm/base/models/base.d.ts +0 -2
  46. package/dist/esm/base/models/base.js +0 -4
  47. package/dist/esm/base/models/base.js.map +1 -1
  48. package/dist/esm/base/models/common/constants.d.ts +9 -0
  49. package/dist/esm/base/models/common/constants.js +15 -0
  50. package/dist/esm/base/models/common/constants.js.map +1 -1
  51. package/dist/esm/base/repositories/common/request-filter-guard.d.ts +52 -2
  52. package/dist/esm/base/repositories/common/request-filter-guard.js +110 -25
  53. package/dist/esm/base/repositories/common/request-filter-guard.js.map +1 -1
  54. package/dist/esm/base/repositories/core/abstract.js +1 -1
  55. package/dist/esm/base/repositories/core/abstract.js.map +1 -1
  56. package/dist/esm/common/statuses/common.d.ts +8 -1
  57. package/dist/esm/common/statuses/common.js +24 -8
  58. package/dist/esm/common/statuses/common.js.map +1 -1
  59. package/dist/esm/helpers/inversion/common/types/model.d.ts +12 -2
  60. package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
  61. package/dist/esm/helpers/inversion/common/types/persistence.d.ts +3 -1
  62. package/dist/esm/helpers/inversion/common/types/persistence.js.map +1 -1
  63. package/dist/esm/repository.d.ts +3 -1
  64. package/dist/esm/repository.js +3 -1
  65. package/dist/esm/repository.js.map +1 -1
  66. package/dist/esm/statuses.d.ts +8 -0
  67. package/dist/esm/statuses.js +8 -0
  68. package/dist/esm/statuses.js.map +1 -0
  69. package/package.json +9 -5
@@ -1,6 +1,7 @@
1
1
  import type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
2
  import { BaseHelper } from '@venizia/ignis-helpers/core';
3
- import type { IDataSource, IDataSourceCapabilities, ITransaction, ITransactionOptions, TAnyDataSourceSchema } from './common/index.js';
3
+ import type { IDataSource, IDataSourceCapabilities, IDataSourceOpening, ITransaction, ITransactionOptions, TAnyDataSourceSchema, TDataSourceOpenMode } from './common/index.js';
4
+ import { OPENING_HANDLES } from './opening-handles.js';
4
5
  /**
5
6
  * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.
6
7
  *
@@ -19,7 +20,73 @@ export declare abstract class AbstractDataSource<Settings extends object = {}, S
19
20
  name: string;
20
21
  settings: Settings;
21
22
  schema: Schema;
22
- abstract configure(opts?: ConfigurableOptions): ValueOrPromise<void>;
23
+ abstract configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;
24
+ /** The options the boot would have given `configure()`, kept for the open that the first use starts. */
25
+ private deferredOptions?;
26
+ /** The open in flight: every call that arrives meanwhile awaits this one promise. */
27
+ private opening?;
28
+ /**
29
+ * An open that outlived its timeout and has not settled. Nothing is retried until it has: two `configure()` must never
30
+ * run at once, and when it does settle what it built is closed, never published.
31
+ */
32
+ private abandoned?;
33
+ private isOpened;
34
+ private isShutDown;
35
+ /**
36
+ * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}
37
+ * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.
38
+ */
39
+ protected supportsDeferredOpen(): boolean;
40
+ /** The `open.on` of `@datasource`, `start` when unset. */
41
+ getOpenMode(): TDataSourceOpenMode;
42
+ isOpenDeferred(): boolean;
43
+ /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */
44
+ getOpenTimeoutMs(): number;
45
+ /**
46
+ * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that
47
+ * opens at start: from the moment the application has started it, until `close()`.
48
+ */
49
+ isOpen(): boolean;
50
+ /** Whether the first use is opening the datasource right now. */
51
+ isOpening(): boolean;
52
+ /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */
53
+ isClosed(): boolean;
54
+ /**
55
+ * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a
56
+ * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.
57
+ */
58
+ [OPENING_HANDLES](): IDataSourceOpening;
59
+ /**
60
+ * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to
61
+ * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the
62
+ * boot's private key.
63
+ */
64
+ protected createOpening(): IDataSourceOpening;
65
+ /**
66
+ * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.
67
+ * Refused for a family that cannot honour it.
68
+ */
69
+ deferOpen(opts: {
70
+ options?: ConfigurableOptions;
71
+ }): void;
72
+ /**
73
+ * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller
74
+ * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the
75
+ * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After
76
+ * `close()` it rejects: a stopped application does not reopen its datasources.
77
+ */
78
+ ensureOpen(): Promise<void>;
79
+ private runOpen;
80
+ /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */
81
+ private settleAbandoned;
82
+ private discardOpenAttempt;
83
+ /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */
84
+ protected discardPartialOpen(): ValueOrPromise<void>;
85
+ /**
86
+ * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives
87
+ * during the first use closes what that open built instead of racing it.
88
+ */
89
+ protected settleOpening(): Promise<void>;
23
90
  getSettings(): Settings;
24
91
  getSchema(): Schema;
25
92
  /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */
@@ -2,6 +2,8 @@ var _a;
2
2
  import { MetadataRegistry } from '../../helpers/inversion/index.js';
3
3
  import { NotSupportedUtility } from '../../utilities/index.js';
4
4
  import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
5
+ import { DataSourceOpenDefaults, DataSourceOpenModes } from './common/index.js';
6
+ import { OPENING_HANDLES } from './opening-handles.js';
5
7
  /**
6
8
  * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.
7
9
  *
@@ -15,11 +17,194 @@ export const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data
15
17
  export const isDataSourceClass = (value) => {
16
18
  return typeof value === 'function' && DATA_SOURCE_BRAND in value;
17
19
  };
20
+ /** The two ways a race between the open and its timeout can end. */
21
+ const OPEN_DONE = 'done';
22
+ const OPEN_TIMED_OUT = 'timed-out';
18
23
  /** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */
19
24
  export class AbstractDataSource extends BaseHelper {
20
- static { _a = DATA_SOURCE_BRAND; }
25
+ constructor() {
26
+ super(...arguments);
27
+ this.isOpened = false;
28
+ this.isShutDown = false;
29
+ }
21
30
  /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */
22
31
  static { this[_a] = true; }
32
+ /**
33
+ * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}
34
+ * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.
35
+ */
36
+ supportsDeferredOpen() {
37
+ return false;
38
+ }
39
+ /** The `open.on` of `@datasource`, `start` when unset. */
40
+ getOpenMode() {
41
+ const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({
42
+ target: this.constructor,
43
+ });
44
+ return metadata?.open?.on ?? DataSourceOpenModes.START;
45
+ }
46
+ isOpenDeferred() {
47
+ return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;
48
+ }
49
+ /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */
50
+ getOpenTimeoutMs() {
51
+ const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({
52
+ target: this.constructor,
53
+ });
54
+ return metadata?.open?.timeoutMs ?? DataSourceOpenDefaults.TIMEOUT_MS;
55
+ }
56
+ /**
57
+ * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that
58
+ * opens at start: from the moment the application has started it, until `close()`.
59
+ */
60
+ isOpen() {
61
+ if (this.isShutDown) {
62
+ return false;
63
+ }
64
+ return this.isOpenDeferred() ? this.isOpened : true;
65
+ }
66
+ /** Whether the first use is opening the datasource right now. */
67
+ isOpening() {
68
+ return this.opening !== undefined;
69
+ }
70
+ /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */
71
+ isClosed() {
72
+ return this.isShutDown;
73
+ }
74
+ /**
75
+ * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a
76
+ * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.
77
+ */
78
+ [(_a = DATA_SOURCE_BRAND, OPENING_HANDLES)]() {
79
+ return this.createOpening();
80
+ }
81
+ /**
82
+ * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to
83
+ * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the
84
+ * boot's private key.
85
+ */
86
+ createOpening() {
87
+ const refuse = (member) => NotSupportedUtility.throwNotSupported({
88
+ scope: this.constructor.name,
89
+ feature: `opening.${member}`,
90
+ logger: this.logger,
91
+ });
92
+ return {
93
+ getConnector: () => refuse('getConnector'),
94
+ getClient: () => refuse('getClient'),
95
+ beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),
96
+ };
97
+ }
98
+ /**
99
+ * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.
100
+ * Refused for a family that cannot honour it.
101
+ */
102
+ deferOpen(opts) {
103
+ if (!this.supportsDeferredOpen()) {
104
+ throw getError({
105
+ message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,
106
+ });
107
+ }
108
+ this.deferredOptions = opts.options;
109
+ }
110
+ /**
111
+ * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller
112
+ * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the
113
+ * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After
114
+ * `close()` it rejects: a stopped application does not reopen its datasources.
115
+ */
116
+ ensureOpen() {
117
+ if (!this.isOpenDeferred()) {
118
+ return Promise.resolve();
119
+ }
120
+ // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.
121
+ if (this.isShutDown) {
122
+ return Promise.reject(getError({
123
+ message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,
124
+ }));
125
+ }
126
+ if (this.isOpened) {
127
+ return Promise.resolve();
128
+ }
129
+ if (this.abandoned) {
130
+ return Promise.reject(getError({
131
+ message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,
132
+ }));
133
+ }
134
+ this.opening ??= this.runOpen();
135
+ return this.opening;
136
+ }
137
+ async runOpen() {
138
+ const timeoutMs = this.getOpenTimeoutMs();
139
+ const work = Promise.resolve().then(() => this.configure(this.deferredOptions, this.createOpening()));
140
+ let timer;
141
+ const expired = new Promise((resolve) => {
142
+ if (timeoutMs > 0) {
143
+ timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);
144
+ }
145
+ });
146
+ try {
147
+ const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);
148
+ if (outcome === OPEN_TIMED_OUT) {
149
+ this.abandoned = this.settleAbandoned({ work });
150
+ throw getError({
151
+ message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,
152
+ });
153
+ }
154
+ this.isOpened = true;
155
+ }
156
+ catch (error) {
157
+ await this.discardOpenAttempt();
158
+ throw error;
159
+ }
160
+ finally {
161
+ if (timer !== undefined) {
162
+ clearTimeout(timer);
163
+ }
164
+ this.opening = undefined;
165
+ }
166
+ }
167
+ /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */
168
+ async settleAbandoned(opts) {
169
+ try {
170
+ await opts.work;
171
+ // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now
172
+ }
173
+ catch {
174
+ // Falls through to the clean-up.
175
+ }
176
+ await this.discardOpenAttempt();
177
+ this.abandoned = undefined;
178
+ }
179
+ async discardOpenAttempt() {
180
+ try {
181
+ await this.discardPartialOpen();
182
+ // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it
183
+ }
184
+ catch (cleanupError) {
185
+ this.logger
186
+ .for(this.ensureOpen.name)
187
+ .warn('Clean-up after a failed open also failed | error: %s', cleanupError);
188
+ }
189
+ }
190
+ /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */
191
+ discardPartialOpen() { }
192
+ /**
193
+ * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives
194
+ * during the first use closes what that open built instead of racing it.
195
+ */
196
+ async settleOpening() {
197
+ this.isShutDown = true;
198
+ try {
199
+ await this.opening;
200
+ // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on
201
+ }
202
+ catch (openError) {
203
+ this.logger
204
+ .for(this.close.name)
205
+ .debug('The open in flight failed while stopping | error: %s', openError);
206
+ }
207
+ }
23
208
  getSettings() {
24
209
  return this.settings;
25
210
  }
@@ -1 +1 @@
1
- {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,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAE5D,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE,CAAC;gBACrE,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,oCAAoC,IAAI,UAAU,UAAU,CAAC,IAAI,aAAa,IAAI,CAAC,IAAI,eAAe,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE;iBAC5K,CAAC,CAAC;YACL,CAAC;YAED,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YACvD,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC;QAC5C,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,CAAC,KAAK,CACV,mDAAmD,EACnD,IAAI,EACJ,IAAI,CAAC,IAAI,EACT,KAAK,CAAC,MAAM,EACZ,KAAK,CACN,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { NotSupportedUtility } from '@/utilities';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type {\n IDataSource,\n IDataSourceCapabilities,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n} from './common';\n\n/**\n * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.\n *\n * Two copies of this package give two `AbstractDataSource` classes, and `instanceof` across them is\n * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is\n * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every\n * subclass however deep.\n */\nexport const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');\n\n/** True for `AbstractDataSource` itself and for any class extending it, across package copies. */\nexport const isDataSourceClass = (value: unknown): value is TClass<AnyType> => {\n return typeof value === 'function' && DATA_SOURCE_BRAND in value;\n};\n\n/** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */\nexport abstract class AbstractDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n>\n extends BaseHelper\n implements IDataSource<Settings, Schema, ConfigurableOptions>\n{\n /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */\n static readonly [DATA_SOURCE_BRAND] = true;\n\n name: string;\n settings: Settings;\n schema: Schema;\n\n abstract configure(opts?: ConfigurableOptions): ValueOrPromise<void>;\n\n getSettings() {\n return this.settings;\n }\n\n getSchema(): Schema {\n if (!this.schema) {\n throw getError({\n message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,\n });\n }\n\n return this.schema;\n }\n\n /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */\n getCapabilities(): IDataSourceCapabilities {\n return { transactions: false };\n }\n\n /** Nothing to release at this root; a family that holds a connection overrides it. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */\n async beginTransaction(_opts?: ITransactionOptions): Promise<ITransaction> {\n return NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: 'Transactions',\n logger: this.logger,\n });\n }\n\n /** Model classes bound to this datasource via `@repository` metadata - paradigm-free (no schema/relation resolution). */\n protected getBoundModelClasses(): Array<TClass<unknown>> {\n return MetadataRegistry.getInstance().getModelClasses({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n }\n\n /** Walks model classes bound to this datasource, reads a connector-specific artifact via `read`, and returns a name-keyed registry - skips undefined reads, throws on duplicate names, honors `autoDiscovery: false`. */\n protected discoverDefinitions<TDefinition extends { name: string }>(opts: {\n read: (modelClass: TClass<unknown>) => TDefinition | undefined;\n kind: string;\n }): Record<string, TDefinition> {\n const { read, kind } = opts;\n const logger = this.logger.for(this.discoverDefinitions.name);\n const registry = MetadataRegistry.getInstance();\n\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n logger.debug('Auto-discovery disabled for %s', this.name);\n\n return {};\n }\n\n const modelClasses = this.getBoundModelClasses();\n\n const definitions: Record<string, TDefinition> = {};\n const definitionOwners = new Map<string, string>();\n\n for (const modelClass of modelClasses) {\n const definition = read(modelClass);\n\n if (!definition) {\n logger.warn(\n 'Model has no %s definition | Skipping | Name: %s | Model: %s',\n kind,\n this.name,\n modelClass.name,\n );\n continue;\n }\n\n const existingOwner = definitionOwners.get(definition.name);\n\n if (existingOwner !== undefined && existingOwner !== modelClass.name) {\n throw getError({\n message: `[${this.constructor.name}][discoverDefinitions] Duplicate ${kind} name '${definition.name}' | Name: ${this.name} | Classes: ${existingOwner}, ${modelClass.name}`,\n });\n }\n\n definitionOwners.set(definition.name, modelClass.name);\n definitions[definition.name] = definition;\n }\n\n const names = Object.keys(definitions);\n logger.debug(\n 'Detected %s(s) | Name: %s | Count: %s | Names: %j',\n kind,\n this.name,\n names.length,\n names,\n );\n\n return definitions;\n }\n}\n"]}
1
+ {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../src/base/datasources/abstract.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAUnE,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,4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AI,CAAC,WAAW,CAAC,IAAI,oCAAoC,IAAI,UAAU,UAAU,CAAC,IAAI,aAAa,IAAI,CAAC,IAAI,eAAe,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE;iBAC5K,CAAC,CAAC;YACL,CAAC;YAED,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YACvD,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC;QAC5C,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,CAAC,KAAK,CACV,mDAAmD,EACnD,IAAI,EACJ,IAAI,CAAC,IAAI,EACT,KAAK,CAAC,MAAM,EACZ,KAAK,CACN,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { NotSupportedUtility } from '@/utilities';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type {\n IDataSource,\n IDataSourceCapabilities,\n IDataSourceOpening,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n TDataSourceOpenMode,\n} from './common';\nimport { DataSourceOpenDefaults, DataSourceOpenModes } from './common';\nimport { OPENING_HANDLES } from './opening-handles';\n\n/**\n * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.\n *\n * Two copies of this package give two `AbstractDataSource` classes, and `instanceof` across them is\n * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is\n * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every\n * subclass however deep.\n */\nexport const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');\n\n/** True for `AbstractDataSource` itself and for any class extending it, across package copies. */\nexport const isDataSourceClass = (value: unknown): value is TClass<AnyType> => {\n return typeof value === 'function' && DATA_SOURCE_BRAND in value;\n};\n\n/** The two ways a race between the open and its timeout can end. */\nconst OPEN_DONE = 'done';\nconst OPEN_TIMED_OUT = 'timed-out';\n\n/** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */\nexport abstract class AbstractDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n>\n extends BaseHelper\n implements IDataSource<Settings, Schema, ConfigurableOptions>\n{\n /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */\n static readonly [DATA_SOURCE_BRAND] = true;\n\n name: string;\n settings: Settings;\n schema: Schema;\n\n abstract configure(\n opts?: ConfigurableOptions,\n opening?: IDataSourceOpening,\n ): ValueOrPromise<void>;\n\n /** The options the boot would have given `configure()`, kept for the open that the first use starts. */\n private deferredOptions?: ConfigurableOptions;\n\n /** The open in flight: every call that arrives meanwhile awaits this one promise. */\n private opening?: Promise<void>;\n\n /**\n * An open that outlived its timeout and has not settled. Nothing is retried until it has: two `configure()` must never\n * run at once, and when it does settle what it built is closed, never published.\n */\n private abandoned?: Promise<void>;\n\n private isOpened = false;\n private isShutDown = false;\n\n /**\n * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}\n * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.\n */\n protected supportsDeferredOpen(): boolean {\n return false;\n }\n\n /** The `open.on` of `@datasource`, `start` when unset. */\n getOpenMode(): TDataSourceOpenMode {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n\n return metadata?.open?.on ?? DataSourceOpenModes.START;\n }\n\n isOpenDeferred(): boolean {\n return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;\n }\n\n /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */\n getOpenTimeoutMs(): number {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n\n return metadata?.open?.timeoutMs ?? DataSourceOpenDefaults.TIMEOUT_MS;\n }\n\n /**\n * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that\n * opens at start: from the moment the application has started it, until `close()`.\n */\n isOpen(): boolean {\n if (this.isShutDown) {\n return false;\n }\n\n return this.isOpenDeferred() ? this.isOpened : true;\n }\n\n /** Whether the first use is opening the datasource right now. */\n isOpening(): boolean {\n return this.opening !== undefined;\n }\n\n /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */\n isClosed(): boolean {\n return this.isShutDown;\n }\n\n /**\n * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a\n * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.\n */\n [OPENING_HANDLES](): IDataSourceOpening {\n return this.createOpening();\n }\n\n /**\n * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to\n * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the\n * boot's private key.\n */\n protected createOpening(): IDataSourceOpening {\n const refuse = (member: string): never =>\n NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: `opening.${member}`,\n logger: this.logger,\n });\n\n return {\n getConnector: () => refuse('getConnector'),\n getClient: () => refuse('getClient'),\n beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),\n };\n }\n\n /**\n * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.\n * Refused for a family that cannot honour it.\n */\n deferOpen(opts: { options?: ConfigurableOptions }): void {\n if (!this.supportsDeferredOpen()) {\n throw getError({\n message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,\n });\n }\n\n this.deferredOptions = opts.options;\n }\n\n /**\n * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller\n * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the\n * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After\n * `close()` it rejects: a stopped application does not reopen its datasources.\n */\n ensureOpen(): Promise<void> {\n if (!this.isOpenDeferred()) {\n return Promise.resolve();\n }\n\n // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.\n if (this.isShutDown) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,\n }),\n );\n }\n\n if (this.isOpened) {\n return Promise.resolve();\n }\n\n if (this.abandoned) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,\n }),\n );\n }\n\n this.opening ??= this.runOpen();\n\n return this.opening;\n }\n\n private async runOpen(): Promise<void> {\n const timeoutMs = this.getOpenTimeoutMs();\n const work = Promise.resolve().then(() =>\n this.configure(this.deferredOptions, this.createOpening()),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<typeof OPEN_TIMED_OUT>((resolve) => {\n if (timeoutMs > 0) {\n timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);\n }\n });\n\n try {\n const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);\n\n if (outcome === OPEN_TIMED_OUT) {\n this.abandoned = this.settleAbandoned({ work });\n\n throw getError({\n message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,\n });\n }\n\n this.isOpened = true;\n } catch (error) {\n await this.discardOpenAttempt();\n\n throw error;\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n this.opening = undefined;\n }\n }\n\n /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */\n private async settleAbandoned(opts: { work: Promise<unknown> }): Promise<void> {\n try {\n await opts.work;\n // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now\n } catch {\n // Falls through to the clean-up.\n }\n\n await this.discardOpenAttempt();\n this.abandoned = undefined;\n }\n\n private async discardOpenAttempt(): Promise<void> {\n try {\n await this.discardPartialOpen();\n // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it\n } catch (cleanupError) {\n this.logger\n .for(this.ensureOpen.name)\n .warn('Clean-up after a failed open also failed | error: %s', cleanupError);\n }\n }\n\n /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */\n protected discardPartialOpen(): ValueOrPromise<void> {}\n\n /**\n * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives\n * during the first use closes what that open built instead of racing it.\n */\n protected async settleOpening(): Promise<void> {\n this.isShutDown = true;\n\n try {\n await this.opening;\n // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on\n } catch (openError) {\n this.logger\n .for(this.close.name)\n .debug('The open in flight failed while stopping | error: %s', openError);\n }\n }\n\n getSettings() {\n return this.settings;\n }\n\n getSchema(): Schema {\n if (!this.schema) {\n throw getError({\n message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,\n });\n }\n\n return this.schema;\n }\n\n /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */\n getCapabilities(): IDataSourceCapabilities {\n return { transactions: false };\n }\n\n /** Nothing to release at this root; a family that holds a connection overrides it. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */\n async beginTransaction(_opts?: ITransactionOptions): Promise<ITransaction> {\n return NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: 'Transactions',\n logger: this.logger,\n });\n }\n\n /** Model classes bound to this datasource via `@repository` metadata - paradigm-free (no schema/relation resolution). */\n protected getBoundModelClasses(): Array<TClass<unknown>> {\n return MetadataRegistry.getInstance().getModelClasses({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n }\n\n /** Walks model classes bound to this datasource, reads a connector-specific artifact via `read`, and returns a name-keyed registry - skips undefined reads, throws on duplicate names, honors `autoDiscovery: false`. */\n protected discoverDefinitions<TDefinition extends { name: string }>(opts: {\n read: (modelClass: TClass<unknown>) => TDefinition | undefined;\n kind: string;\n }): Record<string, TDefinition> {\n const { read, kind } = opts;\n const logger = this.logger.for(this.discoverDefinitions.name);\n const registry = MetadataRegistry.getInstance();\n\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n logger.debug('Auto-discovery disabled for %s', this.name);\n\n return {};\n }\n\n const modelClasses = this.getBoundModelClasses();\n\n const definitions: Record<string, TDefinition> = {};\n const definitionOwners = new Map<string, string>();\n\n for (const modelClass of modelClasses) {\n const definition = read(modelClass);\n\n if (!definition) {\n logger.warn(\n 'Model has no %s definition | Skipping | Name: %s | Model: %s',\n kind,\n this.name,\n modelClass.name,\n );\n continue;\n }\n\n const existingOwner = definitionOwners.get(definition.name);\n\n if (existingOwner !== undefined && existingOwner !== modelClass.name) {\n throw getError({\n message: `[${this.constructor.name}][discoverDefinitions] Duplicate ${kind} name '${definition.name}' | Name: ${this.name} | Classes: ${existingOwner}, ${modelClass.name}`,\n });\n }\n\n definitionOwners.set(definition.name, modelClass.name);\n definitions[definition.name] = definition;\n }\n\n const names = Object.keys(definitions);\n logger.debug(\n 'Detected %s(s) | Name: %s | Count: %s | Names: %j',\n kind,\n this.name,\n names.length,\n names,\n );\n\n return definitions;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AnyType, IConfigurable, TClass, TConstValue } from '@venizia/ignis-helpers/common';
1
+ import type { AnyType, IConfigurable, TClass, TConstValue, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
2
  /** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */
3
3
  export declare class DataSourceDrivers {
4
4
  static readonly NODE_POSTGRES = "node-postgres";
@@ -12,6 +12,55 @@ export declare class DataSourceDrivers {
12
12
  static readonly SCHEME_SET: Set<string>;
13
13
  static isValid(value: string): boolean;
14
14
  }
15
+ /** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */
16
+ export declare class DataSourceOpenModes {
17
+ static readonly START = "start";
18
+ static readonly FIRST_USE = "first-use";
19
+ static readonly SCHEME_SET: Set<string>;
20
+ static isValid(value: string): value is TDataSourceOpenMode;
21
+ }
22
+ /** Defaults of the `open` option. */
23
+ export declare class DataSourceOpenDefaults {
24
+ /** How long a first use waits for the open before it gives up (ms): a WASM boot on a slow link fits, a `configure()` that waits on itself does not hang for ever. */
25
+ static readonly TIMEOUT_MS = 60000;
26
+ }
27
+ /** One of the {@link DataSourceOpenModes} values. */
28
+ export type TDataSourceOpenMode = TConstValue<typeof DataSourceOpenModes>;
29
+ /** The `open` option of `@datasource`. */
30
+ export interface IDataSourceOpenOptions {
31
+ /**
32
+ * `start`: `configure()` runs when the application starts, and `listen()` waits for it. `first-use`: the application
33
+ * starts without opening the datasource; the first call that needs it runs `configure()` once, and every call that
34
+ * arrives meanwhile waits for that one open. A failed open rejects every waiting call, leaves nothing half-open, and is
35
+ * tried again by the next call.
36
+ *
37
+ * @default 'start'
38
+ */
39
+ on?: TDataSourceOpenMode;
40
+ /**
41
+ * `first-use` only: how long the open may take (ms) before every waiting call is rejected with a named error and the
42
+ * attempt is abandoned. An abandoned `configure()` that finishes later is closed and never published, and the next call
43
+ * waits until it has settled before trying again. `0` waits for ever.
44
+ *
45
+ * @default 60000
46
+ */
47
+ timeoutMs?: number;
48
+ }
49
+ /**
50
+ * What `configure()` is given to do its database work while the datasource is opening: the connector, the client and a
51
+ * transaction, through the datasource's own ungated internals. Only `configure()` receives it, so nothing outside can use it
52
+ * and every other caller still waits for the open to finish. Generic over the datasource's connector, client and
53
+ * transaction types, so `opening.getClient()` of a PGlite datasource is a `PGlite`.
54
+ *
55
+ * Inside the open of a datasource that opens on first use, the public `getConnector()`, `getClient()` and
56
+ * `beginTransaction()` are gated (they wait for the open, which waits for `configure()`), and a repository cannot be used:
57
+ * use these handles instead.
58
+ */
59
+ export interface IDataSourceOpening<TConnector = unknown, Client = unknown, TTransaction extends ITransaction = ITransaction, TTransactionOptions extends ITransactionOptions = ITransactionOptions> {
60
+ getConnector(): TConnector;
61
+ getClient(): Client;
62
+ beginTransaction(opts?: TTransactionOptions): Promise<TTransaction>;
63
+ }
15
64
  /** A driver name: one of `DataSourceDrivers`, or any other string for an unlisted engine. */
16
65
  export type TDataSourceDriver = TConstValue<typeof DataSourceDrivers> | (string & {});
17
66
  /**
@@ -31,6 +80,16 @@ export interface IDataSource<Settings extends object = {}, Schema extends TAnyDa
31
80
  getSchema(): Schema;
32
81
  /** Releases what `configure()` opened. `stop()` calls it on every datasource the boot configured. */
33
82
  close?(): Promise<void>;
83
+ /** The datasource's own `configure()` receives the handles of {@link IDataSourceOpening} as its second argument. */
84
+ configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;
85
+ /** True when the datasource opens on first use (`@datasource({ open: { on: 'first-use' } })`): the boot then calls {@link deferOpen} instead of `configure()`. */
86
+ isOpenDeferred?(): boolean;
87
+ /** Records the options `configure()` will get when the datasource opens on first use; nothing is opened. */
88
+ deferOpen?(opts: {
89
+ options?: ConfigurableOptions;
90
+ }): void;
91
+ /** Resolves once the datasource is open: at once when it opens with the application or is already open, else after the one open that the first use starts. */
92
+ ensureOpen?(): Promise<void>;
34
93
  }
35
94
  /**
36
95
  * Neutral transaction options - isolation levels are engine vocabulary, so `isolationLevel` stays
@@ -29,4 +29,18 @@ export class DataSourceDrivers {
29
29
  return this.SCHEME_SET.has(value);
30
30
  }
31
31
  }
32
+ /** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */
33
+ export class DataSourceOpenModes {
34
+ static { this.START = 'start'; }
35
+ static { this.FIRST_USE = 'first-use'; }
36
+ static { this.SCHEME_SET = new Set([this.START, this.FIRST_USE]); }
37
+ static isValid(value) {
38
+ return this.SCHEME_SET.has(value);
39
+ }
40
+ }
41
+ /** Defaults of the `open` option. */
42
+ export class DataSourceOpenDefaults {
43
+ /** How long a first use waits for the open before it gives up (ms): a WASM boot on a slow link fits, a `configure()` that waits on itself does not hang for ever. */
44
+ static { this.TIMEOUT_MS = 60_000; }
45
+ }
32
46
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/base/datasources/common/types.ts"],"names":[],"mappings":"AAEA,sIAAsI;AACtI,MAAM,OAAO,iBAAiB;IAC5B,+FAA+F;aAC/E,kBAAa,GAAG,eAAe,CAAC;aAChC,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;IAElC,SAAS;aACO,cAAS,GAAG,WAAW,CAAC;aACxB,gBAAW,GAAG,aAAa,CAAC;aAE5B,0BAAqB,GAAG,IAAI,GAAG,CAAC;QAC9C,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;KACZ,CAAC,CAAC;aAEa,sBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;aAEhE,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,aAAa;QACb,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QAEX,SAAS;QACT,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { AnyType, IConfigurable, TClass, TConstValue } from '@venizia/ignis-helpers/common';\n\n/** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */\nexport class DataSourceDrivers {\n // Relational - PGlite is a Postgres DRIVER (Postgres compiled to WASM), not a separate engine.\n static readonly NODE_POSTGRES = 'node-postgres';\n static readonly POSTGRES_JS = 'postgres-js';\n static readonly PGLITE = 'pglite';\n static readonly LIBSQL = 'libsql';\n\n // Search\n static readonly TYPESENSE = 'typesense';\n static readonly MEILISEARCH = 'meilisearch';\n\n static readonly RELATIONAL_SCHEME_SET = new Set([\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n ]);\n\n static readonly SEARCH_SCHEME_SET = new Set([this.TYPESENSE, this.MEILISEARCH]);\n\n static readonly SCHEME_SET = new Set([\n // Relational\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n\n // Search\n this.TYPESENSE,\n this.MEILISEARCH,\n ]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n// `(string & {})` keeps autocomplete for the known values\n// while still accepting any other engine-driver string.\n/** A driver name: one of `DataSourceDrivers`, or any other string for an unlisted engine. */\nexport type TDataSourceDriver = TConstValue<typeof DataSourceDrivers> | (string & {});\n\n/**\n * A driver CLASS, named by `@datasource({ driver })`. The class reference is what pulls the peer\n * package into a bundle - a name string pulls nothing, and a bare side-effect import may be\n * dropped. Untyped because `IRelationalDriver` lives under `connectors/`, off-limits to `base/`.\n */\nexport type TDataSourceDriverClass = TClass<AnyType>;\n\n/** Loose schema record of a datasource; the default `Schema` type argument of `IDataSource`. */\nexport type TAnyDataSourceSchema = Record<string, any>;\n\n/** Engine-neutral datasource contract - the root every connector family implements. */\nexport interface IDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n> extends IConfigurable<ConfigurableOptions> {\n name: string;\n settings: Settings;\n schema: Schema;\n\n getSettings(): Settings;\n getSchema(): Schema;\n\n /** Releases what `configure()` opened. `stop()` calls it on every datasource the boot configured. */\n close?(): Promise<void>;\n}\n\n/**\n * Neutral transaction options - isolation levels are engine vocabulary, so `isolationLevel` stays\n * a loose string here and connectors narrow it in their own `ITransactionOptions` extension.\n */\nexport interface ITransactionOptions {\n isolationLevel?: string;\n}\n\n/** Neutral transaction handle - the minimum shape every connector's transaction satisfies. */\nexport interface ITransaction {\n isActive: boolean;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\n/** What a datasource supports. `transactions` tells whether it can open transactions. */\nexport interface IDataSourceCapabilities {\n transactions: boolean;\n}\n\n/** Capabilities of a search datasource. Each `search` flag tells whether the engine supports that feature. */\nexport interface ISearchableDataSourceCapabilities extends IDataSourceCapabilities {\n search?: {\n /** Vector / semantic / hybrid search (search engines). */\n vector?: boolean;\n\n /** Batched multi-query search across collections. */\n multi?: boolean;\n\n /** Merged (union) result set across a multi-search. */\n union?: boolean;\n\n /** Synonym sets (multi-way / one-way). */\n synonyms?: boolean;\n };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/base/datasources/common/types.ts"],"names":[],"mappings":"AAQA,sIAAsI;AACtI,MAAM,OAAO,iBAAiB;IAC5B,+FAA+F;aAC/E,kBAAa,GAAG,eAAe,CAAC;aAChC,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;IAElC,SAAS;aACO,cAAS,GAAG,WAAW,CAAC;aACxB,gBAAW,GAAG,aAAa,CAAC;aAE5B,0BAAqB,GAAG,IAAI,GAAG,CAAC;QAC9C,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;KACZ,CAAC,CAAC;aAEa,sBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;aAEhE,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,aAAa;QACb,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QAEX,SAAS;QACT,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAGH,6HAA6H;AAC7H,MAAM,OAAO,mBAAmB;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,cAAS,GAAG,WAAW,CAAC;aAExB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAEnE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAGH,qCAAqC;AACrC,MAAM,OAAO,sBAAsB;IACjC,qKAAqK;aACrJ,eAAU,GAAG,MAAM,CAAC","sourcesContent":["import type {\n AnyType,\n IConfigurable,\n TClass,\n TConstValue,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\n\n/** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */\nexport class DataSourceDrivers {\n // Relational - PGlite is a Postgres DRIVER (Postgres compiled to WASM), not a separate engine.\n static readonly NODE_POSTGRES = 'node-postgres';\n static readonly POSTGRES_JS = 'postgres-js';\n static readonly PGLITE = 'pglite';\n static readonly LIBSQL = 'libsql';\n\n // Search\n static readonly TYPESENSE = 'typesense';\n static readonly MEILISEARCH = 'meilisearch';\n\n static readonly RELATIONAL_SCHEME_SET = new Set([\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n ]);\n\n static readonly SEARCH_SCHEME_SET = new Set([this.TYPESENSE, this.MEILISEARCH]);\n\n static readonly SCHEME_SET = new Set([\n // Relational\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n\n // Search\n this.TYPESENSE,\n this.MEILISEARCH,\n ]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */\nexport class DataSourceOpenModes {\n static readonly START = 'start';\n static readonly FIRST_USE = 'first-use';\n\n static readonly SCHEME_SET = new Set([this.START, this.FIRST_USE]);\n\n static isValid(value: string): value is TDataSourceOpenMode {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Defaults of the `open` option. */\nexport class DataSourceOpenDefaults {\n /** How long a first use waits for the open before it gives up (ms): a WASM boot on a slow link fits, a `configure()` that waits on itself does not hang for ever. */\n static readonly TIMEOUT_MS = 60_000;\n}\n\n/** One of the {@link DataSourceOpenModes} values. */\nexport type TDataSourceOpenMode = TConstValue<typeof DataSourceOpenModes>;\n\n/** The `open` option of `@datasource`. */\nexport interface IDataSourceOpenOptions {\n /**\n * `start`: `configure()` runs when the application starts, and `listen()` waits for it. `first-use`: the application\n * starts without opening the datasource; the first call that needs it runs `configure()` once, and every call that\n * arrives meanwhile waits for that one open. A failed open rejects every waiting call, leaves nothing half-open, and is\n * tried again by the next call.\n *\n * @default 'start'\n */\n on?: TDataSourceOpenMode;\n\n /**\n * `first-use` only: how long the open may take (ms) before every waiting call is rejected with a named error and the\n * attempt is abandoned. An abandoned `configure()` that finishes later is closed and never published, and the next call\n * waits until it has settled before trying again. `0` waits for ever.\n *\n * @default 60000\n */\n timeoutMs?: number;\n}\n\n/**\n * What `configure()` is given to do its database work while the datasource is opening: the connector, the client and a\n * transaction, through the datasource's own ungated internals. Only `configure()` receives it, so nothing outside can use it\n * and every other caller still waits for the open to finish. Generic over the datasource's connector, client and\n * transaction types, so `opening.getClient()` of a PGlite datasource is a `PGlite`.\n *\n * Inside the open of a datasource that opens on first use, the public `getConnector()`, `getClient()` and\n * `beginTransaction()` are gated (they wait for the open, which waits for `configure()`), and a repository cannot be used:\n * use these handles instead.\n */\nexport interface IDataSourceOpening<\n TConnector = unknown,\n Client = unknown,\n TTransaction extends ITransaction = ITransaction,\n TTransactionOptions extends ITransactionOptions = ITransactionOptions,\n> {\n getConnector(): TConnector;\n getClient(): Client;\n beginTransaction(opts?: TTransactionOptions): Promise<TTransaction>;\n}\n\n// `(string & {})` keeps autocomplete for the known values\n// while still accepting any other engine-driver string.\n/** A driver name: one of `DataSourceDrivers`, or any other string for an unlisted engine. */\nexport type TDataSourceDriver = TConstValue<typeof DataSourceDrivers> | (string & {});\n\n/**\n * A driver CLASS, named by `@datasource({ driver })`. The class reference is what pulls the peer\n * package into a bundle - a name string pulls nothing, and a bare side-effect import may be\n * dropped. Untyped because `IRelationalDriver` lives under `connectors/`, off-limits to `base/`.\n */\nexport type TDataSourceDriverClass = TClass<AnyType>;\n\n/** Loose schema record of a datasource; the default `Schema` type argument of `IDataSource`. */\nexport type TAnyDataSourceSchema = Record<string, any>;\n\n/** Engine-neutral datasource contract - the root every connector family implements. */\nexport interface IDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n> extends IConfigurable<ConfigurableOptions> {\n name: string;\n settings: Settings;\n schema: Schema;\n\n getSettings(): Settings;\n getSchema(): Schema;\n\n /** Releases what `configure()` opened. `stop()` calls it on every datasource the boot configured. */\n close?(): Promise<void>;\n\n /** The datasource's own `configure()` receives the handles of {@link IDataSourceOpening} as its second argument. */\n configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;\n\n /** True when the datasource opens on first use (`@datasource({ open: { on: 'first-use' } })`): the boot then calls {@link deferOpen} instead of `configure()`. */\n isOpenDeferred?(): boolean;\n\n /** Records the options `configure()` will get when the datasource opens on first use; nothing is opened. */\n deferOpen?(opts: { options?: ConfigurableOptions }): void;\n\n /** Resolves once the datasource is open: at once when it opens with the application or is already open, else after the one open that the first use starts. */\n ensureOpen?(): Promise<void>;\n}\n\n/**\n * Neutral transaction options - isolation levels are engine vocabulary, so `isolationLevel` stays\n * a loose string here and connectors narrow it in their own `ITransactionOptions` extension.\n */\nexport interface ITransactionOptions {\n isolationLevel?: string;\n}\n\n/** Neutral transaction handle - the minimum shape every connector's transaction satisfies. */\nexport interface ITransaction {\n isActive: boolean;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\n/** What a datasource supports. `transactions` tells whether it can open transactions. */\nexport interface IDataSourceCapabilities {\n transactions: boolean;\n}\n\n/** Capabilities of a search datasource. Each `search` flag tells whether the engine supports that feature. */\nexport interface ISearchableDataSourceCapabilities extends IDataSourceCapabilities {\n search?: {\n /** Vector / semantic / hybrid search (search engines). */\n vector?: boolean;\n\n /** Batched multi-query search across collections. */\n multi?: boolean;\n\n /** Merged (union) result set across a multi-search. */\n union?: boolean;\n\n /** Synonym sets (multi-way / one-way). */\n synonyms?: boolean;\n };\n}\n"]}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The key under which the application boot asks a datasource for the handles of its open. A symbol, not a public method, and
3
+ * deliberately NOT exported from the package: `opening` must exist only as the argument of `configure()`, so no other code can
4
+ * reach the connector, the client or a transaction while the datasource is still opening (a request could then query before the
5
+ * migrations ran). The kernel's own boot imports this file by path; a consumer cannot name the symbol.
6
+ */
7
+ export declare const OPENING_HANDLES: unique symbol;
8
+ //# sourceMappingURL=opening-handles.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The key under which the application boot asks a datasource for the handles of its open. A symbol, not a public method, and
3
+ * deliberately NOT exported from the package: `opening` must exist only as the argument of `configure()`, so no other code can
4
+ * reach the connector, the client or a transaction while the datasource is still opening (a request could then query before the
5
+ * migrations ran). The kernel's own boot imports this file by path; a consumer cannot name the symbol.
6
+ */
7
+ export const OPENING_HANDLES = Symbol('@venizia/ignis-kernel:datasource-opening-handles');
8
+ //# sourceMappingURL=opening-handles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opening-handles.js","sourceRoot":"","sources":["../../../../src/base/datasources/opening-handles.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC","sourcesContent":["/**\n * The key under which the application boot asks a datasource for the handles of its open. A symbol, not a public method, and\n * deliberately NOT exported from the package: `opening` must exist only as the argument of `configure()`, so no other code can\n * reach the connector, the client or a transaction while the datasource is still opening (a request could then query before the\n * migrations ran). The kernel's own boot imports this file by path; a consumer cannot name the symbol.\n */\nexport const OPENING_HANDLES = Symbol('@venizia/ignis-kernel:datasource-opening-handles');\n"]}
@@ -2,7 +2,7 @@ import { BindingNamespaces } from '../../common/bindings.js';
2
2
  import { ArtifactTypes, BindingKeys, MetadataKeys, MetadataRegistry } from '../../helpers/inversion/index.js';
3
3
  import { ClassResolver, ResolverUtility } from '@venizia/ignis-helpers/common';
4
4
  import { getError } from '@venizia/ignis-helpers/core';
5
- import { isDataSourceClass } from '../datasources/index.js';
5
+ import { DataSourceOpenModes, isDataSourceClass } from '../datasources/index.js';
6
6
  import { RepositoryTypes } from '../repositories/common/constants.js';
7
7
  import { injectable, InjectableUtility } from './injectable.js';
8
8
  import { ModelMetadataUtility } from './model-metadata.js';
@@ -32,6 +32,11 @@ export const model = (input = {}) => {
32
32
  metadata: input,
33
33
  });
34
34
  const { settings } = metadata;
35
+ if (settings && Reflect.has(settings, 'hiddenProperties')) {
36
+ throw getError({
37
+ message: `[model][${target.name}] hiddenProperties was replaced by properties.hidden`,
38
+ });
39
+ }
35
40
  const defaultLimit = settings?.query?.limit?.default;
36
41
  if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {
37
42
  throw getError({
@@ -74,6 +79,20 @@ export const model = (input = {}) => {
74
79
  */
75
80
  export const datasource = (metadata) => {
76
81
  return (target) => {
82
+ const openTimeout = metadata?.open?.timeoutMs;
83
+ if (openTimeout !== undefined &&
84
+ (typeof openTimeout !== 'number' || !Number.isInteger(openTimeout) || openTimeout < 0)) {
85
+ throw getError({
86
+ message: `[datasource][@datasource][${target.name}] Invalid metadata | 'open.timeoutMs' must be a non-negative integer (ms; 0 waits for ever) | Got: ${String(openTimeout)}`,
87
+ });
88
+ }
89
+ const openMode = metadata?.open?.on;
90
+ // Untyped JS callers: a misspelt mode would silently mean "start", so it is refused where it is written.
91
+ if (openMode !== undefined && !DataSourceOpenModes.isValid(openMode)) {
92
+ throw getError({
93
+ message: `[datasource][@datasource][${target.name}] Invalid metadata | Unknown 'open.on': ${String(openMode)} | Expected one of: ${[...DataSourceOpenModes.SCHEME_SET].join(', ')}`,
94
+ });
95
+ }
77
96
  injectable({
78
97
  type: ArtifactTypes.DATASOURCE,
79
98
  ...InjectableUtility.pickRegistrationOptions({ metadata: metadata ?? {} }),