@cratis/chronicle 6.71.1 → 6.72.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 (133) hide show
  1. package/dist/reactors/AsyncQueue.d.ts +10 -0
  2. package/dist/reactors/AsyncQueue.d.ts.map +1 -0
  3. package/dist/reactors/AsyncQueue.js +42 -0
  4. package/dist/reactors/AsyncQueue.js.map +1 -0
  5. package/dist/reactors/IReactorBuilder.d.ts +12 -0
  6. package/dist/reactors/IReactorBuilder.d.ts.map +1 -0
  7. package/dist/reactors/IReactorBuilder.js +4 -0
  8. package/dist/reactors/IReactorBuilder.js.map +1 -0
  9. package/dist/reactors/IReactorDefinition.d.ts +14 -0
  10. package/dist/reactors/IReactorDefinition.d.ts.map +1 -0
  11. package/dist/reactors/IReactorDefinition.js +4 -0
  12. package/dist/reactors/IReactorDefinition.js.map +1 -0
  13. package/dist/reactors/IReactorDefinitionBuilder.d.ts +9 -0
  14. package/dist/reactors/IReactorDefinitionBuilder.d.ts.map +1 -0
  15. package/dist/reactors/IReactorDefinitionBuilder.js +4 -0
  16. package/dist/reactors/IReactorDefinitionBuilder.js.map +1 -0
  17. package/dist/reactors/IReactors.d.ts +21 -10
  18. package/dist/reactors/IReactors.d.ts.map +1 -1
  19. package/dist/reactors/ReactorBuilder.d.ts +32 -0
  20. package/dist/reactors/ReactorBuilder.d.ts.map +1 -0
  21. package/dist/reactors/ReactorBuilder.js +91 -0
  22. package/dist/reactors/ReactorBuilder.js.map +1 -0
  23. package/dist/reactors/ReactorCallback.d.ts +4 -0
  24. package/dist/reactors/ReactorCallback.d.ts.map +1 -0
  25. package/dist/reactors/ReactorCallback.js +4 -0
  26. package/dist/reactors/ReactorCallback.js.map +1 -0
  27. package/dist/reactors/ReactorEvent.d.ts +7 -0
  28. package/dist/reactors/ReactorEvent.d.ts.map +1 -0
  29. package/dist/reactors/ReactorEvent.js +4 -0
  30. package/dist/reactors/ReactorEvent.js.map +1 -0
  31. package/dist/reactors/ReactorObservation.d.ts +21 -0
  32. package/dist/reactors/ReactorObservation.d.ts.map +1 -0
  33. package/dist/reactors/ReactorObservation.js +43 -0
  34. package/dist/reactors/ReactorObservation.js.map +1 -0
  35. package/dist/reactors/ReactorObservationTarget.d.ts +4 -1
  36. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -1
  37. package/dist/reactors/ReactorPageDispatcher.d.ts +6 -0
  38. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -1
  39. package/dist/reactors/ReactorPageDispatcher.js +96 -51
  40. package/dist/reactors/ReactorPageDispatcher.js.map +1 -1
  41. package/dist/reactors/ReactorRegistration.d.ts +14 -0
  42. package/dist/reactors/ReactorRegistration.d.ts.map +1 -0
  43. package/dist/reactors/ReactorRegistration.js +4 -0
  44. package/dist/reactors/ReactorRegistration.js.map +1 -0
  45. package/dist/reactors/ReactorRegistrationKind.d.ts +7 -0
  46. package/dist/reactors/ReactorRegistrationKind.d.ts.map +1 -0
  47. package/dist/reactors/ReactorRegistrationKind.js +10 -0
  48. package/dist/reactors/ReactorRegistrationKind.js.map +1 -0
  49. package/dist/reactors/ReactorRegistrations.d.ts +17 -0
  50. package/dist/reactors/ReactorRegistrations.d.ts.map +1 -0
  51. package/dist/reactors/ReactorRegistrations.js +42 -0
  52. package/dist/reactors/ReactorRegistrations.js.map +1 -0
  53. package/dist/reactors/ReactorSubscription.d.ts +4 -0
  54. package/dist/reactors/ReactorSubscription.d.ts.map +1 -0
  55. package/dist/reactors/ReactorSubscription.js +4 -0
  56. package/dist/reactors/ReactorSubscription.js.map +1 -0
  57. package/dist/reactors/Reactors.d.ts +31 -38
  58. package/dist/reactors/Reactors.d.ts.map +1 -1
  59. package/dist/reactors/Reactors.js +143 -274
  60. package/dist/reactors/Reactors.js.map +1 -1
  61. package/dist/reactors/WaitTillSubscribedOptions.d.ts +7 -0
  62. package/dist/reactors/WaitTillSubscribedOptions.d.ts.map +1 -0
  63. package/dist/reactors/WaitTillSubscribedOptions.js +4 -0
  64. package/dist/reactors/WaitTillSubscribedOptions.js.map +1 -0
  65. package/dist/reactors/index.d.ts +5 -0
  66. package/dist/reactors/index.d.ts.map +1 -1
  67. package/dist/reactors/index.js.map +1 -1
  68. package/dist/reactors/prepareReactor.d.ts +34 -0
  69. package/dist/reactors/prepareReactor.d.ts.map +1 -0
  70. package/dist/reactors/prepareReactor.js +75 -0
  71. package/dist/reactors/prepareReactor.js.map +1 -0
  72. package/dist/reactors/waitTillSubscribed.d.ts +5 -0
  73. package/dist/reactors/waitTillSubscribed.d.ts.map +1 -0
  74. package/dist/reactors/waitTillSubscribed.js +29 -0
  75. package/dist/reactors/waitTillSubscribed.js.map +1 -0
  76. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.d.ts +142 -0
  77. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.d.ts.map +1 -0
  78. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.js +142 -0
  79. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.js.map +1 -0
  80. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.d.ts +24 -0
  81. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.d.ts.map +1 -0
  82. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.js +34 -0
  83. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.js.map +1 -0
  84. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.d.ts +17 -0
  85. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.d.ts.map +1 -0
  86. package/dist/testing/projections/{ProjectionCountChildrenCapabilities.js → ProjectionArithmeticChildrenCapabilities.js} +24 -12
  87. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js.map +1 -0
  88. package/dist/testing/projections/ProjectionRootCapabilities.js +4 -4
  89. package/dist/testing/projections/ProjectionRootCapabilities.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +2 -2
  92. package/reactors/AsyncQueue.ts +41 -0
  93. package/reactors/IReactorBuilder.ts +15 -0
  94. package/reactors/IReactorDefinition.ts +17 -0
  95. package/reactors/IReactorDefinitionBuilder.ts +12 -0
  96. package/reactors/IReactors.ts +25 -10
  97. package/reactors/ReactorBuilder.ts +98 -0
  98. package/reactors/ReactorCallback.ts +7 -0
  99. package/reactors/ReactorEvent.ts +10 -0
  100. package/reactors/ReactorObservation.ts +45 -0
  101. package/reactors/ReactorObservationTarget.ts +4 -1
  102. package/reactors/ReactorPageDispatcher.ts +98 -54
  103. package/reactors/ReactorRegistration.ts +11 -0
  104. package/reactors/ReactorRegistrationKind.ts +9 -0
  105. package/reactors/ReactorRegistrations.ts +45 -0
  106. package/reactors/ReactorSubscription.ts +7 -0
  107. package/reactors/Reactors.ts +156 -310
  108. package/reactors/WaitTillSubscribedOptions.ts +9 -0
  109. package/reactors/for_Reactors/given/runtime_reactors.fixture.ts +50 -0
  110. package/reactors/for_Reactors/when_a_class_reactor_fails_to_restart.spec.ts +67 -0
  111. package/reactors/for_Reactors/when_a_class_reactor_fails_to_start.spec.ts +80 -0
  112. package/reactors/for_Reactors/when_class_delivery_is_unregistered.spec.ts +62 -0
  113. package/reactors/for_Reactors/when_defining_runtime_reactors.spec.ts +77 -0
  114. package/reactors/for_Reactors/when_dispatching_runtime_reactors.spec.ts +94 -0
  115. package/reactors/for_Reactors/when_registering_runtime_reactors.spec.ts +102 -0
  116. package/reactors/for_Reactors/when_stopping_runtime_reactors.spec.ts +160 -0
  117. package/reactors/for_Reactors/when_using_the_default_artifacts_provider.spec.ts +80 -0
  118. package/reactors/for_Reactors/when_waiting_till_subscribed.spec.ts +65 -0
  119. package/reactors/index.ts +5 -0
  120. package/reactors/prepareReactor.ts +79 -0
  121. package/reactors/waitTillSubscribed.ts +29 -0
  122. package/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.ts +71 -0
  123. package/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.ts +38 -0
  124. package/testing/for_ReadModelScenario/when_adding_with_children/with_a_fluent_projection.spec.ts +64 -0
  125. package/testing/for_ReadModelScenario/when_adding_with_children/with_legacy_decorators.legacy.spec.ts +41 -0
  126. package/testing/for_ReadModelScenario/when_adding_with_children/with_standard_decorators.standard.spec.ts +42 -0
  127. package/testing/projections/{ProjectionCountChildrenCapabilities.ts → ProjectionArithmeticChildrenCapabilities.ts} +22 -11
  128. package/testing/projections/ProjectionRootCapabilities.ts +4 -4
  129. package/testing/projections/for_ProjectionCapabilities/when_validating_add_with_children.spec.ts +91 -0
  130. package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +12 -2
  131. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts +0 -15
  132. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts.map +0 -1
  133. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js.map +0 -1
