@cratis/chronicle 6.65.0 → 6.67.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 (137) hide show
  1. package/ArtifactRegistrationResult.ts +31 -0
  2. package/ChronicleClient.ts +4 -3
  3. package/ChronicleOptions.ts +76 -24
  4. package/EventStore.ts +31 -6
  5. package/IEventStore.ts +7 -0
  6. package/artifacts/ArtifactRegistrationAttempt.ts +50 -0
  7. package/connection/ChronicleConnection.auth.spec.ts +3 -3
  8. package/connection/ChronicleConnection.ts +7 -0
  9. package/connection/CompatibilityPreflight.ts +22 -4
  10. package/connection/for_ChronicleConnection/when_checking_compatibility/before_append.spec.ts +12 -1
  11. package/connection/for_ChronicleConnection/when_creating_clients/with_correlated_multi_host_callers.spec.ts +1 -1
  12. package/connection/for_ChronicleConnection/when_deferring_client_creation/and_connecting.spec.ts +1 -1
  13. package/connection/for_CompatibilityPreflight/when_verifying/with_concurrent_calls.spec.ts +2 -2
  14. package/connection/for_CompatibilityPreflight/when_verifying/with_kernel_versions.spec.ts +38 -0
  15. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -1
  16. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -1
  17. package/dist/ArtifactRegistrationResult.d.ts +35 -0
  18. package/dist/ArtifactRegistrationResult.d.ts.map +1 -0
  19. package/dist/ArtifactRegistrationResult.js +4 -0
  20. package/dist/ArtifactRegistrationResult.js.map +1 -0
  21. package/dist/ChronicleClient.d.ts.map +1 -1
  22. package/dist/ChronicleClient.js +4 -3
  23. package/dist/ChronicleClient.js.map +1 -1
  24. package/dist/ChronicleOptions.d.ts +22 -0
  25. package/dist/ChronicleOptions.d.ts.map +1 -1
  26. package/dist/ChronicleOptions.js +62 -24
  27. package/dist/ChronicleOptions.js.map +1 -1
  28. package/dist/EventStore.d.ts +11 -2
  29. package/dist/EventStore.d.ts.map +1 -1
  30. package/dist/EventStore.js +29 -6
  31. package/dist/EventStore.js.map +1 -1
  32. package/dist/IEventStore.d.ts +6 -0
  33. package/dist/IEventStore.d.ts.map +1 -1
  34. package/dist/artifacts/ArtifactRegistrationAttempt.d.ts +20 -0
  35. package/dist/artifacts/ArtifactRegistrationAttempt.d.ts.map +1 -0
  36. package/dist/artifacts/ArtifactRegistrationAttempt.js +47 -0
  37. package/dist/artifacts/ArtifactRegistrationAttempt.js.map +1 -0
  38. package/dist/connection/ChronicleConnection.d.ts +2 -0
  39. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  40. package/dist/connection/ChronicleConnection.js +6 -0
  41. package/dist/connection/ChronicleConnection.js.map +1 -1
  42. package/dist/connection/CompatibilityPreflight.d.ts +5 -0
  43. package/dist/connection/CompatibilityPreflight.d.ts.map +1 -1
  44. package/dist/connection/CompatibilityPreflight.js +18 -3
  45. package/dist/connection/CompatibilityPreflight.js.map +1 -1
  46. package/dist/eventSequences/EventEnrichmentContext.d.ts +15 -0
  47. package/dist/eventSequences/EventEnrichmentContext.d.ts.map +1 -0
  48. package/dist/eventSequences/EventEnrichmentContext.js +4 -0
  49. package/dist/eventSequences/EventEnrichmentContext.js.map +1 -0
  50. package/dist/eventSequences/EventEnrichmentProvider.d.ts +10 -0
  51. package/dist/eventSequences/EventEnrichmentProvider.d.ts.map +1 -0
  52. package/dist/eventSequences/EventEnrichmentProvider.js +4 -0
  53. package/dist/eventSequences/EventEnrichmentProvider.js.map +1 -0
  54. package/dist/eventSequences/EventLog.d.ts +2 -1
  55. package/dist/eventSequences/EventLog.d.ts.map +1 -1
  56. package/dist/eventSequences/EventLog.js +2 -2
  57. package/dist/eventSequences/EventLog.js.map +1 -1
  58. package/dist/eventSequences/EventSequence.d.ts +7 -1
  59. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  60. package/dist/eventSequences/EventSequence.js +40 -11
  61. package/dist/eventSequences/EventSequence.js.map +1 -1
  62. package/dist/eventSequences/IEventSequence.d.ts +2 -0
  63. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  64. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts +1 -1
  65. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts.map +1 -1
  66. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js +3 -3
  67. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js.map +1 -1
  68. package/dist/eventSequences/enrichEventContent.d.ts +5 -0
  69. package/dist/eventSequences/enrichEventContent.d.ts.map +1 -0
  70. package/dist/eventSequences/enrichEventContent.js +16 -0
  71. package/dist/eventSequences/enrichEventContent.js.map +1 -0
  72. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts +2 -2
  73. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts.map +1 -1
  74. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js +10 -3
  75. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js.map +1 -1
  76. package/dist/eventSequences/index.d.ts +2 -0
  77. package/dist/eventSequences/index.d.ts.map +1 -1
  78. package/dist/eventSequences/index.js.map +1 -1
  79. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.d.ts +13 -0
  80. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.d.ts.map +1 -0
  81. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.js +79 -0
  82. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.js.map +1 -0
  83. package/dist/index.d.ts +2 -0
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +1 -0
  86. package/dist/index.js.map +1 -1
  87. package/dist/projections/Projections.d.ts +2 -1
  88. package/dist/projections/Projections.d.ts.map +1 -1
  89. package/dist/projections/Projections.js +7 -4
  90. package/dist/projections/Projections.js.map +1 -1
  91. package/dist/projections/registerProjectionWithRetry.d.ts +4 -2
  92. package/dist/projections/registerProjectionWithRetry.d.ts.map +1 -1
  93. package/dist/projections/registerProjectionWithRetry.js +8 -4
  94. package/dist/projections/registerProjectionWithRetry.js.map +1 -1
  95. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  96. package/dist/testing/ReactorScenario.js +0 -2
  97. package/dist/testing/ReactorScenario.js.map +1 -1
  98. package/dist/transactions/UnitOfWork.d.ts +1 -0
  99. package/dist/transactions/UnitOfWork.d.ts.map +1 -1
  100. package/dist/transactions/UnitOfWork.js +17 -11
  101. package/dist/transactions/UnitOfWork.js.map +1 -1
  102. package/dist/tsconfig.tsbuildinfo +1 -1
  103. package/eventSequences/EventEnrichmentContext.ts +18 -0
  104. package/eventSequences/EventEnrichmentProvider.ts +16 -0
  105. package/eventSequences/EventLog.ts +4 -2
  106. package/eventSequences/EventSequence.ts +47 -13
  107. package/eventSequences/IEventSequence.ts +3 -0
  108. package/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.ts +3 -3
  109. package/eventSequences/enrichEventContent.ts +22 -0
  110. package/eventSequences/ensureNamedTagBatchIsSupported.ts +11 -3
  111. package/eventSequences/for_EventSequence/when_appending_named_tags/given.fixture.ts +3 -2
  112. package/eventSequences/for_EventSequence/when_appending_named_tags/with_kernel_versions.spec.ts +92 -0
  113. package/eventSequences/for_EventSequence/when_appending_named_tags/with_registered_sources.spec.ts +28 -22
  114. package/eventSequences/for_EventSequence/when_enriching_appends/from_client_options.spec.ts +64 -0
  115. package/eventSequences/for_EventSequence/when_enriching_appends/given.fixture.ts +53 -0
  116. package/eventSequences/for_EventSequence/when_enriching_appends/with_a_failing_provider.spec.ts +57 -0
  117. package/eventSequences/for_EventSequence/when_enriching_appends/with_a_pending_provider.spec.ts +58 -0
  118. package/eventSequences/for_EventSequence/when_enriching_appends/with_providers.spec.ts +66 -0
  119. package/eventSequences/for_EventSequence/when_enriching_appends/without_providers.spec.ts +25 -0
  120. package/eventSequences/index.ts +2 -0
  121. package/for_ChronicleClient/connectTimeout.spec.ts +29 -0
  122. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -1
  123. package/for_ChronicleOptions/when_configuring_the_connect_timeout/with_connect_timeout.spec.ts +23 -0
  124. package/for_EventStore/when_inspecting_registration/given/an_event_store.ts +59 -0
  125. package/for_EventStore/when_inspecting_registration/with_new_attempts.spec.ts +104 -0
  126. package/for_EventStore/when_inspecting_registration/with_projection_outcomes.spec.ts +80 -0
  127. package/for_index/when_importing_connection_helpers.spec.ts +13 -0
  128. package/index.ts +2 -0
  129. package/package.json +1 -1
  130. package/patterns/for_Patterns/when_querying_through_the_connection/after_resetting_the_channel.spec.ts +1 -1
  131. package/projections/Projections.ts +10 -4
  132. package/projections/for_registerProjectionWithRetry/when_reporting_outcomes.spec.ts +71 -0
  133. package/projections/registerProjectionWithRetry.ts +11 -5
  134. package/testing/ReactorScenario.ts +0 -3
  135. package/testing/for_ReactorScenario/when_recording_side_effects/with_named_tags.spec.ts +11 -13
  136. package/transactions/UnitOfWork.ts +18 -14
  137. package/transactions/for_UnitOfWork/when_committing_events_with_named_tags.spec.ts +87 -29
