@cratis/chronicle 6.71.2 → 6.72.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.
- package/dist/reactors/AsyncQueue.d.ts +10 -0
- package/dist/reactors/AsyncQueue.d.ts.map +1 -0
- package/dist/reactors/AsyncQueue.js +42 -0
- package/dist/reactors/AsyncQueue.js.map +1 -0
- package/dist/reactors/IReactorBuilder.d.ts +12 -0
- package/dist/reactors/IReactorBuilder.d.ts.map +1 -0
- package/dist/reactors/IReactorBuilder.js +4 -0
- package/dist/reactors/IReactorBuilder.js.map +1 -0
- package/dist/reactors/IReactorDefinition.d.ts +14 -0
- package/dist/reactors/IReactorDefinition.d.ts.map +1 -0
- package/dist/reactors/IReactorDefinition.js +4 -0
- package/dist/reactors/IReactorDefinition.js.map +1 -0
- package/dist/reactors/IReactorDefinitionBuilder.d.ts +9 -0
- package/dist/reactors/IReactorDefinitionBuilder.d.ts.map +1 -0
- package/dist/reactors/IReactorDefinitionBuilder.js +4 -0
- package/dist/reactors/IReactorDefinitionBuilder.js.map +1 -0
- package/dist/reactors/IReactors.d.ts +21 -10
- package/dist/reactors/IReactors.d.ts.map +1 -1
- package/dist/reactors/ReactorBuilder.d.ts +32 -0
- package/dist/reactors/ReactorBuilder.d.ts.map +1 -0
- package/dist/reactors/ReactorBuilder.js +91 -0
- package/dist/reactors/ReactorBuilder.js.map +1 -0
- package/dist/reactors/ReactorCallback.d.ts +4 -0
- package/dist/reactors/ReactorCallback.d.ts.map +1 -0
- package/dist/reactors/ReactorCallback.js +4 -0
- package/dist/reactors/ReactorCallback.js.map +1 -0
- package/dist/reactors/ReactorEvent.d.ts +7 -0
- package/dist/reactors/ReactorEvent.d.ts.map +1 -0
- package/dist/reactors/ReactorEvent.js +4 -0
- package/dist/reactors/ReactorEvent.js.map +1 -0
- package/dist/reactors/ReactorObservation.d.ts +21 -0
- package/dist/reactors/ReactorObservation.d.ts.map +1 -0
- package/dist/reactors/ReactorObservation.js +43 -0
- package/dist/reactors/ReactorObservation.js.map +1 -0
- package/dist/reactors/ReactorObservationTarget.d.ts +4 -1
- package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -1
- package/dist/reactors/ReactorPageDispatcher.d.ts +6 -0
- package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -1
- package/dist/reactors/ReactorPageDispatcher.js +96 -51
- package/dist/reactors/ReactorPageDispatcher.js.map +1 -1
- package/dist/reactors/ReactorRegistration.d.ts +14 -0
- package/dist/reactors/ReactorRegistration.d.ts.map +1 -0
- package/dist/reactors/ReactorRegistration.js +4 -0
- package/dist/reactors/ReactorRegistration.js.map +1 -0
- package/dist/reactors/ReactorRegistrationKind.d.ts +7 -0
- package/dist/reactors/ReactorRegistrationKind.d.ts.map +1 -0
- package/dist/reactors/ReactorRegistrationKind.js +10 -0
- package/dist/reactors/ReactorRegistrationKind.js.map +1 -0
- package/dist/reactors/ReactorRegistrations.d.ts +17 -0
- package/dist/reactors/ReactorRegistrations.d.ts.map +1 -0
- package/dist/reactors/ReactorRegistrations.js +42 -0
- package/dist/reactors/ReactorRegistrations.js.map +1 -0
- package/dist/reactors/ReactorSubscription.d.ts +4 -0
- package/dist/reactors/ReactorSubscription.d.ts.map +1 -0
- package/dist/reactors/ReactorSubscription.js +4 -0
- package/dist/reactors/ReactorSubscription.js.map +1 -0
- package/dist/reactors/Reactors.d.ts +31 -38
- package/dist/reactors/Reactors.d.ts.map +1 -1
- package/dist/reactors/Reactors.js +143 -274
- package/dist/reactors/Reactors.js.map +1 -1
- package/dist/reactors/WaitTillSubscribedOptions.d.ts +7 -0
- package/dist/reactors/WaitTillSubscribedOptions.d.ts.map +1 -0
- package/dist/reactors/WaitTillSubscribedOptions.js +4 -0
- package/dist/reactors/WaitTillSubscribedOptions.js.map +1 -0
- package/dist/reactors/index.d.ts +5 -0
- package/dist/reactors/index.d.ts.map +1 -1
- package/dist/reactors/index.js.map +1 -1
- package/dist/reactors/prepareReactor.d.ts +34 -0
- package/dist/reactors/prepareReactor.d.ts.map +1 -0
- package/dist/reactors/prepareReactor.js +75 -0
- package/dist/reactors/prepareReactor.js.map +1 -0
- package/dist/reactors/waitTillSubscribed.d.ts +5 -0
- package/dist/reactors/waitTillSubscribed.d.ts.map +1 -0
- package/dist/reactors/waitTillSubscribed.js +29 -0
- package/dist/reactors/waitTillSubscribed.js.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.d.ts +145 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.d.ts.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.js +142 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.js.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.d.ts +24 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.d.ts.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.js +34 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.js.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.d.ts +7 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.d.ts.map +1 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.js +33 -0
- package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.js.map +1 -0
- package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js +1 -1
- package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/reactors/AsyncQueue.ts +41 -0
- package/reactors/IReactorBuilder.ts +15 -0
- package/reactors/IReactorDefinition.ts +17 -0
- package/reactors/IReactorDefinitionBuilder.ts +12 -0
- package/reactors/IReactors.ts +25 -10
- package/reactors/ReactorBuilder.ts +98 -0
- package/reactors/ReactorCallback.ts +7 -0
- package/reactors/ReactorEvent.ts +10 -0
- package/reactors/ReactorObservation.ts +45 -0
- package/reactors/ReactorObservationTarget.ts +4 -1
- package/reactors/ReactorPageDispatcher.ts +98 -54
- package/reactors/ReactorRegistration.ts +11 -0
- package/reactors/ReactorRegistrationKind.ts +9 -0
- package/reactors/ReactorRegistrations.ts +45 -0
- package/reactors/ReactorSubscription.ts +7 -0
- package/reactors/Reactors.ts +156 -310
- package/reactors/WaitTillSubscribedOptions.ts +9 -0
- package/reactors/for_Reactors/given/runtime_reactors.fixture.ts +50 -0
- package/reactors/for_Reactors/when_a_class_reactor_fails_to_restart.spec.ts +67 -0
- package/reactors/for_Reactors/when_a_class_reactor_fails_to_start.spec.ts +80 -0
- package/reactors/for_Reactors/when_class_delivery_is_unregistered.spec.ts +62 -0
- package/reactors/for_Reactors/when_defining_runtime_reactors.spec.ts +77 -0
- package/reactors/for_Reactors/when_dispatching_runtime_reactors.spec.ts +94 -0
- package/reactors/for_Reactors/when_registering_runtime_reactors.spec.ts +102 -0
- package/reactors/for_Reactors/when_stopping_runtime_reactors.spec.ts +160 -0
- package/reactors/for_Reactors/when_using_the_default_artifacts_provider.spec.ts +80 -0
- package/reactors/for_Reactors/when_waiting_till_subscribed.spec.ts +65 -0
- package/reactors/index.ts +5 -0
- package/reactors/prepareReactor.ts +79 -0
- package/reactors/waitTillSubscribed.ts +29 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.ts +71 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.ts +38 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.ts +36 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/with_a_fluent_projection.spec.ts +40 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/with_legacy_decorators.legacy.spec.ts +50 -0
- package/testing/for_ReadModelScenario/when_subtracting_with_children/with_standard_decorators.standard.spec.ts +51 -0
- package/testing/projections/ProjectionArithmeticChildrenCapabilities.ts +1 -1
- package/testing/projections/for_ProjectionCapabilities/when_validating_add_with_children.spec.ts +1 -1
- package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +11 -9
- package/testing/projections/for_ProjectionCapabilities/when_validating_subtract_with_children.spec.ts +105 -0
|
@@ -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
|
+
}
|
package/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.ts
ADDED
|
@@ -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('Subtracted')
|
|
12
|
+
export class Subtracted {
|
|
13
|
+
@field(Number) readonly amount: number;
|
|
14
|
+
constructor(amount: number) { this.amount = amount; }
|
|
15
|
+
}
|
|
16
|
+
@eventType('TotalSubtracted')
|
|
17
|
+
class TotalSubtracted {
|
|
18
|
+
@field(Number) readonly total: number;
|
|
19
|
+
constructor(total: number) { this.total = total; }
|
|
20
|
+
}
|
|
21
|
+
@eventType('UnderscoreSubtracted')
|
|
22
|
+
class UnderscoreSubtracted {
|
|
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.subtract(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, model: Totals, artifacts, compile: () => new ProjectionDefinitionCompiler(artifacts, 'test').compile([TotalsProjection], []) };
|
|
65
|
+
}
|
|
66
|
+
export const variants = [
|
|
67
|
+
variant('subtract-children-lifecycle', Subtracted, event => event.amount),
|
|
68
|
+
variant('subtract-children-same-property', TotalSubtracted, event => event.total),
|
|
69
|
+
variant('subtract-children-leading-underscore', UnderscoreSubtracted, 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 { Subtracted, ItemChanged, ItemRemoved, Removed } from './compiled_projection.js';
|
|
6
|
+
|
|
7
|
+
type SubtractedParent = { id: string; total: number; items: Array<{ itemId: string; name: string }> };
|
|
8
|
+
|
|
9
|
+
export function history(subtract: (amount: number) => object = amount => new Subtracted(amount)) {
|
|
10
|
+
return [
|
|
11
|
+
{ source: 'A', event: subtract(2.5) }, { source: 'A', event: subtract(-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: subtract(0) },
|
|
14
|
+
{ source: 'B', event: subtract(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: subtract(4.5) },
|
|
17
|
+
{ source: 'A', event: new ItemChanged('new', 'recreated') }
|
|
18
|
+
];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function lifecycle<T extends SubtractedParent>(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,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 { readFileSync } from 'node:fs';
|
|
5
|
+
import { JsonSerializer } from '@cratis/fundamentals';
|
|
6
|
+
import { chai, type Assertion } from 'vitest';
|
|
7
|
+
import { getEventTypeMetadata } from '../../../../events/eventTypeDecorator.js';
|
|
8
|
+
import type { compile } from './compiled_projection.js';
|
|
9
|
+
import { history } from './lifecycle.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
function should(value: unknown): Assertion { return (value as { should: Assertion }).should; }
|
|
13
|
+
|
|
14
|
+
export function assertOracleInput(candidate: { name: string; event: new (amount: number) => object; compile: typeof compile }) {
|
|
15
|
+
const fixture = JSON.parse(readFileSync(new URL(`../../../projections/fixtures/${candidate.name}.json`, import.meta.url), 'utf8'));
|
|
16
|
+
const compiled = candidate.compile();
|
|
17
|
+
const { LastUpdated, ...wire } = compiled.definitions[0];
|
|
18
|
+
should(LastUpdated).deep.equal(fixture.compilerLastUpdated);
|
|
19
|
+
should(JSON.parse(JSON.stringify({ ...wire, NoAutoMapProperties: wire.NoAutoMapProperties ?? [] }))).deep.equal(fixture.wireDefinition);
|
|
20
|
+
should(JSON.parse(compiled.readModels[0].Schema)).deep.equal(fixture.readModel.schema);
|
|
21
|
+
const schemas = [...compiled.eventSchemas.get(compiled.definitions[0])!.values()].map(entry => {
|
|
22
|
+
should(entry.eventType.Tombstone).be.false;
|
|
23
|
+
const { Tombstone: _falseFlag, ...eventType } = entry.eventType;
|
|
24
|
+
return { ...entry, eventType };
|
|
25
|
+
});
|
|
26
|
+
should(schemas).deep.equal(fixture.eventSchemas);
|
|
27
|
+
const events = history(amount => new candidate.event(amount));
|
|
28
|
+
should(events.length).equal(fixture.events.length);
|
|
29
|
+
events.forEach(({ source, event }, index) => {
|
|
30
|
+
const captured = fixture.events[index];
|
|
31
|
+
const type = getEventTypeMetadata(event.constructor)!.eventType;
|
|
32
|
+
should(captured.context.eventType).deep.equal({ Id: type.id.value, Generation: type.generation.value });
|
|
33
|
+
should(captured.context.eventSourceId).equal(source);
|
|
34
|
+
should(captured.content).deep.equal(JSON.parse(JsonSerializer.serialize(event)));
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
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 { chai, describe, it } from 'vitest';
|
|
5
|
+
import { ReadModelScenario } from '../../ReadModelScenario.js';
|
|
6
|
+
import { artifacts, Totals, variants } from './given/compiled_projection.js';
|
|
7
|
+
import { history, lifecycle } from './given/lifecycle.js';
|
|
8
|
+
import { assertOracleInput } from './given/oracle_input.js';
|
|
9
|
+
|
|
10
|
+
chai.should();
|
|
11
|
+
describe('when subtracting with independent children through a fluent projection', () => {
|
|
12
|
+
for (const variant of variants) {
|
|
13
|
+
it(`should compile exactly the oracle input for ${variant.name}`, () => assertOracleInput(variant));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
it('should subtract fractions, negative and zero values independently of child updates and removals', async () => {
|
|
17
|
+
const result = await lifecycle(new ReadModelScenario(Totals, artifacts));
|
|
18
|
+
result.first.total.should.equal(-1.5);
|
|
19
|
+
result.first.items.should.deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
|
|
20
|
+
result.remaining.total.should.equal(-1.5);
|
|
21
|
+
result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]);
|
|
22
|
+
(result.removed === null).should.be.true;
|
|
23
|
+
result.surviving.should.deep.equal(result.other);
|
|
24
|
+
result.other.total.should.equal(-8);
|
|
25
|
+
result.recreated.total.should.equal(-4.5);
|
|
26
|
+
result.recreated.items.should.deep.equal([{ itemId: 'new', name: 'recreated' }]);
|
|
27
|
+
result.repeated.should.deep.equal(result.recreated);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
for (const variant of variants.slice(1)) {
|
|
31
|
+
it(`should subtract rather than assign for ${variant.name}`, async () => {
|
|
32
|
+
const scenario = new ReadModelScenario(Totals, variant.artifacts);
|
|
33
|
+
for (const { source, event } of history(amount => new variant.event(amount)).slice(0, 8)) {
|
|
34
|
+
scenario.given.forEventSource(source).events(event);
|
|
35
|
+
}
|
|
36
|
+
(await scenario.instanceForEventSourceId('A'))!.total.should.equal(-1.5);
|
|
37
|
+
(await scenario.instanceForEventSourceId('B'))!.total.should.equal(-8);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { ProjectionDefinitionCompiler } from '../../../projections/ProjectionDefinitionCompiler.js';
|
|
7
|
+
import { subtractFrom } from '../../../projections/modelBound/subtractFrom.js';
|
|
8
|
+
import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
|
|
9
|
+
import { removedWith } from '../../../projections/modelBound/removedWith.js';
|
|
10
|
+
import { ReadModelScenario } from '../../ReadModelScenario.js';
|
|
11
|
+
import { Subtracted, artifacts, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
|
|
12
|
+
import { lifecycle } from './given/lifecycle.js';
|
|
13
|
+
import { assertOracleInput } from './given/oracle_input.js';
|
|
14
|
+
|
|
15
|
+
chai.should();
|
|
16
|
+
@removedWith(ItemRemoved, 'itemId')
|
|
17
|
+
class Item {
|
|
18
|
+
@field(String) itemId!: string;
|
|
19
|
+
@field(String) name!: string;
|
|
20
|
+
}
|
|
21
|
+
@removedWith(Removed)
|
|
22
|
+
class Totals {
|
|
23
|
+
@field(String) id!: string;
|
|
24
|
+
@field(Number) @subtractFrom(Subtracted, 'amount') total!: number;
|
|
25
|
+
@field(Array) @childrenFrom(ItemChanged, { childType: Item, key: 'itemId', identifiedBy: 'itemId' })
|
|
26
|
+
items!: Item[];
|
|
27
|
+
}
|
|
28
|
+
const modelArtifacts = { ...artifacts, projections: [], readModels: [Totals] };
|
|
29
|
+
export const candidate = {
|
|
30
|
+
name: 'subtract-children-legacy', event: Subtracted, model: Totals, artifacts: modelArtifacts,
|
|
31
|
+
compile: () => new ProjectionDefinitionCompiler(modelArtifacts, 'test').compile([], [Totals])
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
describe('when subtracting with independent children through legacy decorators', () => {
|
|
35
|
+
it('should compile exactly the oracle input', () => assertOracleInput(candidate));
|
|
36
|
+
|
|
37
|
+
it('should preserve subtraction through child changes, removal, independent roots and parent-first recreation', async () => {
|
|
38
|
+
const result = await lifecycle(new ReadModelScenario(Totals, modelArtifacts));
|
|
39
|
+
result.first.total.should.equal(-1.5);
|
|
40
|
+
result.first.items.should.deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
|
|
41
|
+
result.remaining.total.should.equal(-1.5);
|
|
42
|
+
result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]);
|
|
43
|
+
(result.removed === null).should.be.true;
|
|
44
|
+
result.surviving.should.deep.equal(result.other);
|
|
45
|
+
result.other.total.should.equal(-8);
|
|
46
|
+
result.recreated.total.should.equal(-4.5);
|
|
47
|
+
result.recreated.items.should.deep.equal([{ itemId: 'new', name: 'recreated' }]);
|
|
48
|
+
result.repeated.should.deep.equal(result.recreated);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -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 } from '@cratis/fundamentals';
|
|
5
|
+
import { chai, describe, it, type Assertion } from 'vitest';
|
|
6
|
+
import { ProjectionDefinitionCompiler } from '../../../projections/ProjectionDefinitionCompiler.js';
|
|
7
|
+
import { subtractFrom } from '../../../projections/modelBound/subtractFrom.js';
|
|
8
|
+
import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
|
|
9
|
+
import { removedWith } from '../../../projections/modelBound/removedWith.js';
|
|
10
|
+
import { ReadModelScenario } from '../../ReadModelScenario.js';
|
|
11
|
+
import { Subtracted, artifacts, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
|
|
12
|
+
import { lifecycle } from './given/lifecycle.js';
|
|
13
|
+
import { assertOracleInput } from './given/oracle_input.js';
|
|
14
|
+
|
|
15
|
+
chai.should();
|
|
16
|
+
function should(value: unknown): Assertion { return (value as { should: Assertion }).should; }
|
|
17
|
+
@removedWith(ItemRemoved, 'itemId')
|
|
18
|
+
class Item {
|
|
19
|
+
@field(String) itemId!: string;
|
|
20
|
+
@field(String) name!: string;
|
|
21
|
+
}
|
|
22
|
+
@removedWith(Removed)
|
|
23
|
+
class Totals {
|
|
24
|
+
@field(String) id!: string;
|
|
25
|
+
@field(Number) @subtractFrom(Subtracted, 'amount') total!: number;
|
|
26
|
+
@field(Array, { genericArguments: [Item] })
|
|
27
|
+
@childrenFrom(ItemChanged, { key: 'itemId', identifiedBy: 'itemId' }) items!: Item[];
|
|
28
|
+
}
|
|
29
|
+
const modelArtifacts = { ...artifacts, projections: [], readModels: [Totals] };
|
|
30
|
+
export const candidate = {
|
|
31
|
+
name: 'subtract-children-standard', event: Subtracted, model: Totals, artifacts: modelArtifacts,
|
|
32
|
+
compile: () => new ProjectionDefinitionCompiler(modelArtifacts, 'test').compile([], [Totals])
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
describe('when subtracting with independent children through standard decorators', () => {
|
|
36
|
+
it('should compile exactly the oracle input', () => assertOracleInput(candidate));
|
|
37
|
+
|
|
38
|
+
it('should preserve subtraction through child changes, removal, independent roots and parent-first recreation', async () => {
|
|
39
|
+
const result = await lifecycle(new ReadModelScenario(Totals, modelArtifacts));
|
|
40
|
+
should(result.first.total).equal(-1.5);
|
|
41
|
+
should(result.first.items).deep.equal([{ itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }]);
|
|
42
|
+
should(result.remaining.total).equal(-1.5);
|
|
43
|
+
should(result.remaining.items).deep.equal([{ itemId: 'two', name: 'second' }]);
|
|
44
|
+
should(result.removed === null).be.true;
|
|
45
|
+
should(result.surviving).deep.equal(result.other);
|
|
46
|
+
should(result.other.total).equal(-8);
|
|
47
|
+
should(result.recreated.total).equal(-4.5);
|
|
48
|
+
should(result.recreated.items).deep.equal([{ itemId: 'new', name: 'recreated' }]);
|
|
49
|
+
should(result.repeated).deep.equal(result.recreated);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -25,7 +25,7 @@ export class ProjectionArithmeticChildrenCapabilities {
|
|
|
25
25
|
|
|
26
26
|
private static accumulator(target: JsonSchema | undefined, expression: string, from: FromRecord, require: ProjectionEventSchemaResolver['require']): boolean {
|
|
27
27
|
if (expression === '$count') return this.countTarget(target);
|
|
28
|
-
const operand = /^\$add\(([A-Za-z_][A-Za-z0-9]*)\)$/.exec(expression)?.[1];
|
|
28
|
+
const operand = /^\$(?:add|subtract)\(([A-Za-z_][A-Za-z0-9]*)\)$/.exec(expression)?.[1];
|
|
29
29
|
if (!operand || !this.unformattedNumber(target)) return false;
|
|
30
30
|
const event = require(from.Key, eventContractPath('From', from.Key));
|
|
31
31
|
return this.unformattedNumber(event.properties?.[operand]);
|
package/testing/projections/for_ProjectionCapabilities/when_validating_add_with_children.spec.ts
CHANGED
|
@@ -14,7 +14,7 @@ chai.should();
|
|
|
14
14
|
type Candidate = { compiled: ReturnType<typeof compile>; definition: ProjectionDefinition; schema: JsonSchema; operand: JsonSchema };
|
|
15
15
|
type Mutation = (candidate: Candidate) => void;
|
|
16
16
|
const boundaries: Array<[string, Mutation]> = [
|
|
17
|
-
...['$increment', '$decrement', '$
|
|
17
|
+
...['$increment', '$decrement', '$add(amount + 1)', '$add(nested.amount)', '$add($eventSourceId)',
|
|
18
18
|
'$add(1)', '$add(true)', '$add(snake_case)', '$add(missing)', '$add(amount', '$add(_snake_case)'].map(expression =>
|
|
19
19
|
[expression, ({ definition }: Candidate) => { definition.From[0].Value.Properties.total = expression; }] as [string, Mutation]),
|
|
20
20
|
...['int32', 'uint32', 'float', 'double', ''].flatMap(format => [
|
package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts
CHANGED
|
@@ -15,7 +15,7 @@ chai.should();
|
|
|
15
15
|
type Candidate = { compiled: ReturnType<typeof compile>; definition: ProjectionDefinition; schema: JsonSchema };
|
|
16
16
|
type Mutation = (candidate: Candidate) => void;
|
|
17
17
|
const boundaries: Array<[string, Mutation]> = [
|
|
18
|
-
...['$increment', '$decrement'
|
|
18
|
+
...['$increment', '$decrement'].map(expression => [expression,
|
|
19
19
|
({ definition }: Candidate) => { definition.From[0].Value.Properties.total = expression; }] as [string, Mutation]),
|
|
20
20
|
['int32 count', ({ schema }) => { schema.properties!.total = { type: 'integer', format: 'int32' }; }],
|
|
21
21
|
['float count', ({ schema }) => { schema.properties!.total = { type: 'number', format: 'float' }; }],
|
|
@@ -73,15 +73,17 @@ for (const [name, mutate] of boundaries) {
|
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
76
|
+
for (const [operation, expected] of [['add', 18000], ['subtract', -18000]] as const) {
|
|
77
|
+
describe(`when applying ${operation} to the unformatted same-name operand in the count boundary`, () => {
|
|
78
|
+
it('should admit the fixture-backed arithmetic rather than count or assign', async () => {
|
|
79
|
+
const value = candidate();
|
|
80
|
+
value.definition.From[0].Value.Properties.total = `$${operation}(total)`;
|
|
81
|
+
const processor = new ProjectionReadModelProcessor(Totals, value.compiled, value.definition);
|
|
82
|
+
await processor.process([seeded, { ...seeded, context: { ...seeded.context, sequenceNumber: 1n } }]);
|
|
83
|
+
processor.publicRead.A.total.should.equal(expected);
|
|
84
|
+
});
|
|
83
85
|
});
|
|
84
|
-
}
|
|
86
|
+
}
|
|
85
87
|
|
|
86
88
|
for (const format of [undefined, 'double']) {
|
|
87
89
|
describe(`when admitting count with ${format ?? 'unformatted number'} and typed children`, () => {
|