@cratis/chronicle 6.70.1 → 6.71.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 (50) hide show
  1. package/dist/projections/IProjections.d.ts +27 -1
  2. package/dist/projections/IProjections.d.ts.map +1 -1
  3. package/dist/projections/ProjectionDefinitionCompiler.d.ts +11 -0
  4. package/dist/projections/ProjectionDefinitionCompiler.d.ts.map +1 -1
  5. package/dist/projections/ProjectionDefinitionCompiler.js +42 -18
  6. package/dist/projections/ProjectionDefinitionCompiler.js.map +1 -1
  7. package/dist/projections/Projections.d.ts +9 -0
  8. package/dist/projections/Projections.d.ts.map +1 -1
  9. package/dist/projections/Projections.js +62 -11
  10. package/dist/projections/Projections.js.map +1 -1
  11. package/dist/projections/RuntimeProjectionDefinitions.d.ts +26 -0
  12. package/dist/projections/RuntimeProjectionDefinitions.d.ts.map +1 -0
  13. package/dist/projections/RuntimeProjectionDefinitions.js +55 -0
  14. package/dist/projections/RuntimeProjectionDefinitions.js.map +1 -0
  15. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.d.ts +42 -0
  16. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.d.ts.map +1 -0
  17. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.js +115 -0
  18. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.js.map +1 -0
  19. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.d.ts +20 -0
  20. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.d.ts.map +1 -0
  21. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.js +20 -0
  22. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.js.map +1 -0
  23. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts +15 -0
  24. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts.map +1 -0
  25. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js +62 -0
  26. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js.map +1 -0
  27. package/dist/testing/projections/ProjectionRootCapabilities.d.ts.map +1 -1
  28. package/dist/testing/projections/ProjectionRootCapabilities.js +6 -1
  29. package/dist/testing/projections/ProjectionRootCapabilities.js.map +1 -1
  30. package/dist/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +2 -2
  32. package/projections/IProjections.ts +30 -1
  33. package/projections/ProjectionDefinitionCompiler.ts +46 -17
  34. package/projections/Projections.ts +72 -12
  35. package/projections/RuntimeProjectionDefinitions.ts +68 -0
  36. package/projections/for_Projections/given/default_runtime_registration.fixture.ts +53 -0
  37. package/projections/for_Projections/given/runtime_registration.fixture.ts +51 -0
  38. package/projections/for_Projections/when_mixing_runtime_registration_styles.spec.ts +73 -0
  39. package/projections/for_Projections/when_reconnecting_with_runtime_projections.spec.ts +36 -0
  40. package/projections/for_Projections/when_registering_at_runtime.spec.ts +72 -0
  41. package/projections/for_Projections/when_registering_with_the_default_provider.spec.ts +116 -0
  42. package/projections/for_Projections/when_runtime_registration_fails.spec.ts +106 -0
  43. package/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.ts +55 -0
  44. package/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.ts +24 -0
  45. package/testing/for_ReadModelScenario/when_counting_with_children/with_a_fluent_projection.spec.ts +94 -0
  46. package/testing/for_ReadModelScenario/when_counting_with_children/with_legacy_decorators.legacy.spec.ts +39 -0
  47. package/testing/for_ReadModelScenario/when_counting_with_children/with_standard_decorators.standard.spec.ts +40 -0
  48. package/testing/projections/ProjectionCountChildrenCapabilities.ts +71 -0
  49. package/testing/projections/ProjectionRootCapabilities.ts +4 -1
  50. package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +87 -0
@@ -29,6 +29,9 @@ import { registerProjectionWithRetry } from './registerProjectionWithRetry.js';
29
29
  import type { ProjectionRegistrationOutcome } from '../ArtifactRegistrationResult.js';
30
30
  import type { ResolvedModelBoundMetadata } from './ResolvedModelBoundMetadata.js';
31
31
  import { UnableToQueryProjection } from './UnableToQueryProjection.js';
32
+ import type { IProjectionBuilderFor } from './declarative/IProjectionBuilderFor.js';
33
+ import type { CompiledProjectionDefinitions } from './CompiledProjectionDefinitions.js';
34
+ import { RuntimeProjectionDefinitions } from './RuntimeProjectionDefinitions.js';
32
35
 
