ddd-ts-kit 0.108.1 → 0.109.0

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 (91) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.fr.md +3 -2
  3. package/README.md +2 -1
  4. package/dist/check/catalogue/architecture-rules.d.ts.map +1 -1
  5. package/dist/check/catalogue/architecture-rules.js +2 -0
  6. package/dist/check/catalogue/architecture-rules.js.map +1 -1
  7. package/dist/check/explain/persistence-docs.d.ts.map +1 -1
  8. package/dist/check/explain/persistence-docs.js +18 -0
  9. package/dist/check/explain/persistence-docs.js.map +1 -1
  10. package/dist/check/fixtures/files-fixtures.d.ts.map +1 -1
  11. package/dist/check/fixtures/files-fixtures.js +77 -0
  12. package/dist/check/fixtures/files-fixtures.js.map +1 -1
  13. package/dist/check/rules/search-store-from-platform.d.ts +3 -0
  14. package/dist/check/rules/search-store-from-platform.d.ts.map +1 -0
  15. package/dist/check/rules/search-store-from-platform.js +93 -0
  16. package/dist/check/rules/search-store-from-platform.js.map +1 -0
  17. package/dist/commands/init.d.ts.map +1 -1
  18. package/dist/commands/init.js +1 -0
  19. package/dist/commands/init.js.map +1 -1
  20. package/dist/config/index.d.ts +1 -1
  21. package/dist/config/index.d.ts.map +1 -1
  22. package/dist/config/index.js +1 -1
  23. package/dist/config/index.js.map +1 -1
  24. package/dist/config/known-stack-keys.d.ts +1 -1
  25. package/dist/config/known-stack-keys.d.ts.map +1 -1
  26. package/dist/config/known-stack-keys.js +1 -0
  27. package/dist/config/known-stack-keys.js.map +1 -1
  28. package/dist/config/parse-stack.d.ts.map +1 -1
  29. package/dist/config/parse-stack.js +2 -1
  30. package/dist/config/parse-stack.js.map +1 -1
  31. package/dist/config/stack.d.ts +9 -0
  32. package/dist/config/stack.d.ts.map +1 -1
  33. package/dist/config/stack.js +1 -0
  34. package/dist/config/stack.js.map +1 -1
  35. package/dist/help/usage.js +1 -1
  36. package/dist/init/files/platform-files.d.ts.map +1 -1
  37. package/dist/init/files/platform-files.js +11 -0
  38. package/dist/init/files/platform-files.js.map +1 -1
  39. package/dist/init/manifest/dependencies-for.d.ts.map +1 -1
  40. package/dist/init/manifest/dependencies-for.js +2 -0
  41. package/dist/init/manifest/dependencies-for.js.map +1 -1
  42. package/dist/init/manifest/versions.d.ts.map +1 -1
  43. package/dist/init/manifest/versions.js +25 -24
  44. package/dist/init/manifest/versions.js.map +1 -1
  45. package/dist/init/stack/resolve-operations.d.ts +12 -0
  46. package/dist/init/stack/resolve-operations.d.ts.map +1 -0
  47. package/dist/init/stack/resolve-operations.js +23 -0
  48. package/dist/init/stack/resolve-operations.js.map +1 -0
  49. package/dist/init/stack/resolve-stack.d.ts.map +1 -1
  50. package/dist/init/stack/resolve-stack.js +2 -19
  51. package/dist/init/stack/resolve-stack.js.map +1 -1
  52. package/dist/init/stack/stack-options.d.ts +2 -0
  53. package/dist/init/stack/stack-options.d.ts.map +1 -1
  54. package/dist/init/template-vars.d.ts.map +1 -1
  55. package/dist/init/template-vars.js +6 -4
  56. package/dist/init/template-vars.js.map +1 -1
  57. package/dist/stack/stack-vars.js +5 -3
  58. package/dist/stack/stack-vars.js.map +1 -1
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +6 -5
  62. package/templates/init/README.md.tpl +20 -0
  63. package/templates/init/docker/docker-compose.yml.tpl +24 -0
  64. package/templates/init/docker/env.example.tpl +9 -0
  65. package/templates/init/e2e/test-environment.ts.tpl +4 -0
  66. package/templates/init/main.ts.tpl +3 -0
  67. package/templates/init/platform/composition/compose-application.container.ts.tpl +13 -0
  68. package/templates/init/platform/composition/compose-application.manual.ts.tpl +4 -0
  69. package/templates/init/platform/composition/lay-foundations.container.ts.tpl +30 -0
  70. package/templates/init/platform/composition/lay-foundations.manual.ts.tpl +11 -0
  71. package/templates/init/platform/composition/platform-options.manual.ts.tpl +7 -0
  72. package/templates/init/platform/composition/platform.manual.ts.tpl +7 -0
  73. package/templates/init/platform/config/app-config.ts.tpl +13 -0
  74. package/templates/init/platform/config/load-config.ts.tpl +38 -3
  75. package/templates/init/platform/search/open-search.ts.tpl +88 -0
  76. package/templates/init/platform/search/provisioned-indexes.ts.tpl +134 -0
  77. package/templates/init/platform/search/search-indexes.ts.tpl +23 -0
  78. package/templates/init/platform/search/search-name-taken-error.ts.tpl +10 -0
  79. package/templates/init/platform/search/search.module.container.ts.tpl +17 -0
  80. package/templates/init/platform/search/store-index.ts.tpl +49 -0
  81. package/templates/init/rules/infrastructure.md.tpl +3 -0
  82. package/templates/init/rules/platform.md.tpl +3 -0
  83. package/templates/init/scripts/privacy-erase.container.ts.tpl +9 -0
  84. package/templates/init/scripts/privacy-erase.manual.ts.tpl +9 -0
  85. package/templates/init/scripts/privacy-export.container.ts.tpl +9 -0
  86. package/templates/init/scripts/privacy-export.manual.ts.tpl +9 -0
  87. package/templates/init/scripts/privacy-purge.container.ts.tpl +9 -0
  88. package/templates/init/scripts/privacy-purge.manual.ts.tpl +9 -0
  89. package/templates/pipeline/package-scripts.json +1 -1
  90. package/templates/service/main.ts.tpl +3 -0
  91. package/templates/worker/main.ts.tpl +3 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ddd-ts-kit",
