ddd-ts-kit 0.93.0 → 0.94.1

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 (90) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.fr.md +2 -2
  3. package/README.md +1 -1
  4. package/dist/check/authz/modelled-permissions.d.ts +32 -0
  5. package/dist/check/authz/modelled-permissions.d.ts.map +1 -0
  6. package/dist/check/authz/modelled-permissions.js +169 -0
  7. package/dist/check/authz/modelled-permissions.js.map +1 -0
  8. package/dist/check/catalogue/architecture-rules.d.ts.map +1 -1
  9. package/dist/check/catalogue/architecture-rules.js +4 -0
  10. package/dist/check/catalogue/architecture-rules.js.map +1 -1
  11. package/dist/check/explain/authz-docs.d.ts.map +1 -1
  12. package/dist/check/explain/authz-docs.js +17 -0
  13. package/dist/check/explain/authz-docs.js.map +1 -1
  14. package/dist/check/explain/scheduling-docs.d.ts.map +1 -1
  15. package/dist/check/explain/scheduling-docs.js +7 -0
  16. package/dist/check/explain/scheduling-docs.js.map +1 -1
  17. package/dist/check/fixtures/authz-resource-modelled-fixtures.d.ts +3 -0
  18. package/dist/check/fixtures/authz-resource-modelled-fixtures.d.ts.map +1 -0
  19. package/dist/check/fixtures/authz-resource-modelled-fixtures.js +194 -0
  20. package/dist/check/fixtures/authz-resource-modelled-fixtures.js.map +1 -0
  21. package/dist/check/fixtures/fixtures.d.ts.map +1 -1
  22. package/dist/check/fixtures/fixtures.js +2 -0
  23. package/dist/check/fixtures/fixtures.js.map +1 -1
  24. package/dist/check/fixtures/scheduling-fixtures.d.ts.map +1 -1
  25. package/dist/check/fixtures/scheduling-fixtures.js +69 -1
  26. package/dist/check/fixtures/scheduling-fixtures.js.map +1 -1
  27. package/dist/check/rules/authz-resource-modelled.d.ts +13 -0
  28. package/dist/check/rules/authz-resource-modelled.d.ts.map +1 -0
  29. package/dist/check/rules/authz-resource-modelled.js +128 -0
  30. package/dist/check/rules/authz-resource-modelled.js.map +1 -0
  31. package/dist/check/rules/scheduling-tenancy-declared.d.ts +3 -0
  32. package/dist/check/rules/scheduling-tenancy-declared.d.ts.map +1 -0
  33. package/dist/check/rules/scheduling-tenancy-declared.js +45 -0
  34. package/dist/check/rules/scheduling-tenancy-declared.js.map +1 -0
  35. package/dist/check/scheduling/job-names.d.ts +1 -1
  36. package/dist/check/scheduling/job-names.d.ts.map +1 -1
  37. package/dist/check/scheduling/job-names.js +3 -21
  38. package/dist/check/scheduling/job-names.js.map +1 -1
  39. package/dist/check/scheduling/jobs-declared.d.ts +11 -0
  40. package/dist/check/scheduling/jobs-declared.d.ts.map +1 -0
  41. package/dist/check/scheduling/jobs-declared.js +24 -0
  42. package/dist/check/scheduling/jobs-declared.js.map +1 -0
  43. package/dist/generate/access-vars.js +18 -0
  44. package/dist/generate/access-vars.js.map +1 -1
  45. package/dist/generate/kinds/job/grant-system-actor.js +2 -2
  46. package/dist/generate/kinds/job/grant-system-actor.js.map +1 -1
  47. package/dist/generate/kinds/job-kind.js +1 -1
  48. package/dist/generate/kinds/job-kind.js.map +1 -1
  49. package/dist/init/files/platform-files.js +1 -0
  50. package/dist/init/files/platform-files.js.map +1 -1
  51. package/dist/init/manifest/versions.js +24 -24
  52. package/dist/platform-layout/platform-layout.d.ts +1 -0
  53. package/dist/platform-layout/platform-layout.d.ts.map +1 -1
  54. package/dist/platform-layout/platform-layout.js +1 -0
  55. package/dist/platform-layout/platform-layout.js.map +1 -1
  56. package/dist/presets/apply-preset.d.ts.map +1 -1
  57. package/dist/presets/apply-preset.js +4 -0
  58. package/dist/presets/apply-preset.js.map +1 -1
  59. package/dist/presets/organisations-as-tenant-directory.d.ts +10 -0
  60. package/dist/presets/organisations-as-tenant-directory.d.ts.map +1 -0
  61. package/dist/presets/organisations-as-tenant-directory.js +16 -0
  62. package/dist/presets/organisations-as-tenant-directory.js.map +1 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +4 -4
  66. package/templates/command/command.ts.tpl +3 -0
  67. package/templates/file-upload/command.ts.tpl +3 -0
  68. package/templates/init/docker/env.example.tpl +2 -1
  69. package/templates/init/platform/audit/audit.module.tsyringe.ts.tpl +1 -1
  70. package/templates/init/platform/auth/relationships/relationship-schema.ts.tpl +24 -9
  71. package/templates/init/platform/composition/compose-application.tsyringe.ts.tpl +5 -5
  72. package/templates/init/platform/composition/lay-foundations.manual.ts.tpl +13 -17
  73. package/templates/init/platform/composition/tenant-directory.ts.tpl +14 -0
  74. package/templates/init/platform/config/app-config.ts.tpl +1 -1
  75. package/templates/init/platform/files/files.module.tsyringe.ts.tpl +1 -1
  76. package/templates/init/platform/privacy/privacy.module.tsyringe.ts.tpl +1 -1
  77. package/templates/init/scripts/privacy-erase.manual.ts.tpl +18 -8
  78. package/templates/init/scripts/privacy-erase.tsyringe.ts.tpl +18 -8
  79. package/templates/init/scripts/privacy-export.manual.ts.tpl +17 -7
  80. package/templates/init/scripts/privacy-export.tsyringe.ts.tpl +17 -7
  81. package/templates/job/job.spec.tsyringe.ts.tpl +1 -1
  82. package/templates/pipeline/github/workflows/ci.yml.tpl +2 -0
  83. package/templates/pipeline/gitlab/gitlab-ci.yml.tpl +2 -0
  84. package/templates/pipeline/package-scripts.json +1 -1
  85. package/templates/presets/identity/context/infrastructure/persistence/drizzle-organisation-tenant-directory.reader.drizzle.ts.tpl +26 -0
  86. package/templates/presets/identity/context/infrastructure/persistence/knex-organisation-tenant-directory.reader.knex.ts.tpl +30 -0
  87. package/templates/presets/identity/context/infrastructure/persistence/prisma-organisation-tenant-directory.reader.prisma.ts.tpl +25 -0
  88. package/templates/presets/identity/context/test/integration/organisation-tenant-directory.spec.ts.tpl +107 -0
  89. package/templates/presets/identity/platform/tenant-directory.ts.tpl +13 -0
  90. package/templates/query/query.ts.tpl +3 -0