@@ -0,0 +1,80 @@
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, chai, describe, it, vi } from 'vitest';
5
+ import { DefaultClientArtifactsProvider } from '../../artifacts/DefaultClientArtifactsProvider.js';
6
+ import { ChronicleClient } from '../../ChronicleClient.js';
7
+ import { ChronicleOptions } from '../../ChronicleOptions.js';
8
+ import type { ChronicleConnection } from '../../connection/ChronicleConnection.js';
9
+ import { EventStore } from '../../EventStore.js';
10
+ import { EventStoreName } from '../../EventStoreName.js';
11
+ import { EventStoreNamespaceName } from '../../EventStoreNamespaceName.js';
12
+ import { eventType } from '../../events/eventTypeDecorator.js';
13
+ import { TypeDiscoverer } from '../../types/TypeDiscoverer.js';
14
+ import { DecoratorType } from '../../types/DecoratorType.js';
15
+ import { reactor } from '../reactor.js';
16
+ import { runtime_reactors } from './given/runtime_reactors.fixture.js';
17
+
18
+ chai.should();
19
+
20
+ for (const scenario of ['discovery duplicate', 'runtime duplicate', 'runtime discovery collision', 'mixed reconnect', 'removal during reconnect'] as const) {
21
+ describe(`when using the default artifacts provider for ${scenario}`, () => {
22
+ let context: runtime_reactors;
23
+ let client: ChronicleClient;
24
+ let store: EventStore;
25
+ let failure: unknown;
26
+ beforeEach(async () => {
27
+ TypeDiscoverer.default.clear();
28
+ context = new runtime_reactors();
29
+ @eventType('real-added')
30
+ class Added {}
31
+ @reactor('real-discovered')
32
+ class Discovered { added() {} }
33
+ const register = vi.fn().mockResolvedValue({});
34
+ const connection = new Proxy({}, {
35
+ get: (_target, service) => {
36
+ if (service === 'logger') return undefined;
37
+ if (service === 'reactors') return { observe: context.observe };
38
+ return new Proxy({}, { get: () => register });
39
+ }
40
+ }) as ChronicleConnection;
41
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [] }));
42
+ store = new EventStore(new EventStoreName('store'), EventStoreNamespaceName.default, connection, client['_lifecycle'], 'sink', DefaultClientArtifactsProvider.default);
43
+ client['_stores'].set('store', store);
44
+ const runtime = () => store.reactors.register('runtime', builder => builder.on(Added, () => {}));
45
+ try {
46
+ if (scenario === 'discovery duplicate') {
47
+ @reactor('real-discovered')
48
+ class Duplicate { added() {} }
49
+ TypeDiscoverer.default.register(DecoratorType.Reactor, Discovered, 'first-discovery-key');
50
+ TypeDiscoverer.default.register(DecoratorType.Reactor, Duplicate, 'second-discovery-key');
51
+ await store.reactors.register();
52
+ } else if (scenario === 'runtime duplicate') {
53
+ const first = runtime();
54
+ const second = runtime();
55
+ await first;
56
+ await second;
57
+ } else if (scenario === 'runtime discovery collision') {
58
+ await store.reactors.register('real-discovered', builder => builder.on(Added, () => {}));
59
+ } else {
60
+ await runtime();
61
+ await store.reactors.register();
62
+ if (scenario === 'removal during reconnect') await store.reactors.unregister('runtime');
63
+ await client['_lifecycle'].disconnected(error => { throw error; });
64
+ await client['_lifecycle'].connected(error => { throw error; });
65
+ await store.reactors.register();
66
+ }
67
+ } catch (error) { failure = error; }
68
+ });
69
+ afterEach(() => {
70
+ store.disposeObservations(); client.dispose(); context.reactors.dispose(); TypeDiscoverer.default.clear();
71
+ });
72
+ if (scenario.includes('duplicate') || scenario.includes('collision')) {
73
+ it('should reject rather than overwrite the identity', () => (failure as Error).message.should.match(/already registered/));
74
+ it('should open no streams for the invalid batch', () => context.observe.mock.calls.length.should.equal(scenario === 'runtime duplicate' ? 1 : 0));
75
+ } else {
76
+ it('should use cached EventStore lifecycle restoration exactly once', () => context.observe.mock.calls.length.should.equal(scenario === 'mixed reconnect' ? 4 : 3));
77
+ it('should cancel the previous observations', () => context.attempts[0].signal.aborted.should.be.true);
78
+ }
79
+ });
80
+ }
@@ -0,0 +1,65 @@
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, chai, describe, it, vi } from 'vitest';
5
+ import { ObserverInformation } from '@cratis/chronicle.contracts';
6
+ import { Registered, runtime_reactors } from './given/runtime_reactors.fixture.js';
7
+
8
+ chai.should();
9
+
10
+ describe('when waiting for a reactor subscription', () => {
11
+ let context: runtime_reactors;
12
+ let completed: boolean;
13
+ beforeEach(async () => {
14
+ vi.useFakeTimers();
15
+ context = new runtime_reactors();
16
+ await context.reactors.register('runtime', builder => builder.on(Registered, () => {}).onEventSequence('custom'));
17
+ context.information.mockResolvedValueOnce(ObserverInformation.fromPartial({ IsSubscribed: false }))
18
+ .mockResolvedValue(ObserverInformation.fromPartial({ IsSubscribed: true }));
19
+ const pending = context.reactors.waitTillSubscribed('runtime', { timeout: 100 });
20
+ await vi.advanceTimersByTimeAsync(50);
21
+ await pending;
22
+ completed = true;
23
+ });
24
+ afterEach(() => { context.reactors.dispose(); vi.useRealTimers(); });
25
+ it('should poll until the observer reports subscribed', () => {
26
+ completed.should.be.true;
27
+ context.information.mock.calls.length.should.equal(2);
28
+ });
29
+ it('should scope readiness to the store namespace ID and sequence', () => {
30
+ const request = (context.information.mock.calls as unknown as [object][])[0][0];
31
+ request.should.deep.equal({ EventStore: 'store', Namespace: 'tenant', ObserverId: 'runtime', EventSequenceId: 'custom' });
32
+ });
33
+ });
34
+
35
+ for (const scenario of ['timeout', 'cancellation', 'disposal', 'query failure'] as const) {
36
+ describe(`when subscription readiness encounters ${scenario}`, () => {
37
+ let context: runtime_reactors;
38
+ let failure: unknown;
39
+ beforeEach(async () => {
40
+ vi.useFakeTimers();
41
+ context = new runtime_reactors();
42
+ const controller = new AbortController();
43
+ if (scenario === 'query failure') context.information.mockRejectedValue(new Error('query denied'));
44
+ const pending = context.reactors.waitTillSubscribed('runtime', { timeout: 100, signal: controller.signal }).catch(error => { failure = error; });
45
+ if (scenario === 'cancellation') controller.abort();
46
+ if (scenario === 'disposal') context.reactors.dispose();
47
+ await vi.advanceTimersByTimeAsync(100);
48
+ await pending;
49
+ });
50
+ afterEach(() => { context.reactors.dispose(); vi.useRealTimers(); });
51
+ it('should settle without claiming readiness', () => (failure instanceof Error).should.be.true);
52
+ it('should not register an observation as a side effect', () => context.observe.mock.calls.length.should.equal(0));
53
+ });
54
+ }
55
+
56
+ describe('when readiness observes an already subscribed observer', () => {
57
+ let context: runtime_reactors;
58
+ beforeEach(async () => {
59
+ context = new runtime_reactors();
60
+ context.information.mockResolvedValue(ObserverInformation.fromPartial({ IsSubscribed: true }));
61
+ await context.reactors.waitTillSubscribed('existing');
62
+ });
63
+ afterEach(() => context.reactors.dispose());
64
+ it('should allow readiness independently of a local registration acknowledgment', () => context.information.mock.calls.length.should.equal(1));
65
+ });
package/reactors/index.ts CHANGED
@@ -10,6 +10,11 @@ export { startAtTail } from './startAtTail.js';
10
10
  export { replay } from './replay.js';