3
- "version": "0.108.1",
3
+ "version": "0.109.0",
4
4
  "description": "Bootstrap, scaffold and verify Domain-Driven Design (DDD), Clean Architecture and hexagonal TypeScript backends on Node.js: project and code generators, architecture checks, OpenAPI and AsyncAPI documents, for developers and AI coding agents (Claude Code, Codex, GitHub Copilot).",
5
5
  "keywords": [
6
6
  "ddd",
@@ -55,10 +55,11 @@
55
55
  "clean:packages": "node dist/bin.js check --clean-only ../kernel/src ../validation/src ../http/src ../tracing/src ../di/src ../events/src ../testing/src ../s3/src ../drizzle/src ../knex/src ../prisma/src ../typeorm/src ../aspects/src ../rabbitmq/src ../auth/src ../audit/src ../redis/src ../scheduling/src ../pino/src ../winston/src ../sentry/src ../kafka/src ../nats/src ../eslint-plugin/src"
56
56
  },
57
57
  "devDependencies": {
58
- "@ddd-ts-kit/audit": "^0.108.1",
59
- "@ddd-ts-kit/auth": "^0.108.1",
60
- "@ddd-ts-kit/events": "^0.108.1",
61
- "@ddd-ts-kit/kernel": "^0.108.1",
58
+ "@ddd-ts-kit/audit": "^0.109.0",
59
+ "@ddd-ts-kit/auth": "^0.109.0",
60
+ "@ddd-ts-kit/events": "^0.109.0",
61
+ "@ddd-ts-kit/kernel": "^0.109.0",
62
+ "@ddd-ts-kit/opensearch": "^0.109.0",
62
63
  "@types/pg": "^8.23.1",
63
64
  "pg": "^8.23.1"
64
65
  }
@@ -233,6 +233,26 @@ upload; see https://github.com/gbourgeat/ddd-ts-kit/blob/main/docs/concepts/file
233
233
  | `FILES_SIGNING_SECRET` | signs the links, 32 characters at least: required in production, even before the first file arrives; drawn at each start elsewhere |
234
234
  {{/if}}
235
235
  {{/if}}