@@ -8,9 +8,6 @@ import {
8
8
  {{#if cache.rateLimit}}
9
9
  InMemoryRateLimiter,
10
10
  {{/if}}
11
- {{#if tenancy.any}}
12
- InMemoryTenantDirectory,
13
- {{/if}}
14
11
  {{#if errors.sentry}}
15
12
  NoopErrorReporter,
16
13
  {{/if}}
@@ -34,6 +31,9 @@ import { logDecisions } from '{{alias.platform}}/auth/authorization/log-decision
34
31
  import type { Platform } from '{{alias.platform}}/composition/platform{{alias.ext}}';
35
32
  import type { PlatformOptions } from '{{alias.platform}}/composition/platform-options{{alias.ext}}';
36
33
  import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
34
+ {{#if tenancy.any}}
35
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
36
+ {{/if}}
37
37
  {{#if eventSourcing.on}}
38
38
  import { createEventSourcing } from '{{alias.platform}}/event-sourcing/create-event-sourcing{{alias.ext}}';
39
39
  {{/if}}
@@ -82,6 +82,14 @@ export function layFoundations(persistence: Persistence, options: PlatformOption
82
82
  const audit = createAudit(persistence, { scope, clock, ids });
83
83
  {{/if}}
84
84
 
85
+ {{#if tenancy.any}}
86
+ // The tenants a job declared `per-tenant` runs for, asked at each occurrence.
87
+ const parts = { clock, lock, scope, ids, logger, metrics, tenants: tenantDirectory(persistence, options.tenants) };
88
+ {{/if}}
89
+ {{#unless tenancy.any}}
90
+ const parts = { clock, lock, scope, ids, logger, metrics };
91
+ {{/unless}}
92
+
85
93
  return {
86
94
  traced,
87
95
  scope,
@@ -102,11 +110,11 @@ export function layFoundations(persistence: Persistence, options: PlatformOption
102
110
  rateLimiter: options.redis?.rateLimiter ?? new InMemoryRateLimiter(clock),
103
111
  {{/if}}
104
112
  {{#if errors.none}}
105
- jobs: schedulerOf(options, traced, { clock, lock, scope, ids, logger, metrics }),
113
+ jobs: schedulerOf(options, traced, parts),
106
114
  {{/if}}
107
115
  {{#if errors.sentry}}
108
116
  // A run that failed, a timeout included, is reported; a skipped or missed occurrence is not.
109
- jobs: schedulerOf(options, traced, { clock, lock, scope, ids, logger, metrics, onRun: reportFailedRuns(errors) }),
117
+ jobs: schedulerOf(options, traced, { ...parts, onRun: reportFailedRuns(errors) }),
110
118
  {{/if}}
111
119
  {{#if audit.on}}
112
120
  audit,
@@ -129,17 +137,5 @@ function schedulerOf(
129
137
  traced: TracedApplication,
130
138
  parts: InProcessJobSchedulerOptions,
131
139
  ): JobScheduler {
132
- {{#if tenancy.any}}
133
- // The tenants a job declared `per-tenant` runs for; left out (the tools, the tests), none.
134
- const tenants = new InMemoryTenantDirectory(options.tenants ?? []);
135
-
136
- return new ConfiguredJobScheduler(
137
- new InProcessJobScheduler({ ...parts, tenants }),
138
- options.jobs?.settings ?? {},
139
- traced.job,
140
- );
141
- {{/if}}
142
- {{#unless tenancy.any}}
143
140
  return new ConfiguredJobScheduler(new InProcessJobScheduler(parts), options.jobs?.settings ?? {}, traced.job);
144
- {{/unless}}
145
141
  }
@@ -0,0 +1,14 @@
1
+ import { InMemoryTenantDirectory, type TenantDirectory } from '@ddd-ts-kit/kernel';
2
+ import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
3
+
4
+ /**
5
+ * The tenants a job declared `per-tenant` runs for, asked again at each occurrence.
6
+ *
7
+ * The project has no source of tenants yet, so this is the list of `TENANTS`, read once when the
8
+ * process starts: an organisation or a customer created later gets no run of such a job until the
9
+ * process restarts. Where the tenants live in the database, read them here instead (the identity
10
+ * preset writes this file that way: its organisations are the tenants).
11
+ */
12
+ export function tenantDirectory(_persistence: Persistence, fixed: readonly string[] = []): TenantDirectory {
13
+ return new InMemoryTenantDirectory(fixed);
14
+ }
@@ -27,7 +27,7 @@ export interface AppConfig {
27
27
  /** Whether this process runs the scheduled jobs (`RUN_JOBS`): off for the API of a project that has a worker. */
28
28
  readonly runJobs: boolean;
29
29
  {{#if tenancy.any}}
30
- /** The tenants that exist (`TENANTS`, comma separated): a job declared `per-tenant` runs once for each. Bind a directory of your own in `main.ts` once the tenants live in a table. */
30
+ /** The tenants that exist (`TENANTS`, comma separated): a job declared `per-tenant` runs once for each. Read once at the start: a tenant created later is missed. Once the tenants live in a table, make `composition/tenant-directory.ts` read it (the identity preset does). */
31
31
  readonly tenants: readonly string[];
32
32
  {{/if}}
33
33
  {{#if persistence.needsUrl}}
@@ -15,7 +15,7 @@ export function filesModule(storage: FileStorage, { jobs = true }: { readonly jo
15
15
 
16
16
  // Registered by the process that runs the jobs of the platform; a service of the deployment passes `jobs: false`.
17
17
  if (jobs) {
18
- builder.job('files.purge-staged', { every: '1h' }).handledBy(PurgeStagedFiles, [FileStaging, Clock]);
18
+ builder.job('files.purge-staged', { every: '1h', tenancy: 'global' }).handledBy(PurgeStagedFiles, [FileStaging, Clock]);
19
19
  }
20
20
  },
21
21
  });
@@ -12,7 +12,7 @@ export function privacyModule({ jobs = true }: { readonly jobs?: boolean } = {})
12
12
  register(builder) {
13
13
  // Registered by the process that runs the jobs of the platform; a service of the deployment passes `jobs: false`.
14
14
  if (jobs) {
15
- builder.job('privacy.purge-expired', { cron: '0 3 * * *' }).handledByFactory((resolve) => ({
15
+ builder.job('privacy.purge-expired', { cron: '0 3 * * *', tenancy: 'global' }).handledByFactory((resolve) => ({
16
16
  run: async () => {
17
17
  await runPurge(resolve);
18
18
  },
@@ -9,6 +9,9 @@ import { composeApplication } from '{{alias.platform}}/composition/compose-appli
9
9
  import { loadConfig } from '{{alias.platform}}/config/load-config{{alias.ext}}';
10
10
  {{/if}}
11
11
  import { openPersistence } from '{{alias.platform}}/database/open-persistence{{alias.ext}}';
12
+ {{#if tenancy.any}}
13
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
14
+ {{/if}}
12
15
  import { inProcessEvents } from '{{alias.platform}}/events/in-process-events{{alias.ext}}';
13
16
  import { runErasure } from '{{alias.platform}}/privacy/run-erasure{{alias.ext}}';
14
17
 
@@ -17,11 +20,11 @@ import { runErasure } from '{{alias.platform}}/privacy/run-erasure{{alias.ext}}'
17
20
  {{#if eventSourcing.on}}
18
21
  // The key of the subject is destroyed first, so every personal value of its stored events reads as
19
22
  // erased{{#if audit.on}}, and the erasure leaves a dated entry in the audit trail{{/if}}; then every copy a context declared in
20
- // src/platform/privacy/data-subject-copies.ts is erased{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}.
23
+ // src/platform/privacy/data-subject-copies.ts is erased{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}.
21
24
  {{/if}}
22
25
  {{#unless eventSourcing.on}}
23
26
  // Every copy a context declared in src/platform/privacy/data-subject-copies.ts is erased or
24
- // pseudonymised where it lies{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}: the aggregates of
27
+ // pseudonymised where it lies{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}: the aggregates of
25
28
  // this project are rows, so there is no key to destroy.
26
29
  {{/unless}}
27
30
  // The report says what was reached. Running it again completes an erasure that failed half way.
@@ -39,12 +42,8 @@ if (subject === undefined || positionals.length > 1) {
39
42
  }
40
43
  {{#if tenancy.any}}
41
44
 
42
- const tenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
43
-
44
- if (tenants.length === 0) {
45
- console.error('TENANTS names the tenants the copies are erased in, comma separated: a write of tenant data is never widened.');
46
- process.exit(2);
47
- }
45
+ // The tenants of a project with no source of tenants (comma separated); the identity preset reads its organisations instead.
46
+ const fixedTenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
48
47
  {{/if}}
49
48
 
50
49
  {{#if persistence.needsUrl}}
@@ -61,6 +60,17 @@ const application = composeApplication(persistence, {
61
60
  {{/if}}
62
61
  });
63
62
 
63
+ {{#if tenancy.any}}
64
+ const tenants = await tenantDirectory(persistence, fixedTenants).tenants();
65
+
66
+ if (tenants.length === 0) {
67
+ console.error('The tenant directory lists no tenant: a write of tenant data is never widened. Name them in TENANTS, comma separated, or open an organisation first.');
68
+ await application.stop();
69
+ await persistence.close();
70
+ process.exit(2);
71
+ }
72
+ {{/if}}
73
+
64
74
  try {
65
75
  const report = await runErasure(subject, {
66
76
  platform: application.platform,
@@ -9,6 +9,9 @@ import { composeApplication } from '{{alias.platform}}/composition/compose-appli
9
9
  import { loadConfig } from '{{alias.platform}}/config/load-config{{alias.ext}}';
10
10
  {{/if}}
11
11
  import { openPersistence } from '{{alias.platform}}/database/open-persistence{{alias.ext}}';
12
+ {{#if tenancy.any}}
13
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
14
+ {{/if}}
12
15
  import { inProcessEvents } from '{{alias.platform}}/events/in-process-events{{alias.ext}}';
13
16
  import { runErasure } from '{{alias.platform}}/privacy/run-erasure{{alias.ext}}';
14
17
 
@@ -17,11 +20,11 @@ import { runErasure } from '{{alias.platform}}/privacy/run-erasure{{alias.ext}}'
17
20
  {{#if eventSourcing.on}}
18
21
  // The key of the subject is destroyed first, so every personal value of its stored events reads as
19
22
  // erased{{#if audit.on}}, and the erasure leaves a dated entry in the audit trail{{/if}}; then every copy a context declared in
20
- // src/platform/privacy/data-subject-copies.ts is erased{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}.
23
+ // src/platform/privacy/data-subject-copies.ts is erased{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}.
21
24
  {{/if}}
22
25
  {{#unless eventSourcing.on}}
23
26
  // Every copy a context declared in src/platform/privacy/data-subject-copies.ts is erased or
24
- // pseudonymised where it lies{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}: the aggregates of
27
+ // pseudonymised where it lies{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}: the aggregates of
25
28
  // this project are rows, so there is no key to destroy.
26
29
  {{/unless}}
27
30
  // The report says what was reached. Running it again completes an erasure that failed half way.
@@ -39,12 +42,8 @@ if (subject === undefined || positionals.length > 1) {
39
42
  }
40
43
  {{#if tenancy.any}}
41
44
 
42
- const tenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
43
-
44
- if (tenants.length === 0) {
45
- console.error('TENANTS names the tenants the copies are erased in, comma separated: a write of tenant data is never widened.');
46
- process.exit(2);
47
- }
45
+ // The tenants of a project with no source of tenants (comma separated); the identity preset reads its organisations instead.
46
+ const fixedTenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
48
47
  {{/if}}
49
48
 
50
49
  {{#if persistence.needsUrl}}
@@ -61,6 +60,17 @@ const application = composeApplication(persistence, {
61
60
  {{/if}}
62
61
  });
63
62
 
63
+ {{#if tenancy.any}}
64
+ const tenants = await tenantDirectory(persistence, fixedTenants).tenants();
65
+
66
+ if (tenants.length === 0) {
67
+ console.error('The tenant directory lists no tenant: a write of tenant data is never widened. Name them in TENANTS, comma separated, or open an organisation first.');
68
+ await application.stop();
69
+ await persistence.close();
70
+ process.exit(2);
71
+ }
72
+ {{/if}}
73
+
64
74
  try {
65
75
  const report = await runErasure(subject, {
66
76
  container: application.container,
@@ -9,6 +9,9 @@ import { composeApplication } from '{{alias.platform}}/composition/compose-appli
9
9
  import { loadConfig } from '{{alias.platform}}/config/load-config{{alias.ext}}';
10
10
  {{/if}}
11
11
  import { openPersistence } from '{{alias.platform}}/database/open-persistence{{alias.ext}}';
12
+ {{#if tenancy.any}}
13
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
14
+ {{/if}}
12
15
  import { inProcessEvents } from '{{alias.platform}}/events/in-process-events{{alias.ext}}';
13
16
  import { runExport } from '{{alias.platform}}/privacy/run-export{{alias.ext}}';
14
17
 
@@ -17,7 +20,7 @@ import { runExport } from '{{alias.platform}}/privacy/run-export{{alias.ext}}';
17
20
  // npm run privacy:export -- <subject-id> [--operator <who-asks>] > export.json
18
21
  // One JSON document on the standard output (`format`, `subject`, `exportedAt`, `records`): every
19
22
  // record each context declared in src/platform/privacy/data-subject-exports.ts keeps of the
20
- // person{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}, as plain data. Hand it over to the person, then delete
23
+ // person{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}, as plain data. Hand it over to the person, then delete
21
24
  // the file{{#if audit.on}}; the audit trail keeps the entry of each export, never the values. Every run is a
22
25
  // handover and leaves its entry, a trial included: try it on a test subject, never on a real person{{/if}}.
23
26
  {{#if eventSourcing.on}}
@@ -40,12 +43,8 @@ if (subject === undefined || positionals.length > 1) {
40
43
  }
41
44
  {{#if tenancy.any}}
42
45
 
43
- const tenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
44
-
45
- if (tenants.length === 0) {
46
- console.error('TENANTS names the tenants the records are gathered in, comma separated.');
47
- process.exit(2);
48
- }
46
+ // The tenants of a project with no source of tenants (comma separated); the identity preset reads its organisations instead.
47
+ const fixedTenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
49
48
  {{/if}}
50
49
 
51
50
  {{#if persistence.needsUrl}}
@@ -62,6 +61,17 @@ const application = composeApplication(persistence, {
62
61
  {{/if}}
63
62
  });
64
63
 
64
+ {{#if tenancy.any}}
65
+ const tenants = await tenantDirectory(persistence, fixedTenants).tenants();
66
+
67
+ if (tenants.length === 0) {
68
+ console.error('The tenant directory lists no tenant to gather the records in. Name them in TENANTS, comma separated, or open an organisation first.');
69
+ await application.stop();
70
+ await persistence.close();
71
+ process.exit(2);
72
+ }
73
+ {{/if}}
74
+
65
75
  try {
66
76
  const document = await runExport(subject, {
67
77
  platform: application.platform,
@@ -9,6 +9,9 @@ import { composeApplication } from '{{alias.platform}}/composition/compose-appli
9
9
  import { loadConfig } from '{{alias.platform}}/config/load-config{{alias.ext}}';
10
10
  {{/if}}
11
11
  import { openPersistence } from '{{alias.platform}}/database/open-persistence{{alias.ext}}';
12
+ {{#if tenancy.any}}
13
+ import { tenantDirectory } from '{{alias.platform}}/composition/tenant-directory{{alias.ext}}';
14
+ {{/if}}
12
15
  import { inProcessEvents } from '{{alias.platform}}/events/in-process-events{{alias.ext}}';
13
16
  import { runExport } from '{{alias.platform}}/privacy/run-export{{alias.ext}}';
14
17
 
@@ -17,7 +20,7 @@ import { runExport } from '{{alias.platform}}/privacy/run-export{{alias.ext}}';
17
20
  // npm run privacy:export -- <subject-id> [--operator <who-asks>] > export.json
18
21
  // One JSON document on the standard output (`format`, `subject`, `exportedAt`, `records`): every
19
22
  // record each context declared in src/platform/privacy/data-subject-exports.ts keeps of the
20
- // person{{#if tenancy.any}}, in each tenant of TENANTS (comma separated){{/if}}, as plain data. Hand it over to the person, then delete
23
+ // person{{#if tenancy.any}}, in each tenant the tenant directory lists (TENANTS, or the organisations of the identity context){{/if}}, as plain data. Hand it over to the person, then delete
21
24
  // the file{{#if audit.on}}; the audit trail keeps the entry of each export, never the values. Every run is a
22
25
  // handover and leaves its entry, a trial included: try it on a test subject, never on a real person{{/if}}.
23
26
  {{#if eventSourcing.on}}
@@ -40,12 +43,8 @@ if (subject === undefined || positionals.length > 1) {
40
43
  }
41
44
  {{#if tenancy.any}}
42
45
 
43
- const tenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
44
-
45
- if (tenants.length === 0) {
46
- console.error('TENANTS names the tenants the records are gathered in, comma separated.');
47
- process.exit(2);
48
- }
46
+ // The tenants of a project with no source of tenants (comma separated); the identity preset reads its organisations instead.
47
+ const fixedTenants = (process.env['TENANTS'] ?? '').split(',').map((tenant) => tenant.trim()).filter((tenant) => tenant !== '');
49
48
  {{/if}}
50
49
 
51
50
  {{#if persistence.needsUrl}}
@@ -62,6 +61,17 @@ const application = composeApplication(persistence, {
62
61
  {{/if}}
63
62
  });
64
63
 
64
+ {{#if tenancy.any}}
65
+ const tenants = await tenantDirectory(persistence, fixedTenants).tenants();
66
+
67
+ if (tenants.length === 0) {
68
+ console.error('The tenant directory lists no tenant to gather the records in. Name them in TENANTS, comma separated, or open an organisation first.');
69
+ await application.stop();
70
+ await persistence.close();
71
+ process.exit(2);
72
+ }
73
+ {{/if}}
74
+
65
75
  try {
66
76
  const document = await runExport(subject, {
67
77
  container: application.container,
@@ -47,7 +47,7 @@ describe('{{name.title}}, when its time comes', () => {
47
47
  it.todo('names the period of the occurrence, never the instant it really runs');
48
48
  it.todo('has the same outcome when the same occurrence runs twice');
49
49
  {{#if job.perTenant}}
50
- // TODO(domain): once the handler reads a tenant-scoped repository, run it for both tenants with their own rows and assert each run reads its own tenant only.
50
+ // TODO(domain): once the handler reads a tenant-scoped repository, prove on the test database that each run reads its own tenant only: save a row for each tenant, run the job, and read both through the real repository inside the run (docs/concepts/scheduled-jobs.md, "A run reads its own tenant").
51
51
  it.todo('reads and writes one tenant at a time');
52
52
  {{/if}}
53
53
  });
@@ -256,6 +256,8 @@ jobs:
256
256
  run: |
257
257
  run=$(gh run list --workflow "${{ github.workflow }}" --event schedule --branch "${{ github.event.repository.default_branch }}" --status success --limit 1 --json databaseId --jq '.[0].databaseId')
258
258
  if [ -n "$run" ]; then gh run download "$run" --name mutation --dir reports/mutation || echo "The last night kept no report: a full run."; fi
259
+ # The night runs without a base and writes no incremental file: its json report is the same object, which Stryker reads back.
260
+ if [ -f reports/mutation/mutation.json ]; then cp reports/mutation/mutation.json reports/mutation/incremental.json; fi
259
261
  - name: Stryker on what the change touches, then the survivors of its files
260
262
  run: |
261
263
  mkdir -p reports/mutation
@@ -261,6 +261,8 @@ mutation_changed:
261
261
  GIT_DEPTH: 0
262
262
  script:
263
263
  - 'curl --silent --fail --location --output night.zip --header "JOB-TOKEN: $CI_JOB_TOKEN" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/$CI_DEFAULT_BRANCH/download?job=mutation" && unzip -q -o night.zip && rm night.zip || echo "The last night kept no report: a full run."'
264
+ # The night runs without a base and writes no incremental file: its json report is the same object, which Stryker reads back.
265
+ - if [ -f reports/mutation/mutation.json ]; then cp reports/mutation/mutation.json reports/mutation/incremental.json; fi
264
266
  - git fetch --quiet origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
265
267
  - base=$(git merge-base "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" HEAD)
266
268
  - DDD_TS_KIT_MUTATION_SINCE="$base" npm run test:mutation
@@ -23,7 +23,7 @@
23
23
  "@biomejs/biome": "2.6.2",
24
24
  "@commitlint/cli": "^21.2.3",
25
25
  "@commitlint/config-conventional": "^21.2.3",
26
- "@ddd-ts-kit/eslint-plugin": "^0.93.0",
26
+ "@ddd-ts-kit/eslint-plugin": "^0.94.1",
27
27
  "@eslint/js": "^10.0.1",
28
28
  "@typescript/native": "npm:typescript@~7.0.2",
29
29
  "@vitest/coverage-v8": "5.0.3",
@@ -0,0 +1,26 @@
1
+ import type { TenantDirectory } from '@ddd-ts-kit/kernel';
2
+ import type { Database } from '{{alias.platform}}/database/database{{alias.ext}}';
3
+ import { organisations } from '{{alias.context}}/infrastructure/persistence/{{context.kebab}}.schema{{alias.ext}}';
4
+
5
+ /**
6
+ * The tenants are the organisations of the application, read from the database each time a job
7
+ * declared `per-tenant` has its occurrence: an organisation opened after the boot gets its run
8
+ * at the next one, where a fixed list (`TENANTS`) would miss it.
9
+ */
10
+ export class DrizzleOrganisationTenantDirectory implements TenantDirectory {
11
+ constructor(private readonly database: Database) {}
12
+
13
+ async tenants(): Promise<readonly string[]> {
14
+ const rows = await executorOf(this.database).select({ id: organisations.id }).from(organisations).orderBy(organisations.id);
15
+
16
+ return rows.map((row) => row.id);
17
+ }
18
+ }
19
+
20
+ /** The executor of the unit of work, which every statement of this file goes through. */
21
+ function executorOf(database: Database): ReturnType<Database['executor']> {
22
+ {{#if tenancy.any}}
23
+ // ddd-ts-kit-disable-next-line tenancy/scoped-statement -- {{preset.adr}}: the {{context.kebab}} context is the control plane of the tenants, and its rows belong to none of them.
24
+ {{/if}}
25
+ return database.executor();
26
+ }
@@ -0,0 +1,30 @@
1
+ import type { Knex } from 'knex';
2
+ import type { TenantDirectory } from '@ddd-ts-kit/kernel';
3
+ import type { KnexContext } from '@ddd-ts-kit/knex';
4
+ import { {{context.constant}}_SCHEMA } from '{{alias.context}}/infrastructure/persistence/{{context.kebab}}.schema{{alias.ext}}';
5
+ import type { OrganisationRow } from '{{alias.context}}/infrastructure/persistence/organisation-row.schema{{alias.ext}}';
6
+
7
+ /**
8
+ * The tenants are the organisations of the application, read from the database each time a job
9
+ * declared `per-tenant` has its occurrence: an organisation opened after the boot gets its run
10
+ * at the next one, where a fixed list (`TENANTS`) would miss it.
11
+ */
12
+ export class KnexOrganisationTenantDirectory implements TenantDirectory {
13
+ constructor(private readonly database: KnexContext) {}
14
+
15
+ async tenants(): Promise<readonly string[]> {
16
+ const rows = await tableOf(this.database).select('id').orderBy('id');
17
+
18
+ return rows.map((row) => row.id);
19
+ }
20
+ }
21
+
22
+ /** A function and not a method: a query builder is thenable, and a method that answers one is read as asynchronous by whatever wraps the adapter (tracing), which then answers a promise. */
23
+ function tableOf(database: KnexContext): Knex.QueryBuilder<OrganisationRow, OrganisationRow[]> {
24
+ {{#if tenancy.any}}
25
+ // ddd-ts-kit-disable-next-line tenancy/scoped-statement -- {{preset.adr}}: the {{context.kebab}} context is the control plane of the tenants, and its rows belong to none of them.
26
+ {{/if}}
27
+ const table = database.executor()<OrganisationRow, OrganisationRow[]>('organisations');
28
+
29
+ return table.withSchema({{context.constant}}_SCHEMA);
30
+ }
@@ -0,0 +1,25 @@
1
+ import type { TenantDirectory } from '@ddd-ts-kit/kernel';
2
+ import type { Database } from '{{alias.platform}}/database/database{{alias.ext}}';
3
+
4
+ /**
5
+ * The tenants are the organisations of the application, read from the database each time a job
6
+ * declared `per-tenant` has its occurrence: an organisation opened after the boot gets its run
7
+ * at the next one, where a fixed list (`TENANTS`) would miss it.
8
+ */
9
+ export class PrismaOrganisationTenantDirectory implements TenantDirectory {
10
+ constructor(private readonly database: Database) {}
11
+
12
+ async tenants(): Promise<readonly string[]> {
13
+ const rows = await organisationsOf(this.database).findMany({ select: { id: true }, orderBy: { id: 'asc' } });
14
+
15
+ return rows.map((row) => row.id);
16
+ }
17
+ }
18
+
19
+ /** The organisations on the client of the unit of work, which every statement of this file goes through. */
20
+ function organisationsOf(database: Database): ReturnType<Database['client']>['{{context.camel}}Organisation'] {
21
+ {{#if tenancy.any}}
22
+ // ddd-ts-kit-disable-next-line tenancy/scoped-statement -- {{preset.adr}}: the {{context.kebab}} context is the control plane of the tenants, and its rows belong to none of them.
23
+ {{/if}}
24
+ return database.client().{{context.camel}}Organisation;
25
+ }
@@ -0,0 +1,107 @@
1
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from '{{tests.module}}';
2
+ {{#if di.tsyringe}}
3
+ import { contextModule, createApplication, kernelModule } from '@ddd-ts-kit/di';
4
+ {{/if}}
5
+ {{#if di.tsyringe}}
6
+ import {
7
+ FixedClock,
8
+ FixedExecutionScope,
9
+ executionContext,
10
+ JobScheduler,
11
+ type Actor,
12
+ type JobExecution,
13
+ type ScheduledJob,
14
+ } from '@ddd-ts-kit/kernel';
15
+ {{/if}}
16
+ {{#unless di.tsyringe}}
17
+ import { FixedClock, FixedExecutionScope, executionContext, type Actor } from '@ddd-ts-kit/kernel';
18
+ {{/unless}}
19
+ {{#if di.tsyringe}}
20
+ import { Scheduled } from '@ddd-ts-kit/kernel/declarations';
21
+ {{/if}}
22
+ import { {{preset.adapter.pascal}}OrganisationRepository } from '{{alias.context}}/infrastructure/persistence/{{preset.adapter.kebab}}-organisation.repository{{alias.ext}}';
23
+ import { {{preset.adapter.pascal}}OrganisationTenantDirectory } from '{{alias.context}}/infrastructure/persistence/{{preset.adapter.kebab}}-organisation-tenant-directory.reader{{alias.ext}}';
24
+ import { openTestDatabase, type TestDatabase } from '{{alias.platform}}/database/open-test-database{{alias.ext}}';
25
+ import { anOrganisation } from '{{alias.context}}/test/builders/organisation.builder{{alias.ext}}';
26
+
27
+ const clock = new FixedClock(new Date('2026-01-01T00:00:00.000Z'));
28
+ const actor: Actor = { id: 'subject-ada', type: 'user', roles: [], attributes: {} };
29
+ const scope = new FixedExecutionScope(executionContext({ correlationId: 'tenant-directory-spec', actor, origin: 'test' }));
30
+
31
+ let database: TestDatabase;
32
+
33
+ beforeAll(async () => {
34
+ database = await openTestDatabase();
35
+ });
36
+
37
+ beforeEach(async () => {
38
+ await database.reset();
39
+ });
40
+
41
+ afterAll(async () => {
42
+ await database.close();
43
+ });
44
+
45
+ describe('{{preset.adapter.pascal}}OrganisationTenantDirectory', () => {
46
+ it('lists no tenant while no organisation was opened', async () => {
47
+ const { directory } = arrange();
48
+
49
+ expect(await directory.tenants()).toEqual([]);
50
+ });
51
+
52
+ it('lists the organisations of the application as its tenants, by their id', async () => {
53
+ const { organisations, directory } = arrange();
54
+
55
+ await organisations.save(anOrganisation().identifiedBy('globex').build());
56
+ await organisations.save(anOrganisation().identifiedBy('acme').build());
57
+
58
+ expect(await directory.tenants()).toEqual(['acme', 'globex']);
59
+ });
60
+
61
+ it('lists an organisation opened after the first read, on the same directory', async () => {
62
+ const { organisations, directory } = arrange();
63
+
64
+ await organisations.save(anOrganisation().identifiedBy('acme').build());
65
+ expect(await directory.tenants()).toEqual(['acme']);
66
+
67
+ await organisations.save(anOrganisation().identifiedBy('globex').build());
68
+ expect(await directory.tenants()).toEqual(['acme', 'globex']);
69
+ });
70
+ {{#if di.tsyringe}}
71
+
72
+ it('gives an organisation opened after the boot its run of a per-tenant job', async () => {
73
+ const { organisations, directory } = arrange();
74
+ const ran: (string | undefined)[] = [];
75
+
76
+ class CloseTheDay implements ScheduledJob {
77
+ async run(execution: JobExecution): Promise<void> {
78
+ ran.push(execution.tenantId);
79
+ }
80
+ }
81
+
82
+ Scheduled('tenant-directory-spec.close-the-day', { every: '1d', tenancy: 'per-tenant' }, [])(CloseTheDay);
83
+
84
+ await organisations.save(anOrganisation().identifiedBy('acme').build());
85
+
86
+ const application = createApplication({
87
+ modules: [kernelModule({ tenants: directory }), contextModule('tenant-directory-spec', [CloseTheDay])],
88
+ });
89
+
90
+ await application.resolve(JobScheduler).runNow('tenant-directory-spec.close-the-day');
91
+ expect(ran).toEqual(['acme']);
92
+
93
+ await organisations.save(anOrganisation().identifiedBy('globex').build());
94
+ ran.length = 0;
95
+
96
+ await application.resolve(JobScheduler).runNow('tenant-directory-spec.close-the-day');
97
+ expect(ran).toEqual(['acme', 'globex']);
98
+ });
99
+ {{/if}}
100
+ });
101
+
102
+ function arrange() {
103
+ const organisations = new {{preset.adapter.pascal}}OrganisationRepository(database.persistence.database, scope, clock);
104
+ const directory = new {{preset.adapter.pascal}}OrganisationTenantDirectory(database.persistence.database);
105
+
106
+ return { organisations, directory };
107
+ }
@@ -0,0 +1,13 @@
1
+ import type { TenantDirectory } from '@ddd-ts-kit/kernel';
2
+ import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
3
+ import { {{preset.adapter.pascal}}OrganisationTenantDirectory } from '{{alias.context}}/infrastructure/persistence/{{preset.adapter.kebab}}-organisation-tenant-directory.reader{{alias.ext}}';
4
+
5
+ /**
6
+ * The tenants a job declared `per-tenant` runs for, asked again at each occurrence: the
7
+ * organisations of the {{context.kebab}} context, read from the database. An organisation opened
8
+ * after the process started gets its run at the next occurrence, with no restart. `TENANTS` is
9
+ * not read here: it is the list of a project with no source of tenants.
10
+ */
11
+ export function tenantDirectory(persistence: Persistence, _fixed: readonly string[] = []): TenantDirectory {
12
+ return new {{preset.adapter.pascal}}OrganisationTenantDirectory(persistence.database);
13
+ }
@@ -9,5 +9,8 @@ import type { {{name.pascal}}Result } from '{{alias.context}}/application/querie
9
9
  @{{access.decoration}}
10
10
  {{/if}}
11
11
  export class {{name.pascal}}Query extends {{access.queryBase}}<{{name.pascal}}Result> {
12
+ {{#if access.resourceUnnamed}}
13
+ // {{access.resourceTodo}}
14
+ {{/if}}
12
15
  // TODO(domain): declare the criteria of "{{name.words}}" as a constructor with readonly primitives (filters, page), for example `{{access.constructorSample}}`.
13
16
  }