33
36
  /**
34
37
  * Implements {@link IProjections}, managing discovery and registration of projections
@@ -38,6 +41,7 @@ export class Projections implements IProjections {
38
41
  private readonly _declarative = new Map<string, Constructor>();
39
42
  private readonly _modelBound = new Map<string, Constructor>();
40
43
  private readonly _failedPartitions: FailedPartitions;
44
+ private readonly _runtime = new RuntimeProjectionDefinitions();
41
45
 
42
46
  private readonly _logger: ReturnType<typeof createLogger>;
43
47
 
@@ -75,6 +79,7 @@ export class Projections implements IProjections {
75
79
  const metadata = getProjectionMetadata(type);
76
80
  if (metadata) {
77
81
  this._logger.debug('Discovered declarative projection', { projectionId: metadata.id.value, type: type.name });
82
+ this._runtime.assertAvailable(metadata.id.value);
78
83
  this._declarative.set(metadata.id.value, type);
79
84
  }
80
85
  }
@@ -90,6 +95,10 @@ export class Projections implements IProjections {
90
95
  continue;
91
96
  }
92
97
 
98
+ if (this._runtime.findForModel(type) === metadata.id.value) {
99
+ continue;
100
+ }
101
+ this._runtime.assertAvailable(metadata.id.value);
93
102
  this._logger.debug('Discovered model-bound projection', { projectionId: metadata.id.value, type: type.name });
94
103
  if (!this._modelBound.has(metadata.id.value)) {
95
104
  this._modelBound.set(metadata.id.value, type);
@@ -113,6 +122,59 @@ export class Projections implements IProjections {
113
122
  assertUniqueReadModelIds([...rootReadModelTypes(this._clientArtifacts), ...inferred]);
114
123
  const compiled = new ProjectionDefinitionCompiler(this._clientArtifacts, this._defaultSinkTypeId, this._readModelNamingPolicy)
115
124
  .compile(this._declarative.values(), this._modelBound.values());
125
+ const retained = this._runtime.registrations;
126
+ await this.registerDefinitions({
127
+ ...compiled,
128
+ definitions: [...compiled.definitions, ...retained.flatMap(entry => entry.definitions)],
129
+ readModels: [...compiled.readModels, ...retained.flatMap(entry => entry.readModels)]
130
+ }, record);
131
+ }
132
+
133
+ /** @inheritdoc */
134
+ registerFor<TReadModel>(readModelType: Constructor<TReadModel>, define: (builder: IProjectionBuilderFor<TReadModel>) => void,
135
+ id?: ProjectionId | string): Promise<void> {
136
+ return this.registerRuntime(readModelType, define, id);
137
+ }
138
+
139
+ /** @inheritdoc */
140
+ registerModelBound(readModelType: Constructor): Promise<void> {
141
+ return this.registerRuntime(readModelType);
142
+ }
143
+
144
+ private async registerRuntime<TReadModel>(readModelType: Constructor<TReadModel>, define?: (builder: IProjectionBuilderFor<TReadModel>) => void,
145
+ id?: ProjectionId | string): Promise<void> {
146
+ await this.discover();
147
+ const identifier = id === undefined ? getReadModelId(readModelType) : this.toProjectionIdValue(id);
148
+ if (!define && this._runtime.hasModelBoundFor(readModelType, identifier)) {
149
+ return;
150
+ }
151
+ const discoveredModelBound = !define && !this._declarative.has(identifier) && this._modelBound.get(identifier) === readModelType;
152
+ this.assertRuntimeRegistrationAvailable(readModelType, identifier, discoveredModelBound);
153
+ const inferred = this._clientArtifacts.projections
154
+ .map(type => getProjectionMetadata(type)?.readModelType)
155
+ .filter((type): type is Constructor => type !== undefined);
156
+ assertUniqueReadModelIds([...rootReadModelTypes(this._clientArtifacts), ...inferred, ...this._runtime.readModelTypes, readModelType]);
157
+ const compiled = new ProjectionDefinitionCompiler(this._clientArtifacts, this._defaultSinkTypeId, this._readModelNamingPolicy)
158
+ .compileFor(readModelType, define, identifier);
159
+ await this._runtime.register(readModelType, compiled, define ? 'fluent' : 'modelBound', definition => this.registerDefinitions(definition));
160
+ if (discoveredModelBound) {
161
+ this._modelBound.delete(identifier);
162
+ }
163
+ }
164
+
165
+ private assertRuntimeRegistrationAvailable(readModelType: Constructor, identifier: string, discoveredModelBound: boolean): void {
166
+ const discovered = this._declarative.has(identifier) || this._modelBound.has(identifier);
167
+ if (!discoveredModelBound && discovered) {
168
+ throw new Error(`Projection id '${identifier}' is already discovered.`);
169
+ }
170
+ this._runtime.assertAvailable(identifier);
171
+ if (!discoveredModelBound && this.hasForModel(readModelType)) {
172
+ throw new Error(`Read model '${readModelType.name}' already has a projection.`);
173
+ }
174
+ }
175
+
176
+ private async registerDefinitions(compiled: CompiledProjectionDefinitions,
177
+ record: (outcome: ProjectionRegistrationOutcome) => void = () => {}): Promise<void> {
116
178
  const projections = compiled.definitions;
117
179
  for (const projection of projections) {
118
180
  ensureChildrenOrderingIsSupported(projection);
@@ -146,7 +208,7 @@ export class Projections implements IProjections {
146
208
  /** @inheritdoc */
147
209
  hasFor(projectionId: ProjectionId | string): boolean {
148
210
  const id = this.toProjectionIdValue(projectionId);
149
- return this._declarative.has(id) || this._modelBound.has(id);
211
+ return this._declarative.has(id) || this._modelBound.has(id) || this._runtime.has(id);
150
212
  }
151
213
 
152
214
  /** @inheritdoc */
@@ -247,17 +309,11 @@ export class Projections implements IProjections {
247
309
  * @returns The resolved {@link ProjectionId}.
248
310
  */
249
311
  private resolveProjectionIdForModel(readModelType: Constructor): ProjectionId {
250
- for (const [id, type] of this._modelBound) {
251
- if (type === readModelType) {
252
- return new ProjectionId(id);
253
- }
254
- }
255
-
256
- for (const [id, type] of this._declarative) {
257
- const metadata = getProjectionMetadata(type);
258
- if (metadata?.readModelType === readModelType) {
259
- return new ProjectionId(id);
260
- }
312
+ const id = this._runtime.findForModel(readModelType)
313
+ ?? Array.from(this._modelBound).find(([, type]) => type === readModelType)?.[0]
314
+ ?? Array.from(this._declarative).find(([, type]) => getProjectionMetadata(type)?.readModelType === readModelType)?.[0];
315
+ if (id !== undefined) {
316
+ return new ProjectionId(id);
261
317
  }
262
318
 
263
319
  throw new Error(
@@ -272,6 +328,10 @@ export class Projections implements IProjections {
272
328
  * @returns The resolved event sequence identifier.
273
329
  */
274
330
  private resolveEventSequenceIdFor(projectionId: string): string {
331
+ const runtimeEventSequenceId = this._runtime.eventSequenceIdFor(projectionId);
332
+ if (runtimeEventSequenceId !== undefined) {
333
+ return runtimeEventSequenceId;
334
+ }
275
335
  const modelBoundType = this._modelBound.get(projectionId);
276
336
  if (modelBoundType) {
277
337
  return getEventSequenceMetadata(modelBoundType) ?? EventSequenceId.eventLog.value;
@@ -0,0 +1,68 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { Constructor } from '@cratis/fundamentals';
5
+ import type { CompiledProjectionDefinitions } from './CompiledProjectionDefinitions.js';
6
+
7
+ type RuntimeProjectionKind = 'modelBound' | 'fluent';
8
+
9
+ /** Keeps acknowledged runtime definitions independent of artifact discovery. */
10
+ export class RuntimeProjectionDefinitions {
11
+ private readonly _registered = new Map<string, { readModelType: Constructor; compiled: CompiledProjectionDefinitions; kind: RuntimeProjectionKind }>();
12
+ private readonly _pending = new Map<string, Constructor>();
13
+
14
+ /** Gets the retained contracts to send again after reconnecting. */
15
+ get registrations(): CompiledProjectionDefinitions[] {
16
+ return Array.from(this._registered.values(), entry => entry.compiled);
17
+ }
18
+
19
+ /** Gets read models with retained or in-flight runtime registrations. */
20
+ get readModelTypes(): Constructor[] {
21
+ return [...Array.from(this._registered.values(), entry => entry.readModelType), ...this._pending.values()];
22
+ }
23
+
24
+ /** Checks acknowledged definitions by identifier. */
25
+ has(identifier: string): boolean {
26
+ return this._registered.has(identifier);
27
+ }
28
+
29
+ /** Checks acknowledged model-bound registrations by constructor and identifier. */
30
+ hasModelBoundFor(readModelType: Constructor, identifier: string): boolean {
31
+ const registration = this._registered.get(identifier);
32
+ return registration?.readModelType === readModelType && registration.kind === 'modelBound';
33
+ }
34
+
35
+ /** Refuses discovery or registration that would overwrite a runtime definition. */
36
+ assertAvailable(identifier: string): void {
37
+ if (this._registered.has(identifier) || this._pending.has(identifier)) {
38
+ throw new Error(`Projection id '${identifier}' is already registered at runtime.`);
39
+ }
40
+ }
41
+
42
+ /** Finds the acknowledged projection maintaining a read model. */
43
+ findForModel(readModelType: Constructor): string | undefined {
44
+ return Array.from(this._registered).find(([, entry]) => entry.readModelType === readModelType)?.[0];
45
+ }
46
+
47
+ /** Gets the event sequence used by an acknowledged runtime projection. */
48
+ eventSequenceIdFor(identifier: string): string | undefined {
49
+ return this._registered.get(identifier)?.compiled.definitions[0].EventSequenceId;
50
+ }
51
+
52
+ /** Reserves the identity until the kernel acknowledges it, retaining nothing on failure. */
53
+ async register(readModelType: Constructor, compiled: CompiledProjectionDefinitions, kind: RuntimeProjectionKind,
54
+ send: (compiled: CompiledProjectionDefinitions) => Promise<void>): Promise<void> {
55
+ const identifier = compiled.definitions[0].Identifier;
56
+ this.assertAvailable(identifier);
57
+ if (this.readModelTypes.includes(readModelType)) {
58
+ throw new Error(`Read model '${readModelType.name}' already has a runtime projection.`);
59
+ }
60
+ this._pending.set(identifier, readModelType);
61
+ try {
62
+ await send(compiled);
63
+ this._registered.set(identifier, { readModelType, compiled, kind });
64
+ } finally {
65
+ this._pending.delete(identifier);
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,53 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field } from '@cratis/fundamentals';
5
+ import { vi } from 'vitest';
6
+ import { DefaultClientArtifactsProvider } from '../../../artifacts/DefaultClientArtifactsProvider.js';
7
+ import { ChronicleClient } from '../../../ChronicleClient.js';
8
+ import { ChronicleOptions } from '../../../ChronicleOptions.js';
9
+ import type { ChronicleConnection } from '../../../connection/ChronicleConnection.js';
10
+ import { EventStore } from '../../../EventStore.js';
11
+ import { EventStoreName } from '../../../EventStoreName.js';
12
+ import { EventStoreNamespaceName } from '../../../EventStoreNamespaceName.js';
13
+ import { eventType } from '../../../events/eventTypeDecorator.js';
14
+ import type { IProjectionBuilderFor } from '../../declarative/IProjectionBuilderFor.js';
15
+ import { setFrom } from '../../modelBound/setFrom.js';
16
+
17
+ /** Fresh, unconstructed standard-decorated models and a real provider on a cached event store. */
18
+ export function default_runtime_registration() {
19
+ @eventType('default-runtime-added')
20
+ class Added {
21
+ @field(String) name = '';
22
+ }
23
+
24
+ class PropertyModel {
25
+ static readonly readModelId = 'property-runtime';
26
+ @setFrom(Added)
27
+ @field(String) name = '';
28
+ }
29
+
30
+ const artifacts = DefaultClientArtifactsProvider.default;
31
+ const registerProjection = vi.fn().mockResolvedValue({});
32
+ const register = vi.fn().mockResolvedValue({});
33
+ const connection = new Proxy({}, {
34
+ get: (_target, service) => {
35
+ if (service === 'logger') return undefined;
36
+ if (service === 'projections') return { register: registerProjection };
37
+ return new Proxy({}, { get: () => register });
38
+ }
39
+ }) as ChronicleConnection;
40
+ const client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [] }));
41
+ const store = new EventStore(new EventStoreName('store'), EventStoreNamespaceName.default, connection, client['_lifecycle'], 'sink', artifacts);
42
+ client['_stores'].set('store', store);
43
+
44
+ const define = (builder: IProjectionBuilderFor<PropertyModel>): void => {
45
+ builder.from(Added, from => from.set(model => model.name).to(event => event.name));
46
+ };
47
+ const reconnect = (): Promise<void> => client['_lifecycle'].connected(error => { throw error; });
48
+ const dispose = (): void => {
49
+ store.disposeObservations();
50
+ client.dispose();
51
+ };
52
+ return { artifacts, Added, PropertyModel, store, registerProjection, define, reconnect, dispose };
53
+ }
@@ -0,0 +1,51 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field, type Constructor } from '@cratis/fundamentals';
5
+ import { vi } from 'vitest';
6
+ import type { IClientArtifactsProvider } from '../../../artifacts/IClientArtifactsProvider.js';
7
+ import type { ChronicleConnection } from '../../../connection/ChronicleConnection.js';
8
+ import { eventType } from '../../../events/eventTypeDecorator.js';
9
+ import { Projections } from '../../Projections.js';
10
+ import type { IProjectionBuilderFor } from '../../declarative/IProjectionBuilderFor.js';
11
+ import { fromEvent } from '../../modelBound/fromEvent.js';
12
+ import { setFrom } from '../../modelBound/setFrom.js';
13
+
14
+ @eventType('runtime-added')
15
+ export class Added {
16
+ @field(String) name = '';
17
+ }
18
+
19
+ export class RuntimeModel {
20
+ static readonly readModelId = 'runtime-model';
21
+ @field(String) name = '';
22
+ }
23
+
24
+ @fromEvent(Added)
25
+ export class BoundModel {
26
+ @setFrom(Added)
27
+ @field(String) name = '';
28
+ }
29
+
30
+ export function defineRuntime(builder: IProjectionBuilderFor<RuntimeModel>): void {
31
+ builder.from(Added, from => from.set(model => model.name).to(event => event.name));
32
+ }
33
+
34
+ export function runtime_registration() {
35
+ const artifacts: IClientArtifactsProvider & { projections: Constructor[]; readModels: Constructor[] } = {
36
+ eventTypes: [Added], eventSourceTypes: [], projections: [], readModels: [], constraints: [], reactors: [], reducers: []
37
+ };
38
+ const registerProjection = vi.fn().mockResolvedValue({});
39
+ const registerReadModel = vi.fn().mockResolvedValue({});
40
+ const getState = vi.fn().mockResolvedValue({
41
+ RunningState: 0, IsSubscribed: true, NextEventSequenceNumber: 0n, LastHandledEventSequenceNumber: 0n, TailEventSequenceNumber: 0n
42
+ });
43
+ const connection = {
44
+ connectionId: 'connection',
45
+ projections: { register: registerProjection },
46
+ readModels: { registerMany: registerReadModel },
47
+ observers: { getObserverInformation: getState }
48
+ } as unknown as ChronicleConnection;
49
+ const projections = new Projections('store', 'tenant', connection, artifacts, 'sink');
50
+ return { artifacts, connection, projections, registerProjection, registerReadModel, getState };
51
+ }
@@ -0,0 +1,73 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+ import { TypeDiscoverer } from '../../types/TypeDiscoverer.js';
6
+ import { default_runtime_registration } from './given/default_runtime_registration.fixture.js';
7
+ import { defineRuntime, RuntimeModel, runtime_registration } from './given/runtime_registration.fixture.js';
8
+
9
+ let context: ReturnType<typeof default_runtime_registration>;
10
+ beforeEach(() => {
11
+ TypeDiscoverer.default.clear();
12
+ context = default_runtime_registration();
13
+ });
14
+ afterEach(() => {
15
+ context.dispose();
16
+ TypeDiscoverer.default.clear();
17
+ });
18
+
19
+ describe('when calling model-bound registration after fluent registration', () => {
20
+ it('should reject a plain model rather than accepting it as an already-registered model-bound projection', async () => {
21
+ const plain = runtime_registration();
22
+ await plain.projections.registerFor(RuntimeModel, defineRuntime);
23
+ const original = plain.registerProjection.mock.calls[0][0];
24
+
25
+ await expect(plain.projections.registerModelBound(RuntimeModel)).rejects.toThrow("Projection id 'runtime-model' is already registered at runtime");
26
+
27
+ expect(plain.registerProjection).toHaveBeenCalledTimes(1);
28
+ expect(plain.registerReadModel).toHaveBeenCalledTimes(1);
29
+ await plain.projections.register();
30
+ expect(plain.registerProjection.mock.calls.map(call => call[0])).toEqual([original, original]);
31
+ });
32
+
33
+ it('should also reject a decorated model and retain its original fluent definition on reconnect', async () => {
34
+ const { PropertyModel, store, registerProjection } = context;
35
+ await store.projections.registerFor(PropertyModel, context.define);
36
+ const original = registerProjection.mock.calls[0][0];
37
+
38
+ await expect(store.projections.registerModelBound(PropertyModel)).rejects.toThrow("Projection id 'property-runtime' is already registered at runtime");
39
+
40
+ expect(registerProjection).toHaveBeenCalledTimes(1);
41
+ await context.reconnect();
42
+ expect(registerProjection.mock.calls.map(call => call[0])).toEqual([original, original]);
43
+ });
44
+ });
45
+
46
+ describe('when calling model-bound registration twice', () => {
47
+ it('should be a no-op only after the matching model-bound definition has been acknowledged', async () => {
48
+ const { PropertyModel, store, registerProjection } = context;
49
+ await store.projections.registerModelBound(PropertyModel);
50
+ const original = registerProjection.mock.calls[0][0];
51
+
52
+ await store.projections.registerModelBound(PropertyModel);
53
+
54
+ expect(registerProjection).toHaveBeenCalledTimes(1);
55
+ expect(store.projections.getProjectionIdFor(PropertyModel).value).toBe('property-runtime');
56
+ await context.reconnect();
57
+ expect(registerProjection.mock.calls.map(call => call[0])).toEqual([original, original]);
58
+ });
59
+ });
60
+
61
+ describe('when calling fluent registration after model-bound registration', () => {
62
+ it('should reject the same constructor and identifier as a collision without replacing the model-bound definition', async () => {
63
+ const { PropertyModel, store, registerProjection } = context;
64
+ await store.projections.registerModelBound(PropertyModel);
65
+ const original = registerProjection.mock.calls[0][0];
66
+
67
+ await expect(store.projections.registerFor(PropertyModel, context.define)).rejects.toThrow("Projection id 'property-runtime' is already registered at runtime");
68
+
69
+ expect(registerProjection).toHaveBeenCalledTimes(1);
70
+ await context.reconnect();
71
+ expect(registerProjection.mock.calls.map(call => call[0])).toEqual([original, original]);
72
+ });
73
+ });
@@ -0,0 +1,36 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import { ChronicleClient } from '../../ChronicleClient.js';
6
+ import { ChronicleOptions } from '../../ChronicleOptions.js';
7
+ import { an_event_store } from '../../for_EventStore/when_inspecting_registration/given/an_event_store.js';
8
+ import { BoundModel, defineRuntime, RuntimeModel } from './given/runtime_registration.fixture.js';
9
+
10
+ let client: ChronicleClient | undefined;
11
+ let context: ReturnType<typeof an_event_store> | undefined;
12
+ afterEach(() => {
13
+ context?.store.disposeObservations();
14
+ client?.dispose();
15
+ });
16
+
17
+ describe('when a cached store reconnects with runtime projections', () => {
18
+ it('should rediscover artifacts and re-register both retained authoring forms', async () => {
19
+ context = an_event_store();
20
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [] }));
21
+ client['_stores'].set('store', context.store);
22
+ await context.store.projections.registerFor(RuntimeModel, defineRuntime);
23
+ await context.store.projections.registerModelBound(BoundModel);
24
+ const explicitRequests = context.registerProjection.mock.calls.map(call => call[0]);
25
+ context.registerProjection.mockClear();
26
+
27
+ // This is the callback used after the connection is re-established; it registers cached stores.
28
+ await client['_lifecycle'].connected(error => { throw error; });
29
+
30
+ expect(context.registerProjection).toHaveBeenCalledTimes(5);
31
+ for (const request of explicitRequests) expect(context.registerProjection).toHaveBeenCalledWith(request);
32
+ expect(context.store.projections.getProjectionIdFor(RuntimeModel).value).toBe('runtime-model');
33
+ expect(context.store.projections.getProjectionIdFor(BoundModel).value).toBe('BoundModel');
34
+ expect(context.store.registrationResult.state).toBe('successful');
35
+ });
36
+ });
@@ -0,0 +1,72 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { beforeEach, describe, expect, it } from 'vitest';
5
+ import { WellKnownSinks } from '../../sinks/WellKnownSinks.js';
6
+ import { BoundModel, defineRuntime, RuntimeModel, runtime_registration } from './given/runtime_registration.fixture.js';
7
+
8
+ describe('when registering a fluent projection explicitly at runtime', () => {
9
+ let context: ReturnType<typeof runtime_registration>;
10
+ beforeEach(async () => {
11
+ context = runtime_registration();
12
+ await context.projections.registerFor(RuntimeModel, defineRuntime);
13
+ });
14
+
15
+ it('should send the compiled projection to the kernel', () => {
16
+ expect(context.registerProjection).toHaveBeenCalledWith(expect.objectContaining({
17
+ EventStore: 'store', Projections: [expect.objectContaining({ Identifier: 'runtime-model', ReadModel: 'runtime-model', IsActive: true })]
18
+ }));
19
+ });
20
+
21
+ it('should register the explicit model schema and observer association', () => {
22
+ const model = context.registerReadModel.mock.calls[0][0].ReadModels[0];
23
+ expect(model).toMatchObject({ Type: { Identifier: 'runtime-model' }, ObserverIdentifier: 'runtime-model' });
24
+ expect(JSON.parse(model.Schema).properties).toHaveProperty('name');
25
+ });
26
+
27
+ it('should associate the acknowledged projection with its read model', async () => {
28
+ expect(context.projections.hasFor('runtime-model')).toBe(true);
29
+ expect(context.projections.hasForModel(RuntimeModel)).toBe(true);
30
+ expect(context.projections.getProjectionIdFor(RuntimeModel).value).toBe('runtime-model');
31
+ await context.projections.getStateForModel(RuntimeModel);
32
+ expect(context.getState).toHaveBeenCalledWith(expect.objectContaining({ ObserverId: 'runtime-model', EventSequenceId: 'event-log' }));
33
+ });
34
+
35
+ it('should retain it through discovery and parameterless registration', async () => {
36
+ await context.projections.discover();
37
+ await context.projections.register();
38
+ expect(context.registerProjection).toHaveBeenCalledTimes(2);
39
+ expect(context.registerProjection.mock.calls[1][0]).toEqual(context.registerProjection.mock.calls[0][0]);
40
+ expect(context.registerReadModel.mock.calls[1][0]).toEqual(context.registerReadModel.mock.calls[0][0]);
41
+ });
42
+ });
43
+
44
+ describe('when registering a passive runtime projection with an explicit identifier', () => {
45
+ it('should preserve the identifier, event sequence, and on-demand sink', async () => {
46
+ const context = runtime_registration();
47
+ await context.projections.registerFor(RuntimeModel, builder => {
48
+ defineRuntime(builder);
49
+ builder.passive().fromEventSequence('custom-sequence');
50
+ }, 'explicit-runtime');
51
+ expect(context.projections.getProjectionIdFor(RuntimeModel).value).toBe('explicit-runtime');
52
+ expect(context.registerReadModel.mock.calls[0][0].ReadModels[0].Sink.TypeId).toBe(WellKnownSinks.None);
53
+ await context.projections.getStateForModel(RuntimeModel);
54
+ expect(context.getState).toHaveBeenCalledWith(expect.objectContaining({ ObserverId: 'explicit-runtime', EventSequenceId: 'custom-sequence' }));
55
+ });
56
+ });
57
+
58
+ describe('when registering a model-bound type explicitly at runtime', () => {
59
+ it('should compile decorators and retain the projection independently of discovery', async () => {
60
+ const context = runtime_registration();
61
+ await context.projections.registerModelBound(BoundModel);
62
+ expect(context.registerProjection).toHaveBeenCalledWith(expect.objectContaining({
63
+ Projections: [expect.objectContaining({ Identifier: 'BoundModel', ReadModel: 'BoundModel', From: expect.any(Array) })]
64
+ }));
65
+ expect(context.registerReadModel.mock.calls[0][0].ReadModels[0].ObserverIdentifier).toBe('BoundModel');
66
+ expect(context.projections.getProjectionIdFor(BoundModel).value).toBe('BoundModel');
67
+ await context.projections.discover();
68
+ await context.projections.register();
69
+ expect(context.registerProjection).toHaveBeenCalledTimes(2);
70
+ expect(context.projections.hasForModel(BoundModel)).toBe(true);
71
+ });
72
+ });
@@ -0,0 +1,116 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field } from '@cratis/fundamentals';
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
6
+ import { TypeDiscoverer } from '../../types/TypeDiscoverer.js';
7
+ import { projection } from '../declarative/projection.js';
8
+ import { fromEvent } from '../modelBound/fromEvent.js';
9
+ import { setFrom } from '../modelBound/setFrom.js';
10
+ import { default_runtime_registration } from './given/default_runtime_registration.fixture.js';
11
+
12
+ let context: ReturnType<typeof default_runtime_registration>;
13
+ beforeEach(() => {
14
+ TypeDiscoverer.default.clear();
15
+ context = default_runtime_registration();
16
+ });
17
+ afterEach(() => {
18
+ context.dispose();
19
+ TypeDiscoverer.default.clear();
20
+ });
21
+
22
+ describe('when standard property decorators become discoverable after runtime registration', () => {
23
+ it.each(['fluent', 'model-bound'] as const)('should retain the %s definition through discovery, registration and reconnect', async style => {
24
+ const { artifacts, PropertyModel, store, registerProjection } = context;
25
+ expect(artifacts.readModels).not.toContain(PropertyModel);
26
+ if (style === 'fluent') await store.projections.registerFor(PropertyModel, context.define);
27
+ else await store.projections.registerModelBound(PropertyModel);
28
+ expect(artifacts.readModels).toContain(PropertyModel);
29
+ const original = registerProjection.mock.calls[0][0];
30
+
31
+ await store.projections.discover();
32
+ await store.projections.register();
33
+ await context.reconnect();
34
+
35
+ expect(registerProjection).toHaveBeenCalledTimes(3);
36
+ expect(registerProjection.mock.calls.map(call => call[0])).toEqual([original, original, original]);
37
+ expect(store.projections.getProjectionIdFor(PropertyModel).value).toBe('property-runtime');
38
+ expect(store.registrationResult.state).toBe('successful');
39
+ });
40
+
41
+ it.each(['fluent', 'model-bound'] as const)('should allow later registrations after the %s model is constructed by introspection', async style => {
42
+ const { Added, PropertyModel, store } = context;
43
+ if (style === 'fluent') await store.projections.registerFor(PropertyModel, context.define);
44
+ else await store.projections.registerModelBound(PropertyModel);
45
+
46
+ @fromEvent(Added)
47
+ class LaterModel { @field(String) name = ''; }
48
+ await store.projections.registerModelBound(LaterModel);
49
+
50
+ expect(store.projections.hasForModel(PropertyModel)).toBe(true);
51
+ expect(store.projections.hasForModel(LaterModel)).toBe(true);
52
+ expect(context.registerProjection).toHaveBeenCalledTimes(2);
53
+ });
54
+ });
55
+
56
+ describe('when explicitly registering an already-discovered class-level model', () => {
57
+ it('should acknowledge it once, then be idempotent for the same constructor and identifier', async () => {
58
+ const { Added, artifacts, store, registerProjection } = context;
59
+ @fromEvent(Added)
60
+ class NameDetails {
61
+ @setFrom(Added)
62
+ @field(String) name = '';
63
+ }
64
+ expect(artifacts.readModels).toContain(NameDetails);
65
+ await store.projections.discover();
66
+ expect(store.projections.hasForModel(NameDetails)).toBe(true);
67
+
68
+ await store.projections.registerModelBound(NameDetails);
69
+ await store.projections.registerModelBound(NameDetails);
70
+ expect(registerProjection).toHaveBeenCalledTimes(1);
71
+ await store.projections.discover();
72
+ await store.projections.register();
73
+ await context.reconnect();
74
+
75
+ expect(registerProjection).toHaveBeenCalledTimes(3);
76
+ expect(registerProjection.mock.calls[1][0]).toEqual(registerProjection.mock.calls[0][0]);
77
+ expect(registerProjection.mock.calls[2][0]).toEqual(registerProjection.mock.calls[0][0]);
78
+ expect(store.projections.getProjectionIdFor(NameDetails).value).toBe('NameDetails');
79
+ });
80
+ });
81
+
82
+ describe('when another declaration uses the same runtime projection identifier', () => {
83
+ it('should reject a different discovered model constructor rather than treating it as the retained model', async () => {
84
+ const { Added, PropertyModel, store, registerProjection } = context;
85
+ await store.projections.registerModelBound(PropertyModel);
86
+ @fromEvent(Added)
87
+ class DifferentModel { static readonly readModelId = 'property-runtime'; }
88
+ expect(context.artifacts.readModels).toContain(DifferentModel);
89
+
90
+ await expect(store.projections.discover()).rejects.toThrow("Projection id 'property-runtime' is already registered at runtime");
91
+ await expect(store.projections.registerModelBound(DifferentModel)).rejects.toThrow('already registered at runtime');
92
+ expect(store.projections.getProjectionIdFor(PropertyModel).value).toBe('property-runtime');
93
+ expect(registerProjection).toHaveBeenCalledTimes(1);
94
+ });
95
+
96
+ it('should reject a different constructor that was discovered before the explicit registration', async () => {
97
+ const { Added, PropertyModel, store } = context;
98
+ @fromEvent(Added)
99
+ class DifferentModel { static readonly readModelId = 'property-runtime'; }
100
+ expect(context.artifacts.readModels).toContain(DifferentModel);
101
+
102
+ await expect(store.projections.registerModelBound(PropertyModel)).rejects.toThrow("Projection id 'property-runtime' is already discovered");
103
+ expect(context.registerProjection).not.toHaveBeenCalled();
104
+ });
105
+
106
+ it('should still reject a separate declarative projection even when it targets the same model', async () => {
107
+ const { PropertyModel, store } = context;
108
+ await store.projections.registerFor(PropertyModel, context.define);
109
+ @projection('property-runtime', PropertyModel)
110
+ class DifferentProjection { define = context.define; }
111
+ expect(context.artifacts.projections).toContain(DifferentProjection);
112
+
113
+ await expect(store.projections.discover()).rejects.toThrow("Projection id 'property-runtime' is already registered at runtime");
114
+ expect(context.registerProjection).toHaveBeenCalledTimes(1);
115
+ });
116
+ });