236
+ {{#if search.opensearch}}
237
+
238
+ ## Search
239
+
240
+ A read model that serves lists with filters, sorts and pages may live in OpenSearch, OpenSearch
241
+ in `docker-compose.yml` while developing: a copy for reading, written by its projection from the
242
+ events and rebuilt from them, never the source of truth nor what an invariant or a right is decided
243
+ on. Its port lives in `application/ports/`, its adapter in `infrastructure/` extends
244
+ `OpenSearchReadModelStore` of `@ddd-ts-kit/opensearch` and takes `SearchIndexes` of
245
+ `{{config.platformDir}}/search/search-indexes.ts`, which sets the node and the tenancy; the
246
+ platform provisions the index of each store built so before a request{{#if tenancy.any}}, for the tenant of the work once
247
+ the tenant directory of the platform lists it: a tenant it does not list creates no index{{/if}}. The start never fails
248
+ on it, and a project with no such store calls nothing at start. The specs of a context bind the port to the in-memory
249
+ store of the kernel; the tests of this project are given no node.
250
+
251
+ | Variable | Says |
252
+ |---|---|
253
+ | `OPENSEARCH_URL` | the node, or the load balancer in front of the cluster: required |
254
+ | `OPENSEARCH_USERNAME`, `OPENSEARCH_PASSWORD` | the user of the security plugin, both or neither: left out locally, where the plugin is off |
255
+ {{/if}}
236
256
  {{#if errors.sentry}}
237
257
 
238
258
  ## Error reporting
@@ -165,6 +165,27 @@ services:
165
165
  timeout: 3s
166
166
  retries: 30
167
167
 
168
+ {{/if}}
169
+ {{#if search.opensearch}}
170
+ # OpenSearch, one node for local use: its security plugin is off, so it holds no user and no TLS; a deployment keeps
171
+ # the plugin on, with TLS and a user whose rights cover the indices and aliases of this project only.
172
+ opensearch:
173
+ image: opensearchproject/opensearch:3@sha256:3b55f6b6249cfdb92b52ee59adc8a266203ba9ef9f5d82544fad6f1af2f3609e
174
+ environment:
175
+ discovery.type: single-node
176
+ DISABLE_SECURITY_PLUGIN: "true"
177
+ DISABLE_INSTALL_DEMO_CONFIG: "true"
178
+ OPENSEARCH_JAVA_OPTS: -Xms512m -Xmx512m
179
+ ports:
180
+ - "127.0.0.1:${OPENSEARCH_PORT:-9200}:9200"
181
+ volumes:
182
+ - opensearch-data:/usr/share/opensearch/data
183
+ healthcheck:
184
+ test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:9200/_cluster/health"]
185
+ interval: 5s
186
+ timeout: 5s
187
+ retries: 60
188
+
168
189
  {{/if}}
169
190
  {{#if authn.keycloak}}
170
191
  # Keycloak {{keycloak.version}} in development mode, for local use only: it imports docker/keycloak/{{project.name}}-realm.json
@@ -282,3 +303,6 @@ volumes:
282
303
  {{#if files.s3}}
283
304
  minio-data:
284
305
  {{/if}}
306
+ {{#if search.opensearch}}
307
+ opensearch-data:
308
+ {{/if}}
@@ -191,6 +191,15 @@ S3_ACCESS_KEY_ID=minio-app
191
191
  S3_SECRET_ACCESS_KEY=minio-app-secret
192
192
  MINIO_PORT=9000
193
193
  {{/if}}
194
+ {{#if search.opensearch}}
195
+
196
+ # The read models kept for search (OpenSearch in docker-compose.yml), a copy rebuilt from the events, never the source of truth.
197
+ OPENSEARCH_PORT=9200
198
+ OPENSEARCH_URL=http://localhost:9200
199
+ # The user of the security plugin, both or neither: left out locally, where the plugin is off; a service account in a deployment.
200
+ # OPENSEARCH_USERNAME=
201
+ # OPENSEARCH_PASSWORD=
202
+ {{/if}}
194
203
 
195
204
  # Traces: start Jaeger with `docker compose --profile observability up -d jaeger`, then open http://127.0.0.1:16686
196
205
  # Without an endpoint no span leaves the process.
@@ -30,6 +30,10 @@ export function testEnvironment(overrides: Variables = {}): Variables {
30
30
  VARNISH_URL: (process.env['VARNISH_URL'] ?? '') || 'http://varnish.e2e.test',
31
31
  VARNISH_PURGE_KEY: (process.env['VARNISH_PURGE_KEY'] ?? '') || 'e2e-purge-key',
32
32
  {{/if}}
33
+ {{#if search.opensearch}}
34
+ // The configuration asks for a node; the application of the tests is given none, so no store reaches it.
35
+ OPENSEARCH_URL: (process.env['OPENSEARCH_URL'] ?? '') || 'http://localhost:9200',
36
+ {{/if}}
33
37
  {{#if cache.rateLimit}}
34
38
  RATE_LIMIT_MAX: process.env['RATE_LIMIT_MAX'] ?? '1000000',
35
39
  {{/if}}
@@ -66,6 +66,9 @@ const application = composeApplication(
66
66
  {{#if files.any}}
67
67
  files: openFiles(config.files),
68
68
  {{/if}}
69
+ {{#if search.opensearch}}
70
+ search: config.search,
71
+ {{/if}}
69
72
  },
70
73
  hostedContexts,
71
74
  );
@@ -73,6 +73,9 @@ import { relateSystemActors } from '{{alias.platform}}/auth/relationships/relate
73
73
  {{/if}}
74
74
  import { createCommandBus } from '{{alias.platform}}/buses/create-command-bus{{alias.ext}}';
75
75
  import { createQueryBus } from '{{alias.platform}}/buses/create-query-bus{{alias.ext}}';
76
+ {{#if search.opensearch}}
77
+ import type { AppConfig } from '{{alias.platform}}/config/app-config{{alias.ext}}';
78
+ {{/if}}
76
79
  import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
77
80
  {{#if eventSourcing.on}}
78
81
  import { eventSourcingModule } from '{{alias.platform}}/event-sourcing/event-sourcing.module{{alias.ext}}';
@@ -87,6 +90,9 @@ import { filesModule } from '{{alias.platform}}/files/files.module{{alias.ext}}'
87
90
  import { DEFAULT_HOUSEKEEPING } from '{{alias.platform}}/jobs/housekeeping{{alias.ext}}';
88
91
  import { housekeepingModule } from '{{alias.platform}}/jobs/housekeeping.module{{alias.ext}}';
89
92
  {{/if}}
93
+ {{#if search.opensearch}}
94
+ import { searchModule } from '{{alias.platform}}/search/search.module{{alias.ext}}';
95
+ {{/if}}
90
96
  {{#if privacy.on}}
91
97
  import { privacyModule } from '{{alias.platform}}/privacy/privacy.module{{alias.ext}}';
92
98
  {{/if}}
@@ -115,6 +121,10 @@ export interface ApplicationOptions extends PlatformOptions {
115
121
  /** Where the content of files lives: the storage of `main.ts`; left out (the tools, the tests), the memory of the process. */
116
122
  readonly files?: FileStorage;
117
123
  {{/if}}
124
+ {{#if search.opensearch}}
125
+ /** Where the read models of OpenSearch live: the configuration of `main.ts`; left out (the tools, the tests), no node, and a store built then is refused at its first request. */
126
+ readonly search?: AppConfig['search'];
127
+ {{/if}}
118
128
  }
119
129
 
120
130
  export interface Application {
@@ -220,6 +230,9 @@ export function composeApplication(
220
230
  {{#if files.any}}
221
231
  filesModule(options.files ?? new InMemoryFileStorage(), { jobs: options.platformJobs !== false }),
222
232
  {{/if}}
233
+ {{#if search.opensearch}}
234
+ searchModule(foundations.search),
235
+ {{/if}}
223
236
  {{#if privacy.on}}
224
237
  privacyModule({ jobs: options.platformJobs !== false }),
225
238
  {{/if}}
@@ -289,6 +289,10 @@ async function start(platform: Platform, options: ApplicationOptions): Promise<v
289
289
  {{#unless broker.external}}
290
290
  subscribeAll(platform.subscriber, platform.audit.subscriptions);
291
291
  {{/unless}}
292
+ {{/if}}
293
+ {{#if search.opensearch}}
294
+ // The index of every read model of OpenSearch the contexts built, before an event reaches its projection.
295
+ await platform.search.provision();
292
296
  {{/if}}
293
297
  await options.events.start();
294
298
 
@@ -18,12 +18,22 @@ import { createAudit, type Audit } from '{{alias.platform}}/audit/create-audit{{
18
18
  {{#unless audit.on}}
19
19
  import { logDecisions } from '{{alias.platform}}/auth/authorization/log-decisions{{alias.ext}}';
20
20
  {{/unless}}
21
+ {{#if search.opensearch}}
22
+ import type { AppConfig } from '{{alias.platform}}/config/app-config{{alias.ext}}';
23
+ {{/if}}
21
24
  import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
22
25
  {{#if eventSourcing.on}}
23
26
  import { createEventSourcing, type EventSourcing } from '{{alias.platform}}/event-sourcing/create-event-sourcing{{alias.ext}}';
24
27
  {{/if}}
25
28
  import { createLogger, type LogSettings } from '{{alias.platform}}/observability/create-logger{{alias.ext}}';
26
29
  import { createMetrics } from '{{alias.platform}}/observability/create-metrics{{alias.ext}}';
30
+ {{#if search.opensearch}}
31
+ {{#if tenancy.any}}
32
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
33
+ {{/if}}
34
+ import { openSearch } from '{{alias.platform}}/search/open-search{{alias.ext}}';
35
+ import type { SearchIndexes } from '{{alias.platform}}/search/search-indexes{{alias.ext}}';
36
+ {{/if}}
27
37
 
28
38
  /**
29
39
  * What exists before any module: built once and handed to the kernel module, so that the buses,
@@ -49,6 +59,10 @@ export interface Foundations {
49
59
  /** The event store, the keys of the data subjects{{#if audit.on}}, audited,{{/if}} and the cipher of the personal values of the stored events. */
50
60
  readonly eventSourcing: EventSourcing;
51
61
  {{/if}}
62
+ {{#if search.opensearch}}
63
+ /** The read models of OpenSearch, with the transport and the tenancy of the platform: what the adapter of a read model port is built from. */
64
+ readonly search: SearchIndexes;
65
+ {{/if}}
52
66
  }
53
67
 
54
68
  interface Observed {
@@ -56,6 +70,14 @@ interface Observed {
56
70
  readonly log?: LogSettings;
57
71
  /** Whether a consumed event continues the trace of its publication (the default) or starts one linked to it. */
58
72
  readonly traceConsumers?: ConsumerTrace;
73
+ {{#if search.opensearch}}
74
+ /** Where the read models of OpenSearch live: the configuration in `main.ts`; left out (the tools, the tests), no node. */
75
+ readonly search?: AppConfig['search'];
76
+ {{#if tenancy.any}}
77
+ /** The tenants whose read models are provisioned. */
78
+ readonly tenants?: readonly string[];
79
+ {{/if}}
80
+ {{/if}}
59
81
  }
60
82
 
61
83
  export function layFoundations(persistence: Persistence, options: Observed): Foundations {
@@ -74,6 +96,14 @@ export function layFoundations(persistence: Persistence, options: Observed): Fou
74
96
  logger,
75
97
  metrics: createMetrics(),
76
98
  traced: traceApplication({ consumers: options.traceConsumers ?? 'continue' }),
99
+ {{#if search.opensearch}}
100
+ {{#if tenancy.any}}
101
+ search: openSearch(options.search, { logger, scope, directory: tenantDirectory(persistence, options.tenants) }),
102
+ {{/if}}
103
+ {{#unless tenancy.any}}
104
+ search: openSearch(options.search, { logger }),
105
+ {{/unless}}
106
+ {{/if}}
77
107
  {{#if audit.on}}
78
108
  audit,
79
109
  {{#if eventSourcing.on}}
@@ -40,6 +40,9 @@ import { createEventSourcing } from '{{alias.platform}}/event-sourcing/create-ev
40
40
  import { ConfiguredJobScheduler } from '{{alias.platform}}/jobs/configured-job-scheduler{{alias.ext}}';
41
41
  import { createLogger } from '{{alias.platform}}/observability/create-logger{{alias.ext}}';
42
42
  import { createMetrics } from '{{alias.platform}}/observability/create-metrics{{alias.ext}}';
43
+ {{#if search.opensearch}}
44
+ import { openSearch } from '{{alias.platform}}/search/open-search{{alias.ext}}';
45
+ {{/if}}
43
46
 
44
47
  {{foundations.founded}}
45
48
 
@@ -109,6 +112,14 @@ export function layFoundations(persistence: Persistence, options: PlatformOption
109
112
  {{#if cache.rateLimit}}
110
113
  rateLimiter: options.redis?.rateLimiter ?? new InMemoryRateLimiter(clock),
111
114
  {{/if}}
115
+ {{#if search.opensearch}}
116
+ {{#if tenancy.any}}
117
+ search: openSearch(options.search, { logger, scope, directory: parts.tenants }),
118
+ {{/if}}
119
+ {{#unless tenancy.any}}
120
+ search: openSearch(options.search, { logger }),
121
+ {{/unless}}
122
+ {{/if}}
112
123
  {{#if errors.none}}
113
124
  jobs: schedulerOf(options, traced, parts),
114
125
  {{/if}}
@@ -16,6 +16,9 @@ import type { JobSettings } from '@ddd-ts-kit/kernel';
16
16
  {{/unless}}
17
17
  import type { QueueWorkerOptions } from '@ddd-ts-kit/scheduling';
18
18
  import type { ConsumerTrace } from '@ddd-ts-kit/tracing';
19
+ {{#if search.opensearch}}
20
+ import type { AppConfig } from '{{alias.platform}}/config/app-config{{alias.ext}}';
21
+ {{/if}}
19
22
  import type { EventProvider } from '{{alias.platform}}/events/event-provider{{alias.ext}}';
20
23
  {{#if housekeeping.any}}
21
24
  import type { Housekeeping } from '{{alias.platform}}/jobs/housekeeping{{alias.ext}}';
@@ -71,4 +74,8 @@ export interface PlatformOptions {
71
74
  /** Where the content of files lives: the storage of `main.ts`; left out (the tools, the tests), the memory of the process. */
72
75
  readonly files?: FileStorage;
73
76
  {{/if}}
77
+ {{#if search.opensearch}}
78
+ /** Where the read models of OpenSearch live: the configuration of `main.ts`; left out (the tools, the tests), no node, and a store built then is refused at its first request. */
79
+ readonly search?: AppConfig['search'];
80
+ {{/if}}
74
81
  }
@@ -41,6 +41,9 @@ import type { EventSourcing } from '{{alias.platform}}/event-sourcing/create-eve
41
41
  import type { Files } from '{{alias.platform}}/files/create-files{{alias.ext}}';
42
42
  {{/if}}
43
43
  import type { BackgroundJobs } from '{{alias.platform}}/jobs/background-jobs{{alias.ext}}';
44
+ {{#if search.opensearch}}
45
+ import type { SearchIndexes } from '{{alias.platform}}/search/search-indexes{{alias.ext}}';
46
+ {{/if}}
44
47
 
45
48
  /** Wraps an adapter from outside: a span for its kind and, for what leaves the process, the default policy unless it states its own. */
46
49
  type Adapt = <T extends object>(instance: T, info: AspectInfo) => T;
@@ -115,4 +118,8 @@ export interface Platform {
115
118
  /** Where files live, the keys they are stored under and the staging that keeps them consistent with the database: never their content in a table. */
116
119
  readonly files: Files;
117
120
  {{/if}}
121
+ {{#if search.opensearch}}
122
+ /** The read models of OpenSearch, with the transport and the tenancy of the platform: what the adapter of a read model port is built from. */
123
+ readonly search: SearchIndexes;
124
+ {{/if}}
118
125
  }
@@ -100,6 +100,10 @@ export interface AppConfig {
100
100
  /** Where the content of files lives (`files/open-files.ts`), never in the database. */
101
101
  readonly files: FilesConfig;
102
102
  {{/if}}
103
+ {{#if search.opensearch}}
104
+ /** Where the read models of OpenSearch live (`search/open-search.ts`): a copy for search, never the source of truth. */
105
+ readonly search: SearchConfig;
106
+ {{/if}}
103
107
  }
104
108
 
105
109
  /** `LOG_LEVEL`, `LOG_FORMAT` and `LOG_SCRUB_MESSAGES`. */
@@ -137,6 +141,15 @@ interface KeycloakConfig {
137
141
  readonly clientId?: string;
138
142
  }
139
143
  {{/if}}
144
+ {{#if search.opensearch}}
145
+
146
+ /** `OPENSEARCH_URL`, and `OPENSEARCH_USERNAME` with `OPENSEARCH_PASSWORD` when the security plugin asks for a user (both or neither). */
147
+ interface SearchConfig {
148
+ readonly node: string;
149
+ readonly username?: string;
150
+ readonly password?: string;
151
+ }
152
+ {{/if}}
140
153
  {{#if authn.jwks}}
141
154
 
142
155
  /** Where tokens come from and whom they are for: the issuer, the audience this service answers to, the keys of the issuer. */
@@ -55,9 +55,7 @@ export function loadConfig(variables: Variables): AppConfig {
55
55
  {{/if}}
56
56
 
57
57
  const config: AppConfig = {
58
- serviceName: env.optional('OTEL_SERVICE_NAME') ?? '{{project.name}}',
59
- deploymentName: env.optional('DEPLOYMENT_NAME') ?? '{{project.name}}',
60
- serviceVersion: env.optional('SERVICE_VERSION') ?? '0.0.0',
58
+ ...readIdentity(env),
61
59
  environment,
62
60
  port: env.integer('PORT', { fallback: 3000, min: 0, max: 65535 }),
63
61
  log: readLog(env),
@@ -120,6 +118,9 @@ export function loadConfig(variables: Variables): AppConfig {
120
118
  {{#if files.s3}}
121
119
  files: readFiles(env),
122
120
  {{/if}}
121
+ {{#if search.opensearch}}
122
+ search: readSearch(env),
123
+ {{/if}}
123
124
  };
124
125
 
125
126
  env.assertValid();
@@ -127,6 +128,15 @@ export function loadConfig(variables: Variables): AppConfig {
127
128
  return config;
128
129
  }
129
130
 
131
+ /** What this process is called, in its deployment and in its version. */
132
+ function readIdentity(env: Environment): Pick<AppConfig, 'serviceName' | 'deploymentName' | 'serviceVersion'> {
133
+ return {
134
+ serviceName: env.optional('OTEL_SERVICE_NAME') ?? '{{project.name}}',
135
+ deploymentName: env.optional('DEPLOYMENT_NAME') ?? '{{project.name}}',
136
+ serviceVersion: env.optional('SERVICE_VERSION') ?? '0.0.0',
137
+ };
138
+ }
139
+
130
140
  {{#if authn.none}}
131
141
  /** The development header is believed where NODE_ENV says so, never by default. */
132
142
  function requireEnvironmentForTheDevelopmentHeader(env: Environment): void {
@@ -191,6 +201,13 @@ function readTenants(env: Environment): readonly string[] {
191
201
  if (!tenants.every(isTenantId)) {
192
202
  env.problem('TENANTS must list tenant ids: letters, digits, _ and -, at most 63 characters each');
193
203
  }
204
+ {{#if search.opensearch}}
205
+
206
+ // A tenant is part of the name of its search index, which OpenSearch keeps in lower case.
207
+ if (tenants.some((tenant) => tenant !== tenant.toLowerCase())) {
208
+ env.problem('TENANTS must be lower case: each tenant names a search index of OpenSearch');
209
+ }
210
+ {{/if}}
194
211
 
195
212
  return tenants;
196
213
  }
@@ -220,6 +237,24 @@ function readLogFormat(env: Environment): AppConfig['log']['format'] {
220
237
  }
221
238
  {{/if}}
222
239
 
240
+ {{#if search.opensearch}}
241
+ /** The node of OpenSearch, and the user of its security plugin: both or neither. */
242
+ function readSearch(env: Environment): AppConfig['search'] {
243
+ const username = env.optional('OPENSEARCH_USERNAME');
244
+ const password = env.optional('OPENSEARCH_PASSWORD');
245
+
246
+ if ((username === undefined) !== (password === undefined)) {
247
+ env.problem('OPENSEARCH_USERNAME and OPENSEARCH_PASSWORD must be set together, or neither');
248
+ }
249
+
250
+ return {
251
+ node: env.url('OPENSEARCH_URL'),
252
+ ...(username === undefined ? {} : { username }),
253
+ ...(password === undefined ? {} : { password }),
254
+ };
255
+ }
256
+
257
+ {{/if}}
223
258
  function readResilience(env: Environment): AppConfig['resilience'] {
224
259
  return {
225
260
  retryAttempts: env.integer('OUTBOUND_RETRY_ATTEMPTS', { fallback: 3, min: 1, max: 10 }),
@@ -0,0 +1,88 @@
1
+ {{#if tenancy.any}}
2
+ import type { ExecutionScope, Logger, TenantDirectory } from '@ddd-ts-kit/kernel';
3
+ {{/if}}
4
+ {{#unless tenancy.any}}
5
+ import type { Logger } from '@ddd-ts-kit/kernel';
6
+ {{/unless}}
7
+ import {
8
+ OpenSearchUnavailableError,
9
+ fetchTransport,
10
+ type FetchTransportOptions,
11
+ type OpenSearchTransport,
12
+ } from '@ddd-ts-kit/opensearch';
13
+ import type { AppConfig } from '{{alias.platform}}/config/app-config{{alias.ext}}';
14
+ import { ProvisionedIndexes } from '{{alias.platform}}/search/provisioned-indexes{{alias.ext}}';
15
+ import type { SearchIndexes } from '{{alias.platform}}/search/search-indexes{{alias.ext}}';
16
+
17
+ /** What the read models of OpenSearch are built on: the logger of the platform{{#if tenancy.any}}, the tenant of the work and the tenants that exist{{/if}}. */
18
+ interface Grounds {
19
+ /** Where a provisioning of the start that failed is told, as a warning: the start goes on. */
20
+ readonly logger: Logger;
21
+ {{#if tenancy.any}}
22
+ readonly scope: ExecutionScope;
23
+ /** The tenants that exist, the same directory the jobs read: only a tenant it lists is ever provisioned. */
24
+ readonly directory: TenantDirectory;
25
+ {{/if}}
26
+ }
27
+
28
+ /** No node, for the tools and the tests that give none: the start provisions nothing, and a store is refused at its first request. */
29
+ const NO_NODE: OpenSearchTransport = {
30
+ request: ({ method, path }) =>
31
+ Promise.reject(
32
+ new OpenSearchUnavailableError(method, path, { cause: new Error('no OpenSearch node: pass `search` to the application') }),
33
+ ),
34
+ };
35
+
36
+ /**
37
+ * The read models of OpenSearch on the node of `config.search` (`OPENSEARCH_URL`); left out,
38
+ * none.
39
+ {{#if tenancy.any}}
40
+ * Shared tables keep the tenants of a store in one index, each document holding its
41
+ * tenant and each tenant read through a filtered alias: `{ strategy: 'attribute', scope }`. For
42
+ * an index per tenant (a tenant whose data must stay apart, dropped with its index when it leaves),
43
+ * write `{ strategy: 'index', scope }` instead.
44
+ {{/if}}
45
+ {{#unless tenancy.any}}
46
+ * Without tenancy a store is one index: `{ strategy: 'none' }`. Once the project has tenants
47
+ * (`init --force --tenancy shared-table`), this file keeps them apart.
48
+ {{/unless}}
49
+ */
50
+ {{#if tenancy.any}}
51
+ export function openSearch(config: AppConfig['search'] | undefined, { logger, scope, directory }: Grounds): SearchIndexes {
52
+ return new ProvisionedIndexes({
53
+ transport: transportOf(config),
54
+ tenancy: { strategy: 'attribute', scope },
55
+ logger,
56
+ reachable: config !== undefined,
57
+ tenants: { ofWork: () => tenantOfWork(scope), listed: () => directory.tenants() },
58
+ });
59
+ }
60
+ {{/if}}
61
+ {{#unless tenancy.any}}
62
+ export function openSearch(config: AppConfig['search'] | undefined, { logger }: Grounds): SearchIndexes {
63
+ return new ProvisionedIndexes({
64
+ transport: transportOf(config),
65
+ tenancy: { strategy: 'none' },
66
+ logger,
67
+ reachable: config !== undefined,
68
+ });
69
+ }
70
+ {{/unless}}
71
+
72
+ function transportOf(config: AppConfig['search'] | undefined): OpenSearchTransport {
73
+ return config === undefined ? NO_NODE : fetchTransport({ node: config.node, ...authOf(config) });
74
+ }
75
+
76
+ /** The user of the security plugin, when the configuration names one. */
77
+ function authOf({ username, password }: AppConfig['search']): Pick<FetchTransportOptions, 'auth'> {
78
+ return username === undefined || password === undefined ? {} : { auth: { username, password } };
79
+ }
80
+ {{#if tenancy.any}}
81
+
82
+ /** The tenant a request is provisioned for: none for work with no tenant, nor under an elevation, which reads across tenants. */
83
+ function tenantOfWork(scope: ExecutionScope): string | undefined {
84
+ const work = scope.current();
85
+
86
+ return work?.elevation === undefined ? work?.tenantId : undefined;
87
+ }
88
+ {{/if}}
@@ -0,0 +1,134 @@
1
+ import type { CriteriaDefinition, Logger } from '@ddd-ts-kit/kernel';
2
+ import {
3
+ OpenSearchReadModelStore,
4
+ type OpenSearchReadModelOptions,
5
+ type OpenSearchTenancy,
6
+ type OpenSearchTransport,
7
+ } from '@ddd-ts-kit/opensearch';
8
+ import { SearchIndexes, type SearchStoreSettings } from '{{alias.platform}}/search/search-indexes{{alias.ext}}';
9
+ import { SearchNameTakenError } from '{{alias.platform}}/search/search-name-taken-error{{alias.ext}}';
10
+ import { StoreIndex } from '{{alias.platform}}/search/store-index{{alias.ext}}';
11
+
12
+ /** The tenants a store is provisioned for, under a tenant strategy. */
13
+ interface Tenants {
14
+ /** The tenant of the work a request is sent for; none for work with no tenant or under an elevation. */
15
+ readonly ofWork: () => string | undefined;
16
+ /** The tenants that exist: a tenant it does not list is never provisioned, and its store refuses it. */
17
+ readonly listed: () => Promise<readonly string[]>;
18
+ }
19
+
20
+ /** What every store is built and provisioned with. */
21
+ interface IndexSettings {
22
+ readonly transport: OpenSearchTransport;
23
+ readonly tenancy: OpenSearchTenancy;
24
+ readonly logger: Logger;
25
+ /** `false` without a node: the start provisions nothing, and the transport refuses each request. */
26
+ readonly reachable: boolean;
27
+ /** Left out without tenancy: the index of a store is then provisioned once, by `ensureMapping`. */
28
+ readonly tenants?: Tenants;
29
+ }
30
+
31
+ /** A store built under a name: what it was built from, and its index. */
32
+ interface Built {
33
+ readonly definition: unknown;
34
+ readonly fields: unknown;
35
+ readonly index: StoreIndex;
36
+ }
37
+
38
+ /**
39
+ * The stores built from the platform, one index each, provisioned before a request: once without
40
+ * tenancy, for each tenant of the work the directory lists otherwise. A tenant whose provisioning
41
+ * failed is tried again at its next request, the others untouched.
42
+ */
43
+ export class ProvisionedIndexes extends SearchIndexes {
44
+ private readonly stores = new Map<string, Built>();
45
+
46
+ constructor(private readonly settings: IndexSettings) {
47
+ super();
48
+ }
49
+
50
+ options<Row extends object>(
51
+ name: string,
52
+ definition: CriteriaDefinition<Row>,
53
+ settings: SearchStoreSettings<Row> = {},
54
+ ): OpenSearchReadModelOptions<Row> {
55
+ const { transport, tenancy } = this.settings;
56
+ const options = { ...settings, transport, name, definition, tenancy };
57
+ const built = { definition, fields: settings.fields };
58
+ const index = this.indexOf(name, built, () => new StoreIndex(new OpenSearchReadModelStore(options)));
59
+
60
+ return { ...options, transport: { request: (request) => this.ready(index).then(() => transport.request(request)) } };
61
+ }
62
+
63
+ /** At the start, best effort: every tenant the directory lists, for each store built by then; a failure is a warning. */
64
+ async provision(): Promise<void> {
65
+ if (!this.settings.reachable) {
66
+ return;
67
+ }
68
+
69
+ await Promise.all([...this.stores].map(([name, { index }]) => this.provisionAtStart(name, index)));
70
+ }
71
+
72
+ private indexOf(name: string, built: Omit<Built, 'index'>, created: () => StoreIndex): StoreIndex {
73
+ const known = this.stores.get(name);
74
+
75
+ if (known === undefined) {
76
+ const index = created();
77
+
78
+ this.stores.set(name, { ...built, index });
79
+
80
+ return index;
81
+ }
82
+
83
+ if (known.definition !== built.definition || !sameFields(known.fields, built.fields)) {
84
+ throw new SearchNameTakenError(name);
85
+ }
86
+
87
+ return known.index;
88
+ }
89
+
90
+ private async ready(index: StoreIndex): Promise<void> {
91
+ const { tenants } = this.settings;
92
+
93
+ if (tenants === undefined) {
94
+ return index.mapped();
95
+ }
96
+
97
+ const tenant = tenants.ofWork();
98
+
99
+ if (tenant !== undefined && (index.has(tenant) || (await tenants.listed()).includes(tenant))) {
100
+ await index.provisioned(tenant);
101
+ }
102
+ }
103
+
104
+ private async provisionAtStart(name: string, index: StoreIndex): Promise<void> {
105
+ const { tenants } = this.settings;
106
+
107
+ if (tenants === undefined) {
108
+ return index.mapped().catch((error: unknown) => this.warn(error, name));
109
+ }
110
+
111
+ const listed = await tenants.listed().catch((error: unknown) => {
112
+ this.warn(error, name);
113
+
114
+ return [];
115
+ });
116
+
117
+ await Promise.all(
118
+ listed.map((tenant) => index.provisioned(tenant).catch((error: unknown) => this.warn(error, name, tenant))),
119
+ );
120
+ }
121
+
122
+ private warn(error: unknown, store: string, tenant?: string): void {
123
+ this.settings.logger.warn('search index not provisioned', {
124
+ store,
125
+ ...(tenant === undefined ? {} : { tenant }),
126
+ error: error instanceof Error ? error : String(error),
127
+ });
128
+ }
129
+ }
130
+
131
+ /** The same fields kept with the rows: the same names with the same types. */
132
+ function sameFields(known: unknown, asked: unknown): boolean {
133
+ return JSON.stringify(known ?? {}) === JSON.stringify(asked ?? {});
134
+ }
@@ -0,0 +1,23 @@
1
+ import type { CriteriaDefinition } from '@ddd-ts-kit/kernel';
2
+ import type { OpenSearchReadModelOptions } from '@ddd-ts-kit/opensearch';
3
+
4
+ /** What a store may add to its name and its definition: the other fields of its rows, a write seen by the next search, the settings of its index. */
5
+ export type SearchStoreSettings<Row> = Pick<OpenSearchReadModelOptions<Row>, 'fields' | 'refresh' | 'settings'>;
6
+
7
+ /**
8
+ * The read models kept in OpenSearch, as a capability of the platform. The adapter of a read
9
+ * model port extends `OpenSearchReadModelStore` and passes to it what `options` answers: the
10
+ * transport and the tenancy of the project are set here, never in a context. The platform
11
+ * provisions the index of every store built so, before its first request.
12
+ */
13
+ export abstract class SearchIndexes {
14
+ /** The options of the store `name`: lower case letters, digits and `_`, prefixed by its context (`billing_invoices`). */
15
+ abstract options<Row extends object>(
16
+ name: string,
17
+ definition: CriteriaDefinition<Row>,
18
+ settings?: SearchStoreSettings<Row>,
19
+ ): OpenSearchReadModelOptions<Row>;
20
+
21
+ /** Provisions the index of every store built so far: at the start of the application, and again at will, since it is idempotent. */
22
+ abstract provision(): Promise<void>;
23
+ }