@@ -0,0 +1,59 @@
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 { vi, type Mock } from 'vitest';
5
+ import type { IEventStore } from '../../../IEventStore.js';
6
+ import { EventStore } from '../../../EventStore.js';
7
+ import { EventStoreName } from '../../../EventStoreName.js';
8
+ import { EventStoreNamespaceName } from '../../../EventStoreNamespaceName.js';
9
+ import type { ChronicleConnection } from '../../../connection/ChronicleConnection.js';
10
+ import { ConnectionLifecycle } from '../../../connection/ConnectionLifecycle.js';
11
+ import { eventType } from '../../../events/eventTypeDecorator.js';
12
+ import { fromEvent } from '../../../projections/modelBound/fromEvent.js';
13
+ import { reactor } from '../../../reactors/reactor.js';
14
+ import { reducer } from '../../../reducers/reducer.js';
15
+
16
+ @eventType('registration-item')
17
+ class Item {}
18
+ @fromEvent(Item)
19
+ class First { static readonly readModelId = 'first'; }
20
+ @fromEvent(Item)
21
+ class Second { static readonly readModelId = 'second'; }
22
+ @fromEvent(Item)
23
+ class Third { static readonly readModelId = 'third'; }
24
+ class State { total = 0; }
25
+ @reactor('observer-reactor')
26
+ class ObserverReactor {}
27
+ @reducer('observer-reducer', undefined, State)
28
+ class ObserverReducer {}
29
+
30
+ /** A real event store and the kernel operations recorded during registration. */
31
+ export interface RegistrationContext {
32
+ readonly store: EventStore;
33
+ readonly publicStore: IEventStore;
34
+ readonly registerProjection: Mock;
35
+ readonly observe: Mock;
36
+ }
37
+
38
+ /** A real event store using in-memory kernel acknowledgments, with three declared projections. */
39
+ export function an_event_store(withObservers = false): RegistrationContext {
40
+ const observe = vi.fn((_requests: unknown, options: { signal: AbortSignal }) => (async function* () {
41
+ await new Promise<void>(resolve => options.signal.addEventListener('abort', () => resolve(), { once: true }));
42
+ })());
43
+ const registerProjection = vi.fn().mockResolvedValue({});
44
+ const register = vi.fn().mockResolvedValue({});
45
+ const connection = new Proxy({}, {
46
+ get: (_target, service) => {
47
+ if (service === 'logger') return undefined;
48
+ if (service === 'projections') return { register: registerProjection };
49
+ if (service === 'reactors' || service === 'reducers') return { observe };
50
+ return new Proxy({}, { get: () => register });
51
+ }
52
+ }) as ChronicleConnection;
53
+ const store = new EventStore(new EventStoreName('store'), EventStoreNamespaceName.default, connection, new ConnectionLifecycle(), 'sink', {
54
+ eventTypes: [Item], readModels: [First, Second, Third], projections: [],
55
+ reactors: withObservers ? [ObserverReactor] : [], reducers: withObservers ? [ObserverReducer] : [],
56
+ seeders: [], constraints: [], webhooks: [], eventTypeMigrations: [], globalForHandlers: []
57
+ });
58
+ return { store, publicStore: store, registerProjection, observe };
59
+ }
@@ -0,0 +1,104 @@
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 { ChronicleClient, ChronicleOptions } from '../../index.js';
6
+ import { an_event_store } from './given/an_event_store.js';
7
+
8
+ chai.should();
9
+
10
+ describe('when artifact registration runs again', () => {
11
+ let context: ReturnType<typeof an_event_store>;
12
+ let client: ChronicleClient;
13
+ beforeEach(() => {
14
+ context = an_event_store();
15
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [] }));
16
+ });
17
+ afterEach(() => {
18
+ context.store.disposeObservations();
19
+ client.dispose();
20
+ });
21
+
22
+ it('should identify reconnect attempts and replace stale failures without mutating retained snapshots', async () => {
23
+ context.registerProjection.mockRejectedValueOnce(new Error('Invalid declaration'));
24
+ await client['registerArtifactsForStore'](context.store, 'new-store').catch(() => undefined);
25
+ const previous = context.publicStore.registrationResult!;
26
+ await client['registerArtifactsForStore'](context.store, 'session-lost');
27
+ const current = context.publicStore.registrationResult!;
28
+ current.attemptId.should.equal(previous.attemptId + 1);
29
+ current.reason.should.equal('session-lost');
30
+ current.state.should.equal('successful');
31
+ current.failures.should.deep.equal([]);
32
+ previous.state.should.equal('failed');
33
+ previous.reason.should.equal('new-store');
34
+ previous.failures.should.have.lengthOf(1);
35
+ });
36
+
37
+ it('should expose in-progress without claiming a pending declaration succeeded', async () => {
38
+ let finish!: (response: {}) => void;
39
+ let started!: () => void;
40
+ const pending = new Promise<void>(resolve => { started = resolve; });
41
+ context.registerProjection.mockImplementationOnce(() => {
42
+ started();
43
+ return new Promise(resolve => { finish = resolve; });
44
+ });
45
+ const registration = context.store.registerArtifacts();
46
+ await pending;
47
+ const snapshot = context.publicStore.registrationResult!;
48
+ snapshot.state.should.equal('in-progress');
49
+ snapshot.projections.map(outcome => outcome.state).should.deep.equal(['not-run', 'not-run', 'not-run']);
50
+ finish({});
51
+ await registration;
52
+ snapshot.state.should.equal('in-progress');
53
+ context.publicStore.registrationResult!.state.should.equal('successful');
54
+ });
55
+
56
+ it('should become partially-failed when a pending projection succeeds after a parallel registration fails', async () => {
57
+ let finish!: (response: {}) => void;
58
+ let started!: () => void;
59
+ const pending = new Promise<void>(resolve => { started = resolve; });
60
+ context.registerProjection.mockImplementationOnce(() => {
61
+ started();
62
+ return new Promise(resolve => { finish = resolve; });
63
+ });
64
+ const failure = new Error('Graph registration failed');
65
+ vi.spyOn(context.store.graphs, 'register').mockRejectedValue(failure);
66
+ const projections = vi.spyOn(context.store.projections, 'register');
67
+ const registration = context.store.registerArtifacts().catch(error => error);
68
+ await pending;
69
+ (await registration).should.equal(failure);
70
+ const snapshot = context.publicStore.registrationResult!;
71
+ snapshot.state.should.equal('failed');
72
+ snapshot.projections.map(outcome => outcome.state).should.deep.equal(['not-run', 'not-run', 'not-run']);
73
+
74
+ finish({});
75
+ await projections.mock.results[0].value;
76
+ const current = context.publicStore.registrationResult!;
77
+ current.state.should.equal('partially-failed');
78
+ current.attemptId.should.equal(snapshot.attemptId);
79
+ current.error!.should.equal(failure);
80
+ current.projections.map(outcome => outcome.state).should.deep.equal(['successful', 'successful', 'successful']);
81
+ snapshot.state.should.equal('failed');
82
+ snapshot.projections.map(outcome => outcome.state).should.deep.equal(['not-run', 'not-run', 'not-run']);
83
+ });
84
+
85
+ it('should not let a late failure from a previous attempt overwrite the current attempt', async () => {
86
+ let fail!: (error: Error) => void;
87
+ let started!: () => void;
88
+ const pending = new Promise<void>(resolve => { started = resolve; });
89
+ context.registerProjection.mockImplementationOnce(() => {
90
+ started();
91
+ return new Promise((_resolve, reject) => { fail = reject; });
92
+ });
93
+ const previous = context.store.registerArtifacts('previous').catch(error => error);
94
+ await pending;
95
+ await context.store.registerArtifacts('replacement');
96
+ fail(new Error('Late failure'));
97
+ await previous;
98
+ const current = context.publicStore.registrationResult!;
99
+ current.attemptId.should.equal(2);
100
+ current.reason.should.equal('replacement');
101
+ current.state.should.equal('successful');
102
+ current.failures.should.deep.equal([]);
103
+ });
104
+ });
@@ -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 } from 'vitest';
5
+ import type { ArtifactRegistrationResult, IEventStore } from '../../index.js';
6
+ import { an_event_store } from './given/an_event_store.js';
7
+
8
+ chai.should();
9
+
10
+ describe('when inspecting event store registration through the public API', () => {
11
+ let context: ReturnType<typeof an_event_store>;
12
+ const result = (): ArtifactRegistrationResult => context.publicStore.registrationResult!;
13
+
14
+ beforeEach(() => { context = an_event_store(); });
15
+ afterEach(() => { context.store.disposeObservations(); });
16
+
17
+ it('should allow legacy and in-process event stores to omit registration reporting', () => {
18
+ const legacy = {} as Omit<IEventStore, 'registrationResult'>;
19
+ const store: IEventStore = legacy;
20
+ (store.registrationResult === undefined).should.be.true;
21
+ });
22
+
23
+ it('should keep observer liveness unknown even after reactor and reducer streams open', async () => {
24
+ context = an_event_store(true);
25
+ await context.store.registerArtifacts();
26
+ context.observe.mock.calls.should.have.lengthOf(2);
27
+ result().state.should.equal('successful');
28
+ result().observerLiveness.should.equal('unknown');
29
+ });
30
+
31
+ it('should report not-run before the first registration attempt', () => {
32
+ result().state.should.equal('not-run');
33
+ result().attemptId.should.equal(0);
34
+ result().projections.should.deep.equal([]);
35
+ });
36
+
37
+ it('should expose successful declarations and their actual kernel responses without claiming observer liveness', async () => {
38
+ const response = {};
39
+ context.registerProjection.mockResolvedValue(response);
40
+ await context.store.registerArtifacts();
41
+ result().state.should.equal('successful');
42
+ result().projections.should.have.lengthOf(3);
43
+ result().projections.forEach(outcome => {
44
+ outcome.state.should.equal('successful');
45
+ if (outcome.state === 'successful') outcome.response.should.equal(response);
46
+ });
47
+ result().failures.should.deep.equal([]);
48
+ result().observerLiveness.should.equal('unknown');
49
+ });
50
+
51
+ it('should retain successful and failed declarations while preserving fail-fast registration', async () => {
52
+ const failure = Object.assign(new Error('Invalid declaration'), { code: 3, details: ['diagnostic'] });
53
+ context.registerProjection.mockResolvedValueOnce({}).mockRejectedValueOnce(failure);
54
+ const thrown = await context.store.registerArtifacts().catch(error => error);
55
+ thrown.message.should.equal("Failed to register projection 'second' after 1 attempt(s): Error: Invalid declaration");
56
+ result().state.should.equal('partially-failed');
57
+ result().error!.should.equal(thrown);
58
+ result().projections.map(outcome => outcome.state).should.deep.equal(['successful', 'failed', 'not-run']);
59
+ result().failures[0].identifier.should.equal('second');
60
+ result().failures[0].error!.should.equal(failure);
61
+ context.registerProjection.mock.calls.should.have.lengthOf(2);
62
+ });
63
+
64
+ it('should report failed when no projection registration succeeds', async () => {
65
+ context.registerProjection.mockRejectedValue(new Error('Invalid declaration'));
66
+ await context.store.registerArtifacts().catch(() => undefined);
67
+ result().state.should.equal('failed');
68
+ result().projections.map(outcome => outcome.state).should.deep.equal(['failed', 'not-run', 'not-run']);
69
+ result().failures.should.have.lengthOf(1);
70
+ });
71
+
72
+ it('should capture an orchestration failure even before projection registration', async () => {
73
+ const failure = new Error('Discovery failed');
74
+ context.store.eventTypes.discover = async () => { throw failure; };
75
+ const thrown = await context.store.registerArtifacts().catch(error => error);
76
+ thrown.should.equal(failure);
77
+ result().state.should.equal('failed');
78
+ result().error!.should.equal(failure);
79
+ });
80
+ });
@@ -0,0 +1,13 @@
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 { ChronicleConnectionString, ChronicleOptions } from '../index.js';
6
+
7
+ chai.should();
8
+
9
+ describe('when importing connection helpers from the package root', () => {
10
+ it('should export the connection string', () =>
11
+ ChronicleOptions.fromConnectionString(new ChronicleConnectionString('chronicle://localhost:35001'))
12
+ .connectionString.serverAddress.port.should.equal(35001));
13
+ });
package/index.ts CHANGED
@@ -34,7 +34,9 @@ export { RejectedChronicleCredentials } from './connection/RejectedChronicleCred
34
34
  export { ClientObserversRequireKeepAlive } from './connection/ClientObserversRequireKeepAlive.js';