11
11
  export type { ReactorMetadata } from './reactor.js';
12
12
  export type { IReactors } from './IReactors.js';
13
+ export type { IReactorBuilder } from './IReactorBuilder.js';
14
+ export type { IReactorDefinitionBuilder } from './IReactorDefinitionBuilder.js';
15
+ export type { IReactorDefinition } from './IReactorDefinition.js';
16
+ export type { ReactorEvent } from './ReactorEvent.js';
17
+ export type { WaitTillSubscribedOptions } from './WaitTillSubscribedOptions.js';
13
18
  export { Reactors } from './Reactors.js';
14
19
  export type { ReactorResultHandler } from './ReactorResultHandler.js';
15
20
  export type { ReactorServices } from './ReactorServices.js';
@@ -0,0 +1,79 @@
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 { EventGenerationDelivery, type ReactorMessage } from '@cratis/chronicle.contracts';
5
+ import { createHandlerInstanceValidator } from '../observation/createHandlerInstanceValidator.js';
6
+ import { EventSequenceId } from '../eventSequences/EventSequenceId.js';
7
+ import { getEventTypeMetadata } from '../events/eventTypeDecorator.js';
8
+ import { getTagsFor } from '../events/tagDecorator.js';
9
+ import { getFilterTagsFor } from '../events/filterEventsByTagDecorator.js';
10
+ import { getEventSourceTypeFor } from '../events/eventSourceTypeDecorator.js';
11
+ import { getEventStreamTypeFor } from '../events/eventStreamTypeDecorator.js';
12
+ import { toPageDelivery } from '../observation/batches/batchSize.js';
13
+ import type { IClientArtifactsProvider } from '../artifacts/IClientArtifactsProvider.js';
14
+ import type { ReactorSubscription } from './ReactorSubscription.js';
15
+ import type { ReactorRegistration } from './ReactorRegistration.js';
16
+ import { ReactorRegistrationKind } from './ReactorRegistrationKind.js';
17
+ import { getReactorMetadata } from './reactor.js';
18
+ import { isOnceOnly } from './onceOnly.js';
19
+ import { isStartAtTail } from './startAtTail.js';
20
+ import { getReactorBatchMethods, getReactorEventTypes } from './ReactorDispatcher.js';
21
+
22
+ /** Resolves handler validation before opening any stream in a registration batch. */
23
+ export function prepareReactor(registration: ReactorRegistration, artifacts: IClientArtifactsProvider) {
24
+ if (registration.kind !== ReactorRegistrationKind.Discovered) {
25
+ const definition = registration.definition;
26
+ if (!definition.id.value.trim()) throw new Error('Reactor id must not be empty.');
27
+ if (!definition.eventTypes.length) throw new Error('Reactor must subscribe to at least one event type.');
28
+ const known = artifacts.eventTypes.map(type => getEventTypeMetadata(type)?.eventType.id.value);
29
+ for (const type of definition.eventTypes) {
30
+ if (!known.includes(type.id.value)) throw new Error(`Reactor event type '${type.id.value}' has no registered event type.`);
31
+ }
32
+ return {
33
+ id: registration.id, reactorType: undefined, runtime: definition,
34
+ eventSequenceId: definition.eventSequenceId.value,
35
+ entries: definition.eventTypes.map(type => ({ id: type.id.value, generation: type.generation.value })),
36
+ batchMethods: [], validateInstance: (_instance: object) => {},
37
+ isReplayable: definition.isReplayable
38
+ };
39
+ }
40
+ const type = registration.type;
41
+ const entries = getReactorEventTypes(type, artifacts.eventTypes);
42
+ const batchMethods = getReactorBatchMethods(type, artifacts.eventTypes);
43
+ return {
44
+ id: registration.id, reactorType: type, runtime: undefined,
45
+ eventSequenceId: getReactorMetadata(type)!.eventSequenceId ?? EventSequenceId.eventLog.value,
46
+ entries, batchMethods,
47
+ validateInstance: createHandlerInstanceValidator(type, [
48
+ ...entries.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)),
49
+ ...batchMethods.map(method => method.methodName)
50
+ ]),
51
+ isReplayable: !isOnceOnly(type)
52
+ };
53
+ }
54
+
55
+ /** Creates the protocol subscription, without implying remote acknowledgment. */
56
+ export function reactorSubscriptionMessage(subscription: ReactorSubscription, scope: {
57
+ connectionId: string; eventStore: string; namespace: string;
58
+ }): ReactorMessage {
59
+ const { reactorType: type } = subscription;
60
+ return { Content: { Value0: {
61
+ ConnectionId: scope.connectionId, EventStore: scope.eventStore, Namespace: scope.namespace,
62
+ Reactor: {
63
+ ReactorId: subscription.id, EventSequenceId: subscription.eventSequenceId,
64
+ EventTypes: [...subscription.entries, ...subscription.batchMethods.flatMap(method => [...method.eventTypes.values()])].map(entry => ({
65
+ EventType: { Id: entry.id, Generation: entry.generation, Tombstone: false }, Key: '$eventSourceId'
66
+ })),
67
+ IsReplayable: subscription.isReplayable, IsNotReplayable: !subscription.isReplayable,
68
+ StartAtTail: type ? isStartAtTail(type) : false,
69
+ GenerationDelivery: EventGenerationDelivery.Compatibility,
70
+ Tags: type ? getTagsFor(type).map(tag => tag.value) : [],
71
+ Filters: {
72
+ FilterTags: type ? getFilterTagsFor(type).map(tag => tag.value) : [],
73
+ EventSourceType: type ? getEventSourceTypeFor(type) : '',
74
+ EventStreamType: type ? getEventStreamTypeFor(type) : 'All'
75
+ }
76
+ },
77
+ PageDelivery: type ? toPageDelivery(type) : undefined
78
+ }, Value1: undefined } };
79
+ }
@@ -0,0 +1,29 @@
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 { setTimeout as delay } from 'node:timers/promises';
5
+ import type { ChronicleConnection } from '../connection/ChronicleConnection.js';
6
+ import type { WaitTillSubscribedOptions } from './WaitTillSubscribedOptions.js';
7
+
8
+ /** Polls current observer readiness; a previous subscription can satisfy this check. */
9
+ export async function waitTillSubscribed(read: (signal: AbortSignal) => ReturnType<ChronicleConnection['observers']['getObserverInformation']>,
10
+ options: WaitTillSubscribedOptions, lifetime: AbortSignal): Promise<void> {
11
+ const timeout = options.timeout ?? 5000;
12
+ if (!Number.isFinite(timeout) || timeout < 0) throw new Error('Subscription timeout must be a finite non-negative number.');
13
+ const controller = new AbortController();
14
+ const timer = setTimeout(() => controller.abort(new Error('Timed out waiting for reactor subscription.')), timeout);
15
+ const signals = [controller.signal, lifetime];
16
+ if (options.signal) signals.push(options.signal);
17
+ const signal = AbortSignal.any(signals);
18
+ try {
19
+ for (;;) {
20
+ signal.throwIfAborted();
21
+ const information = await read(signal);
22
+ signal.throwIfAborted();
23
+ if (information.IsSubscribed) return;
24
+ await delay(50, undefined, { signal });
25
+ }
26
+ } finally {
27
+ clearTimeout(timer);
28
+ }
29
+ }
@@ -0,0 +1,71 @@
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 type { IClientArtifactsProvider } from '../../../../artifacts/IClientArtifactsProvider.js';
6
+ import { eventType } from '../../../../events/eventTypeDecorator.js';
7
+ import type { IProjectionBuilderFor } from '../../../../projections/declarative/IProjectionBuilderFor.js';
8
+ import { projection } from '../../../../projections/declarative/projection.js';
9
+ import { ProjectionDefinitionCompiler } from '../../../../projections/ProjectionDefinitionCompiler.js';
10
+
11
+ @eventType('Added')
12
+ export class Added {
13
+ @field(Number) readonly amount: number;
14
+ constructor(amount: number) { this.amount = amount; }
15
+ }
16
+ @eventType('TotalAdded')
17
+ class TotalAdded {
18
+ @field(Number) readonly total: number;
19
+ constructor(total: number) { this.total = total; }
20
+ }
21
+ @eventType('UnderscoreAdded')
22
+ class UnderscoreAdded {
23
+ @field(Number) readonly _amount: number;
24
+ constructor(_amount: number) { this._amount = _amount; }
25
+ }
26
+ @eventType('ItemChanged')
27
+ export class ItemChanged {
28
+ @field(String) readonly itemId: string;
29
+ @field(String) readonly name: string;
30
+ constructor(itemId: string, name: string) { this.itemId = itemId; this.name = name; }
31
+ }
32
+ @eventType('ItemRemoved')
33
+ export class ItemRemoved {
34
+ @field(String) readonly itemId: string;
35
+ constructor(itemId: string) { this.itemId = itemId; }
36
+ }
37
+ @eventType('Removed')
38
+ export class Removed {}
39
+ export class Item {
40
+ @field(String) itemId!: string;
41
+ @field(String) name!: string;
42
+ }
43
+ export class Totals {
44
+ @field(String) id!: string;
45
+ @field(Number) total!: number;
46
+ @field(Array, { genericArguments: [Item] }) items!: Item[];
47
+ }
48
+
49
+ function variant<E extends object>(name: string, event: new (amount: number) => E, operand: (event: E) => number) {
50
+ class TotalsProjection {
51
+ define(builder: IProjectionBuilderFor<Totals>): void {
52
+ builder.from(event, from => from.add(model => model.total).with(operand))
53
+ .children<Item>(model => model.items, child => child.identifiedBy(item => item.itemId)
54
+ .from(ItemChanged, from => from.usingKey(value => value.itemId))
55
+ .removedWith(ItemRemoved, removal => removal.usingKey(value => value.itemId)))
56
+ .removedWith(Removed);
57
+ }
58
+ }
59
+ projection(name, Totals)(TotalsProjection);
60
+ const artifacts = {
61
+ readModels: [Totals], projections: [TotalsProjection], eventTypes: [event, ItemChanged, ItemRemoved, Removed],
62
+ globalForHandlers: [], reducers: [], reactors: [], seeders: [], constraints: [], webhooks: [], eventTypeMigrations: []
63
+ } satisfies IClientArtifactsProvider;
64
+ return { name, event, artifacts, compile: () => new ProjectionDefinitionCompiler(artifacts, 'test').compile([TotalsProjection], []) };
65
+ }
66
+ export const variants = [
67
+ variant('add-children-lifecycle', Added, event => event.amount),
68
+ variant('add-children-same-property', TotalAdded, event => event.total),
69
+ variant('add-children-leading-underscore', UnderscoreAdded, event => event._amount)
70
+ ];
71
+ export const { artifacts, compile } = variants[0];
@@ -0,0 +1,38 @@
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 { ReadModelScenario } from '../../../ReadModelScenario.js';
5
+ import { Added, ItemChanged, ItemRemoved, Removed } from './compiled_projection.js';
6
+
7
+ type AddedParent = { id: string; total: number; items: Array<{ itemId: string; name: string }> };
8
+
9
+ export function history(add: (amount: number) => object = amount => new Added(amount)) {
10
+ return [
11
+ { source: 'A', event: add(2.5) }, { source: 'A', event: add(-1) },
12
+ { source: 'A', event: new ItemChanged('one', 'first') }, { source: 'A', event: new ItemChanged('two', 'second') },
13
+ { source: 'A', event: new ItemChanged('one', 'updated') }, { source: 'A', event: add(0) },
14
+ { source: 'B', event: add(8) }, { source: 'B', event: new ItemChanged('one', 'independent') },
15
+ { source: 'A', event: new ItemRemoved('one') }, { source: 'A', event: new ItemRemoved('unknown') },
16
+ { source: 'A', event: new Removed() }, { source: 'A', event: add(4.5) },
17
+ { source: 'A', event: new ItemChanged('new', 'recreated') }
18
+ ];
19
+ }
20
+
21
+ export async function lifecycle<T extends AddedParent>(scenario: ReadModelScenario<T>) {
22
+ const events = history();
23
+ const seed = (start: number, end: number) => {
24
+ for (const { source, event } of events.slice(start, end)) scenario.given.forEventSource(source).events(event);
25
+ };
26
+ seed(0, 8);
27
+ const first = (await scenario.instanceForEventSourceId('A'))!;
28
+ const other = (await scenario.instanceForEventSourceId('B'))!;
29
+ seed(8, 10);
30
+ const remaining = (await scenario.instanceForEventSourceId('A'))!;
31
+ seed(10, 11);
32
+ const removed = await scenario.instanceForEventSourceId('A');
33
+ const surviving = (await scenario.instanceForEventSourceId('B'))!;
34
+ seed(11, 13);
35
+ const recreated = (await scenario.instanceForEventSourceId('A'))!;
36
+ const repeated = (await scenario.instanceForEventSourceId('A'))!;
37
+ return { first, other, remaining, removed, surviving, recreated, repeated };
38
+ }
@@ -0,0 +1,64 @@
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 { readFileSync } from 'node:fs';
5
+ import { JsonSerializer } from '@cratis/fundamentals';
6
+ import { chai, describe, it } from 'vitest';
7
+ import { getEventTypeMetadata } from '../../../events/eventTypeDecorator.js';
8
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
9
+ import { artifacts, Totals, variants } from './given/compiled_projection.js';
10
+ import { history, lifecycle } from './given/lifecycle.js';
11
+
12
+ chai.should();
13
+ describe('when adding with independent children through a fluent projection', () => {
14
+ for (const variant of variants) {
15
+ it(`should compile exactly the oracle input for ${variant.name}`, () => {
16
+ const fixture = JSON.parse(readFileSync(new URL(`../../projections/fixtures/${variant.name}.json`, import.meta.url), 'utf8'));
17
+ const compiled = variant.compile();
18
+ const { LastUpdated, ...wire } = compiled.definitions[0];
19
+ LastUpdated!.should.deep.equal(fixture.compilerLastUpdated);
20
+ JSON.parse(JSON.stringify({ ...wire, NoAutoMapProperties: [] })).should.deep.equal(fixture.wireDefinition);
21
+ JSON.parse(compiled.readModels[0].Schema).should.deep.equal(fixture.readModel.schema);
22
+ const schemas = [...compiled.eventSchemas.get(compiled.definitions[0])!.values()].map(entry => {
23
+ entry.eventType.Tombstone.should.be.false;
24
+ const { Tombstone: _falseFlag, ...eventType } = entry.eventType;
25
+ return { ...entry, eventType };
26
+ });
27
+ schemas.should.deep.equal(fixture.eventSchemas);
28
+ const events = history(amount => new variant.event(amount));
29
+ events.length.should.equal(fixture.events.length);
30
+ events.forEach(({ source, event }, index) => {
31
+ const captured = fixture.events[index];
32
+ const type = getEventTypeMetadata(event.constructor)!.eventType;
33
+ captured.context.eventType.should.deep.equal({ Id: type.id.value, Generation: type.generation.value });
34
+ captured.context.eventSourceId.should.equal(source);
35
+ captured.content.should.deep.equal(JSON.parse(JsonSerializer.serialize(event)));
36
+ });
37
+ });
38
+ }
39
+
40
+ it('should accumulate fractions, negative and zero values independently of child updates and removals', async () => {
41
+ const result = await lifecycle(new ReadModelScenario(Totals, artifacts));
42
+ result.first.total.should.equal(1.5);
43
+ result.first.items.should.deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
44
+ result.remaining.total.should.equal(1.5);
45
+ result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]);
46
+ (result.removed === null).should.be.true;
47
+ result.surviving.should.deep.equal(result.other);
48
+ result.other.total.should.equal(8);
49
+ result.recreated.total.should.equal(4.5);
50
+ result.recreated.items.should.deep.equal([{ itemId: 'new', name: 'recreated' }]);
51
+ result.repeated.should.deep.equal(result.recreated);
52
+ });
53
+
54
+ for (const variant of variants.slice(1)) {
55
+ it(`should add rather than assign for ${variant.name}`, async () => {
56
+ const scenario = new ReadModelScenario(Totals, variant.artifacts);
57
+ for (const { source, event } of history(amount => new variant.event(amount)).slice(0, 8)) {
58
+ scenario.given.forEventSource(source).events(event);
59
+ }
60
+ (await scenario.instanceForEventSourceId('A'))!.total.should.equal(1.5);
61
+ (await scenario.instanceForEventSourceId('B'))!.total.should.equal(8);
62
+ });
63
+ }
64
+ });
@@ -0,0 +1,41 @@
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 { chai, describe, it } from 'vitest';
6
+ import { addFrom } from '../../../projections/modelBound/addFrom.js';
7
+ import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
8
+ import { removedWith } from '../../../projections/modelBound/removedWith.js';
9
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
10
+ import { Added, artifacts, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
11
+ import { lifecycle } from './given/lifecycle.js';
12
+
13
+ chai.should();
14
+ @removedWith(ItemRemoved, 'itemId')
15
+ class Item {
16
+ @field(String) itemId!: string;
17
+ @field(String) name!: string;
18
+ }
19
+ @removedWith(Removed)
20
+ class Totals {
21
+ @field(String) id!: string;
22
+ @field(Number) @addFrom(Added, 'amount') total!: number;
23
+ @field(Array) @childrenFrom(ItemChanged, { childType: Item, key: 'itemId', identifiedBy: 'itemId' })
24
+ items!: Item[];
25
+ }
26
+
27
+ describe('when adding with independent children through legacy decorators', () => {
28
+ it('should preserve sums through child changes, removal, independent roots and parent-first recreation', async () => {
29
+ const result = await lifecycle(new ReadModelScenario(Totals, { ...artifacts, projections: [], readModels: [Totals] }));
30
+ result.first.total.should.equal(1.5);
31
+ result.first.items.should.deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
32
+ result.remaining.total.should.equal(1.5);
33
+ result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]);
34
+ (result.removed === null).should.be.true;
35
+ result.surviving.should.deep.equal(result.other);
36
+ result.other.total.should.equal(8);
37
+ result.recreated.total.should.equal(4.5);
38
+ result.recreated.items.should.deep.equal([{ itemId: 'new', name: 'recreated' }]);
39
+ result.repeated.should.deep.equal(result.recreated);
40
+ });
41
+ });
@@ -0,0 +1,42 @@
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 { chai, describe, it, type Assertion } from 'vitest';
6
+ import { addFrom } from '../../../projections/modelBound/addFrom.js';
7
+ import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
8
+ import { removedWith } from '../../../projections/modelBound/removedWith.js';
9
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
10
+ import { Added, artifacts, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
11
+ import { lifecycle } from './given/lifecycle.js';
12
+
13
+ chai.should();
14
+ function should(value: unknown): Assertion { return (value as { should: Assertion }).should; }
15
+ @removedWith(ItemRemoved, 'itemId')
16
+ class Item {
17
+ @field(String) itemId!: string;
18
+ @field(String) name!: string;
19
+ }
20
+ @removedWith(Removed)
21
+ class Totals {
22
+ @field(String) id!: string;
23
+ @field(Number) @addFrom(Added, 'amount') total!: number;
24
+ @field(Array, { genericArguments: [Item] })
25
+ @childrenFrom(ItemChanged, { key: 'itemId', identifiedBy: 'itemId' }) items!: Item[];
26
+ }
27
+
28
+ describe('when adding with independent children through standard decorators', () => {
29
+ it('should preserve sums through child changes, removal, independent roots and parent-first recreation', async () => {
30
+ const result = await lifecycle(new ReadModelScenario(Totals, { ...artifacts, projections: [], readModels: [Totals] }));
31
+ should(result.first.total).equal(1.5);
32
+ should(result.first.items).deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
33
+ should(result.remaining.total).equal(1.5);
34
+ should(result.remaining.items).deep.equal([{ itemId: 'two', name: 'second' }]);
35
+ should(result.removed === null).be.true;
36
+ should(result.surviving).deep.equal(result.other);
37
+ should(result.other.total).equal(8);
38
+ should(result.recreated.total).equal(4.5);
39
+ should(result.recreated.items).deep.equal([{ itemId: 'new', name: 'recreated' }]);
40
+ should(result.repeated).deep.equal(result.recreated);
41
+ });
42
+ });
@@ -4,30 +4,41 @@
4
4
  import type { ChildrenDefinition } from '@cratis/chronicle.contracts';
5
5
  import type { FromRecord, RemovedWithRecord } from '../../projections/declarative/ProjectionBuilderCore.js';
6
6
  import type { JsonSchema } from '../../schemas/JsonSchema.js';
7
+ import { eventContractPath } from '../../projections/eventContractPath.js';
8
+ import type { ProjectionEventSchemaResolver } from './ProjectionEventSchemaResolver.js';
7
9
 
8
- /** The measured intersection of root counting and independent typed children. */
9
- export class ProjectionCountChildrenCapabilities {
10
- static supports(schema: JsonSchema, wire: Record<string, unknown>): boolean {
10
+ /** The measured intersection of one root accumulator and independent typed children. */
11
+ export class ProjectionArithmeticChildrenCapabilities {
12
+ static supports(schema: JsonSchema, wire: Record<string, unknown>, require: ProjectionEventSchemaResolver['require']): boolean {
11
13
  const from = wire.From as FromRecord[] ?? [];
12
14
  const children = Object.entries(wire.Children as Record<string, ChildrenDefinition> ?? {});
13
- if (!this.singleCount(from) || children.length !== 1) return false;
15
+ if (from.length !== 1 || children.length !== 1) return false;
16
+ const mappings = Object.entries(from[0].Value.Properties ?? {});
17
+ if (mappings.length !== 1) return false;
18
+ const [accumulator, expression] = mappings[0];
19
+ if (!this.accumulator(schema.properties?.[accumulator], expression, from[0], require)) return false;
14
20
  const [collection, child] = children[0];
15
- const count = Object.keys(from[0].Value.Properties)[0];
16
- return this.rootShape(schema, count, collection)
21
+ return this.rootShape(schema, accumulator, collection)
17
22
  && this.childShape(schema.properties?.[collection], child)
18
23
  && this.independentEvents(from, wire, child) && this.noInteractions(wire);
19
24
  }
20
25
 
21
- private static singleCount(from: FromRecord[]): boolean {
22
- if (from.length !== 1) return false;
23
- const expressions = Object.values(from[0].Value.Properties ?? {});
24
- return expressions.length === 1 && expressions[0] === '$count';
26
+ private static accumulator(target: JsonSchema | undefined, expression: string, from: FromRecord, require: ProjectionEventSchemaResolver['require']): boolean {
27
+ if (expression === '$count') return this.countTarget(target);
28
+ const operand = /^\$add\(([A-Za-z_][A-Za-z0-9]*)\)$/.exec(expression)?.[1];
29
+ if (!operand || !this.unformattedNumber(target)) return false;
30
+ const event = require(from.Key, eventContractPath('From', from.Key));
31
+ return this.unformattedNumber(event.properties?.[operand]);
32
+ }
33
+
34
+ private static unformattedNumber(schema?: JsonSchema): boolean {
35
+ return schema?.type === 'number' && schema.format === undefined;
25
36
  }
26
37
 
27
38
  private static rootShape(schema: JsonSchema, count: string, collection: string): boolean {
28
39
  const properties = schema.properties ?? {};
29
40
  return this.exactRootMembers(properties, count, collection)
30
- && this.plainString(properties.id) && this.countTarget(properties[count]);
41
+ && this.plainString(properties.id);
31
42
  }
32
43
 
33
44
  private static exactRootMembers(properties: Record<string, JsonSchema>, count: string, collection: string): boolean {
@@ -6,7 +6,7 @@ import type { FromRecord, RemovedWithRecord } from '../../projections/declarativ
6
6
  import { eventContractPath } from '../../projections/eventContractPath.js';
7
7
  import type { JsonSchema } from '../../schemas/JsonSchema.js';
8
8
  import { ProjectionArithmetic } from './ProjectionArithmetic.js';
9
- import { ProjectionCountChildrenCapabilities } from './ProjectionCountChildrenCapabilities.js';
9
+ import { ProjectionArithmeticChildrenCapabilities } from './ProjectionArithmeticChildrenCapabilities.js';
10
10
  import type { ProjectionCapabilityReject } from './ProjectionCapabilityReject.js';
11
11
  import type { ProjectionEventSchemaResolver } from './ProjectionEventSchemaResolver.js';
12
12
  import { ProjectionMappingCapabilities } from './ProjectionMappingCapabilities.js';
@@ -25,7 +25,7 @@ export class ProjectionRootCapabilities {
25
25
  this.checkOverlaps();
26
26
  const accumulators = new Set(this.from.flatMap(entry => Object.entries(entry.Value.Properties ?? {})
27
27
  .filter(([, expression]) => ProjectionArithmetic.isArithmetic(expression)).map(([property]) => property)));
28
- this.checkAccumulatorChildren(accumulators);
28
+ this.checkAccumulatorChildren(accumulators, resolver);
29
29
  for (const entry of this.from) this.checkClearedAccumulators(entry, accumulators);
30
30
  const mappings = new ProjectionMappingCapabilities(this.schema, this.reject, accumulators);
31
31
  for (const entry of [...this.from, ...this.removedWith]) this.subscription(entry, resolver, mappings);
@@ -39,10 +39,10 @@ export class ProjectionRootCapabilities {
39
39
  }
40
40
  }
41
41
 
42
- private checkAccumulatorChildren(accumulators: Set<string>): void {
42
+ private checkAccumulatorChildren(accumulators: Set<string>, resolver: ProjectionEventSchemaResolver): void {
43
43
  if (!accumulators.size) return;
44
44
  if (!Object.keys(this.wire.Children as object ?? {}).length) return;
45
- if (!ProjectionCountChildrenCapabilities.supports(this.schema, this.wire)) {
45
+ if (!ProjectionArithmeticChildrenCapabilities.supports(this.schema, this.wire, resolver.require)) {
46
46
  this.reject('Children', 'root arithmetic combined with children requires a kernel-backed test');
47
47
  }
48
48
  }