35
35
  export type { IChronicleClient } from './IChronicleClient.js';
36
36
  export { ChronicleOptions } from './ChronicleOptions.js';
37
+ export { ChronicleConnectionString } from './connection/ChronicleConnectionString.js';
37
38
  export { EventStore } from './EventStore.js';
39
+ export type { ArtifactRegistrationResult, ArtifactRegistrationState, ProjectionRegistrationOutcome, ProjectionRegistrationResponse } from './ArtifactRegistrationResult.js';
38
40
  export type { IEventStore } from './IEventStore.js';
39
41
  export { EventStoreName } from './EventStoreName.js';
40
42
  export { EventStoreNamespaceName } from './EventStoreNamespaceName.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.65.0",
3
+ "version": "6.67.0",
4
4
  "description": "Event sourcing for TypeScript and Node.js — the idiomatic client for Cratis Chronicle, the open-source event-sourcing database",
5
5
  "author": "Cratis",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@ describe('when querying patterns through an event store after resetting its conn
25
25
  const unused = async () => { throw new Error('Unexpected RPC'); };
26
26
  server.add(ConnectionServiceDefinition, {
27
27
  ...Object.fromEntries(Object.keys(ConnectionServiceDefinition.methods).map(name => [name, unused])),
28
- checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' })
28
+ checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: '19.37.4' })
29
29
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
30
30
  server.add(PatternsDefinition, {
31
31
  allPatterns: unused, allPatternScopes: unused, matchingPatterns: unused, patternsForScope: unused,
@@ -26,6 +26,7 @@ import { ProjectionState } from './ProjectionState.js';
26
26
  import { ProjectionDefinitionCompiler } from './ProjectionDefinitionCompiler.js';
27
27
  import { ensureChildrenOrderingIsSupported } from './childrenOrderingSupport.js';
28
28
  import { registerProjectionWithRetry } from './registerProjectionWithRetry.js';
29
+ import type { ProjectionRegistrationOutcome } from '../ArtifactRegistrationResult.js';
29
30
  import type { ResolvedModelBoundMetadata } from './ResolvedModelBoundMetadata.js';
30
31
  import { UnableToQueryProjection } from './UnableToQueryProjection.js';
31
32
 
@@ -99,7 +100,7 @@ export class Projections implements IProjections {
99
100
  }
100
101
 
101
102
  /** @inheritdoc */
102
- async register(): Promise<void> {
103
+ async register(record: (outcome: ProjectionRegistrationOutcome) => void = () => {}): Promise<void> {
103
104
  if (this._declarative.size === 0 && this._modelBound.size === 0) {
104
105
  await this.discover();
105
106
  }
@@ -122,6 +123,10 @@ export class Projections implements IProjections {
122
123
  return;
123
124
  }
124
125
 
126
+ projections.forEach(projection => {
127
+ record({ identifier: String(projection.Identifier ?? '<unknown>'), state: 'not-run' });
128
+ });
129
+
125
130
  const readModels = compiled.readModels;
126
131
  if (readModels.length > 0) {
127
132
  await this._connection.readModels.registerMany({
@@ -134,7 +139,7 @@ export class Projections implements IProjections {
134
139
 
135
140
  for (const projection of projections) {
136
141
  const identifier = String(projection.Identifier ?? '<unknown>');
137
- await this.registerWithRetry(projection, identifier);
142
+ await this.registerWithRetry(projection, identifier, record);
138
143
  }
139
144
  }
140
145
 
@@ -280,8 +285,9 @@ export class Projections implements IProjections {
280
285
  return EventSequenceId.eventLog.value;
281
286
  }
282
287
 
283
- private registerWithRetry(projection: ProjectionDefinition, identifier: string): Promise<void> {
284
- return registerProjectionWithRetry(this._connection, this._eventStore, this._logger, projection, identifier);
288
+ private async registerWithRetry(projection: ProjectionDefinition, identifier: string,
289
+ record: (outcome: ProjectionRegistrationOutcome) => void): Promise<void> {
290
+ await registerProjectionWithRetry(this._connection, this._eventStore, this._logger, projection, identifier, undefined, record);
285
291
  }
286
292
 
287
293
  private resolveModelBoundMetadata(type: Constructor): ResolvedModelBoundMetadata | undefined {
@@ -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 type { ProjectionDefinition } from '@cratis/chronicle.contracts';
5
+ import { afterEach, beforeEach, chai, describe, it, vi } from 'vitest';
6
+ import type { ProjectionRegistrationOutcome } from '../../ArtifactRegistrationResult.js';
7
+ import type { ChronicleConnection } from '../../connection/ChronicleConnection.js';
8
+ import { createLogger } from '../../logging/createLogger.js';
9
+ import { registerProjectionWithRetry } from '../registerProjectionWithRetry.js';
10
+
11
+ chai.should();
12
+
13
+ describe('when reporting projection registration outcomes', () => {
14
+ let register: ReturnType<typeof vi.fn>;
15
+ let record: ReturnType<typeof vi.fn<(outcome: ProjectionRegistrationOutcome) => void>>;
16
+ let connection: ChronicleConnection;
17
+ const projection = { Identifier: 'projection' } as ProjectionDefinition;
18
+ const logger = createLogger('registration-spec');
19
+ const run = (maxAttempts?: number) => registerProjectionWithRetry(connection, 'store', logger, projection, 'projection', maxAttempts, record);
20
+
21
+ beforeEach(() => {
22
+ vi.useFakeTimers();
23
+ register = vi.fn().mockResolvedValue({});
24
+ record = vi.fn();
25
+ connection = { projections: { register } } as unknown as ChronicleConnection;
26
+ });
27
+ afterEach(() => { vi.useRealTimers(); });
28
+
29
+ it('should retain the actual response only after a transient failure recovers', async () => {
30
+ const response = {};
31
+ register.mockRejectedValueOnce(new Error('UNAVAILABLE')).mockResolvedValueOnce(response);
32
+ const registration = run();
33
+ await vi.advanceTimersByTimeAsync(1999);
34
+ register.mock.calls.should.have.lengthOf(1);
35
+ record.mock.calls.should.have.lengthOf(0);
36
+ await vi.advanceTimersByTimeAsync(1);
37
+ (await registration)!.should.equal(response);
38
+ record.mock.calls.should.deep.equal([[{ identifier: 'projection', state: 'successful', response }]]);
39
+ });
40
+
41
+ it('should preserve all five attempts and the growing delays before reporting the underlying failure', async () => {
42
+ const failure = Object.assign(new Error('UNAVAILABLE'), { code: 14 });
43
+ register.mockRejectedValue(failure);
44
+ const registration = run().catch(error => error);
45
+ for (const delay of [2000, 4000, 8000, 15000]) {
46
+ await vi.advanceTimersByTimeAsync(delay - 1);
47
+ record.mock.calls.should.have.lengthOf(0);
48
+ await vi.advanceTimersByTimeAsync(1);
49
+ }
50
+ const thrown = await registration;
51
+ thrown.message.should.equal("Failed to register projection 'projection' after 5 attempt(s): Error: UNAVAILABLE");
52
+ register.mock.calls.should.have.lengthOf(5);
53
+ record.mock.calls.should.deep.equal([[{ identifier: 'projection', state: 'failed', error: failure }]]);
54
+ });
55
+
56
+ it('should preserve immediate non-transient rejection without retrying', async () => {
57
+ const failure = new Error('Invalid declaration');
58
+ register.mockRejectedValue(failure);
59
+ const thrown = await run().catch(error => error);
60
+ thrown.message.should.equal("Failed to register projection 'projection' after 1 attempt(s): Error: Invalid declaration");
61
+ register.mock.calls.should.have.lengthOf(1);
62
+ record.mock.calls.should.deep.equal([[{ identifier: 'projection', state: 'failed', error: failure }]]);
63
+ });
64
+
65
+ it('should retain the no-attempt behavior without inventing an acknowledgment', async () => {
66
+ const response = await run(0);
67
+ (response === undefined).should.be.true;
68
+ register.mock.calls.should.have.lengthOf(0);
69
+ record.mock.calls.should.have.lengthOf(0);
70
+ });
71
+ });
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { ProjectionOwner, type ProjectionDefinition } from '@cratis/chronicle.contracts';
5
5
  import type { ChronicleConnection } from '../connection/index.js';
6
+ import type { ProjectionRegistrationOutcome, ProjectionRegistrationResponse } from '../ArtifactRegistrationResult.js';
6
7
  import type { createLogger } from '../logging/createLogger.js';
7
8
 
8
9
  /**
@@ -13,7 +14,8 @@ import type { createLogger } from '../logging/createLogger.js';
13
14
  * @param projection - The projection definition to register.
14
15
  * @param identifier - The identifier of the projection, for reporting.
15
16
  * @param maxAttempts - The number of attempts before giving up.
16
- * @returns A promise that resolves when the projection is registered.
17
+ * @param record - Receives the actual kernel response or final underlying failure.
18
+ * @returns The kernel acknowledgment, or undefined if no attempts were requested.
17
19
  */
18
20
  export async function registerProjectionWithRetry(
19
21
  connection: ChronicleConnection,
@@ -21,23 +23,26 @@ export async function registerProjectionWithRetry(
21
23
  logger: ReturnType<typeof createLogger>,
22
24
  projection: ProjectionDefinition,
23
25
  identifier: string,
24
- maxAttempts = 5
25
- ): Promise<void> {
26
+ maxAttempts = 5,
27
+ record: (outcome: ProjectionRegistrationOutcome) => void = () => {}
28
+ ): Promise<ProjectionRegistrationResponse | undefined> {
26
29
  let delay = 2000;
27
30
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
28
31
  try {
29
32
  logger.info('Registering projection', { identifier, readModel: projection.ReadModel, attempt });
30
- await connection.projections.register({
33
+ const response = await connection.projections.register({
31
34
  EventStore: eventStore,
32
35
  Owner: ProjectionOwner.PROJECTION_OWNER_Client,
33
36
  Projections: [projection]
34
37
  });
35
38
  logger.info('Projection registered successfully', { identifier });
36
- return;
39
+ record({ identifier, state: 'successful', response });
40
+ return response;
37
41
  } catch (error) {
38
42
  const msg = String(error);
39
43
  const isTransient = msg.includes('UNKNOWN') || msg.includes('UNAVAILABLE') || msg.includes('INTERNAL');
40
44
  if (!isTransient || attempt === maxAttempts) {
45
+ record({ identifier, state: 'failed', error });
41
46
  throw new Error(`Failed to register projection '${identifier}' after ${attempt} attempt(s): ${msg}`);
42
47
  }
43
48
  logger.warn('Projection registration failed with transient error, retrying', {
@@ -50,4 +55,5 @@ export async function registerProjectionWithRetry(
50
55
  delay = Math.min(delay * 2, 15000);
51
56
  }
52
57
  }
58
+ return undefined;
53
59
  }
@@ -19,7 +19,6 @@ import { getDeclaredEventStreamTypeFor, getEventStreamTypeFor } from '../events/
19
19
  import type { IEventLog } from '../eventSequences/IEventLog.js';
20
20
  import type { EventForEventSourceId } from '../eventSequences/EventForEventSourceId.js';
21
21
  import type { AppendOptions } from '../eventSequences/AppendOptions.js';
22
- import { ensureNamedTagBatchIsSupported } from '../eventSequences/ensureNamedTagBatchIsSupported.js';
23
22
  import { EventStoreName } from '../EventStoreName.js';
24
23
  import { EventStoreNamespaceName } from '../EventStoreNamespaceName.js';
25
24
  import type { IEventStore } from '../IEventStore.js';
@@ -380,8 +379,6 @@ export class ReactorScenario {
380
379
  }
381
380
  // Production validates named tags before appending, failing the delivery on an invalid tag; so does recording.
382
381
  for (const target of events) mergeNamedTags(target.namedTags);
383
- ensureNamedTagBatchIsSupported(events.some(event => mergeNamedTags(event.namedTags).length > 0),
384
- events.some(event => event.eventSource !== undefined));
385
382
  for (const target of events) {
386
383
  this._effects.push(Object.freeze({ kind: 'event', value: target.event, target, triggeringContext: context,
387
384
  handler, deliveryIndex }));
@@ -6,7 +6,6 @@ import { beforeEach, chai, describe, it } from 'vitest';
6
6
  import { eventType } from '../../../events/eventTypeDecorator.js';
7
7
  import { InvalidNamedTag } from '../../../events/InvalidNamedTag.js';
8
8
  import { NamedTag } from '../../../events/NamedTag.js';
9
- import { NamedTagsWithRegisteredEventSourceNotSupported } from '../../../eventSequences/index.js';
10
9
  import type { EventContext } from '../../../events/EventContext.js';
11
10
  import { reactor } from '../../../reactors/reactor.js';
12
11
  import { ReactorScenario } from '../../ReactorScenario.js';
@@ -86,24 +85,23 @@ describe('when recording a side effect with an invalid named tag', () => {
86
85
  (error as Error).should.be.instanceOf(InvalidNamedTag));
87
86
  });
88
87
 
89
- for (const [description, reactorType] of [
90
- ['the same entry', NamedTagRegisteredSourceReactor],
91
- ['a tagged entry before a registered entry', NamedTagCrossEntryReactor],
92
- ['a registered entry before a tagged entry', NamedTagCrossEntryReversedReactor]
88
+ for (const [description, reactorType, effectCount] of [
89
+ ['the same entry', NamedTagRegisteredSourceReactor, 1],
90
+ ['a tagged entry before a registered entry', NamedTagCrossEntryReactor, 2],
91
+ ['a registered entry before a tagged entry', NamedTagCrossEntryReversedReactor, 2]
93
92
  ] as const) {
94
93
  describe(`when recording named tags and a registered source in ${description}`, () => {
95
94
  let scenario: ReactorScenario;
96
- let error: unknown;
97
95
  beforeEach(async () => {
98
96
  scenario = new ReactorScenario(reactorType, { artifacts, constraints: 'disabled' });
99
- error = await scenario.when.forEventSource('trigger').events(new NamedTagInput()).catch(caught => caught);
97
+ await scenario.when.forEventSource('trigger').events(new NamedTagInput());
100
98
  });
101
- it('should reject with the production unsupported combination error', () =>
102
- (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
103
- it('should record an unsuccessful delivery', () => scenario.results[0].completed.should.be.false);
104
- it('should retain the rejection on the delivery result', () => scenario.results[0].error!.should.equal(error));
105
- it('should not record any returned side effect', () => scenario.sideEffects.should.have.lengthOf(0));
106
- it('should not report any produced event', () => scenario.produced.should.have.lengthOf(0));
99
+ it('should complete the delivery', () => scenario.results[0].completed.should.be.true);
100
+ it('should record every returned side effect', () => scenario.sideEffects.should.have.lengthOf(effectCount));
101
+ it('should keep the registered source on the registered effect', () =>
102
+ scenario.sideEffects.some(effect => effect.target.eventSource === 'Account').should.be.true);
103
+ it('should keep the named tags on the tagged effect', () =>
104
+ scenario.sideEffects.flatMap(effect => effect.target.namedTags ?? []).map(tag => `${tag.name}=${tag.value}`).should.deep.equal(['origin=trigger']));
107
105
  });
108
106
  }
109
107
 
@@ -108,11 +108,6 @@ export class UnitOfWork implements IUnitOfWork {
108
108
  this.throwIfCompleted();
109
109
 
110
110
  if (this._events.length > 0) {
111
- // Validate the entire commit before writing any sequence, including combinations in different groups.
112
- ensureNamedTagBatchIsSupported(
113
- this._events.some(entry => (entry.eventForEventSourceId.namedTags?.length ?? 0) > 0),
114
- this._events.some(entry => entry.eventForEventSourceId.eventSource !== undefined)
115
- );
116
111
  const resultsBySequenceNumber = new Map<number, AppendResult>();
117
112
  const eventsByEventSequence = new Map<string, EventForEventSourceIdWithSequenceNumber[]>();
118
113
 
@@ -123,15 +118,7 @@ export class UnitOfWork implements IUnitOfWork {
123
118
  eventsByEventSequence.set(key, events);
124
119
  }
125
120
 
126
- // Resolve routing and required guards for every group first: a rejection must not follow a written group.
127
- const eventSources = this._eventStore.eventSources;
128
- if (eventSources) {
129
- for (const [eventSequenceId, eventsForSequence] of eventsByEventSequence) {
130
- const events = eventsForSequence.map(_ => _.eventForEventSourceId);
131
- const explicitIds = new Set(this._concurrencyScopes.get(eventSequenceId)?.keys() ?? []);
132
- planDerivedGuards(events.map(_ => resolveBatchRouting(eventSources, _)), events, undefined, explicitIds);
133
- }
134
- }
121
+ await this.validateBatches(eventsByEventSequence);
135
122
 
136
123
  for (const [eventSequenceId, eventsForSequence] of eventsByEventSequence) {
137
124
  const sequence = this._eventStore.getEventSequence(new EventSequenceId(eventSequenceId));
@@ -179,6 +166,23 @@ export class UnitOfWork implements IUnitOfWork {
179
166
  };
180
167
  }
181
168
 
169
+ private async validateBatches(eventsByEventSequence: Map<string, EventForEventSourceIdWithSequenceNumber[]>): Promise<void> {
170
+ const hasNamedTags = this._events.some(entry => (entry.eventForEventSourceId.namedTags?.length ?? 0) > 0);
171
+ const hasRegisteredEventSource = this._events.some(entry => entry.eventForEventSourceId.eventSource !== undefined);
172
+ if (hasNamedTags && hasRegisteredEventSource) {
173
+ ensureNamedTagBatchIsSupported(true, true, await this._eventStore.eventLog.getKernelVersion?.());
174
+ }
175
+
176
+ // Resolve routing and required guards for every group first: a rejection must not follow a written group.
177
+ const eventSources = this._eventStore.eventSources;
178
+ if (!eventSources) return;
179
+ for (const [eventSequenceId, eventsForSequence] of eventsByEventSequence) {
180
+ const events = eventsForSequence.map(_ => _.eventForEventSourceId);
181
+ const explicitIds = new Set(this._concurrencyScopes.get(eventSequenceId)?.keys() ?? []);
182
+ planDerivedGuards(events.map(_ => resolveBatchRouting(eventSources, _)), events, undefined, explicitIds);
183
+ }
184
+ }
185
+
182
186
  private throwIfCompleted(): void {
183
187
  if (this._isCommitted) {
184
188
  throw new Error(`Unit of work ${this.correlationId} is already committed.`);