@cratis/chronicle 6.66.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 (85) hide show
  1. package/ArtifactRegistrationResult.ts +31 -0
  2. package/ChronicleClient.ts +2 -2
  3. package/ChronicleOptions.ts +12 -2
  4. package/EventStore.ts +31 -6
  5. package/IEventStore.ts +7 -0
  6. package/artifacts/ArtifactRegistrationAttempt.ts +50 -0
  7. package/dist/ArtifactRegistrationResult.d.ts +35 -0
  8. package/dist/ArtifactRegistrationResult.d.ts.map +1 -0
  9. package/dist/ArtifactRegistrationResult.js +4 -0
  10. package/dist/ArtifactRegistrationResult.js.map +1 -0
  11. package/dist/ChronicleClient.js +2 -2
  12. package/dist/ChronicleClient.js.map +1 -1
  13. package/dist/ChronicleOptions.d.ts +4 -0
  14. package/dist/ChronicleOptions.d.ts.map +1 -1
  15. package/dist/ChronicleOptions.js +8 -2
  16. package/dist/ChronicleOptions.js.map +1 -1
  17. package/dist/EventStore.d.ts +11 -2
  18. package/dist/EventStore.d.ts.map +1 -1
  19. package/dist/EventStore.js +29 -6
  20. package/dist/EventStore.js.map +1 -1
  21. package/dist/IEventStore.d.ts +6 -0
  22. package/dist/IEventStore.d.ts.map +1 -1
  23. package/dist/artifacts/ArtifactRegistrationAttempt.d.ts +20 -0
  24. package/dist/artifacts/ArtifactRegistrationAttempt.d.ts.map +1 -0
  25. package/dist/artifacts/ArtifactRegistrationAttempt.js +47 -0
  26. package/dist/artifacts/ArtifactRegistrationAttempt.js.map +1 -0
  27. package/dist/eventSequences/EventEnrichmentContext.d.ts +15 -0
  28. package/dist/eventSequences/EventEnrichmentContext.d.ts.map +1 -0
  29. package/dist/eventSequences/EventEnrichmentContext.js +4 -0
  30. package/dist/eventSequences/EventEnrichmentContext.js.map +1 -0
  31. package/dist/eventSequences/EventEnrichmentProvider.d.ts +10 -0
  32. package/dist/eventSequences/EventEnrichmentProvider.d.ts.map +1 -0
  33. package/dist/eventSequences/EventEnrichmentProvider.js +4 -0
  34. package/dist/eventSequences/EventEnrichmentProvider.js.map +1 -0
  35. package/dist/eventSequences/EventLog.d.ts +2 -1
  36. package/dist/eventSequences/EventLog.d.ts.map +1 -1
  37. package/dist/eventSequences/EventLog.js +2 -2
  38. package/dist/eventSequences/EventLog.js.map +1 -1
  39. package/dist/eventSequences/EventSequence.d.ts +4 -1
  40. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  41. package/dist/eventSequences/EventSequence.js +28 -8
  42. package/dist/eventSequences/EventSequence.js.map +1 -1
  43. package/dist/eventSequences/enrichEventContent.d.ts +5 -0
  44. package/dist/eventSequences/enrichEventContent.d.ts.map +1 -0
  45. package/dist/eventSequences/enrichEventContent.js +16 -0
  46. package/dist/eventSequences/enrichEventContent.js.map +1 -0
  47. package/dist/eventSequences/index.d.ts +2 -0
  48. package/dist/eventSequences/index.d.ts.map +1 -1
  49. package/dist/eventSequences/index.js.map +1 -1
  50. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.d.ts +13 -0
  51. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.d.ts.map +1 -0
  52. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.js +79 -0
  53. package/dist/for_EventStore/when_inspecting_registration/given/an_event_store.js.map +1 -0
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/projections/Projections.d.ts +2 -1
  58. package/dist/projections/Projections.d.ts.map +1 -1
  59. package/dist/projections/Projections.js +7 -4
  60. package/dist/projections/Projections.js.map +1 -1
  61. package/dist/projections/registerProjectionWithRetry.d.ts +4 -2
  62. package/dist/projections/registerProjectionWithRetry.d.ts.map +1 -1
  63. package/dist/projections/registerProjectionWithRetry.js +8 -4
  64. package/dist/projections/registerProjectionWithRetry.js.map +1 -1
  65. package/dist/tsconfig.tsbuildinfo +1 -1
  66. package/eventSequences/EventEnrichmentContext.ts +18 -0
  67. package/eventSequences/EventEnrichmentProvider.ts +16 -0
  68. package/eventSequences/EventLog.ts +4 -2
  69. package/eventSequences/EventSequence.ts +33 -10
  70. package/eventSequences/enrichEventContent.ts +22 -0
  71. package/eventSequences/for_EventSequence/when_enriching_appends/from_client_options.spec.ts +64 -0
  72. package/eventSequences/for_EventSequence/when_enriching_appends/given.fixture.ts +53 -0
  73. package/eventSequences/for_EventSequence/when_enriching_appends/with_a_failing_provider.spec.ts +57 -0
  74. package/eventSequences/for_EventSequence/when_enriching_appends/with_a_pending_provider.spec.ts +58 -0
  75. package/eventSequences/for_EventSequence/when_enriching_appends/with_providers.spec.ts +66 -0
  76. package/eventSequences/for_EventSequence/when_enriching_appends/without_providers.spec.ts +25 -0
  77. package/eventSequences/index.ts +2 -0
  78. package/for_EventStore/when_inspecting_registration/given/an_event_store.ts +59 -0
  79. package/for_EventStore/when_inspecting_registration/with_new_attempts.spec.ts +104 -0
  80. package/for_EventStore/when_inspecting_registration/with_projection_outcomes.spec.ts +80 -0
  81. package/index.ts +1 -0
  82. package/package.json +1 -1
  83. package/projections/Projections.ts +10 -4
  84. package/projections/for_registerProjectionWithRetry/when_reporting_outcomes.spec.ts +71 -0
  85. package/projections/registerProjectionWithRetry.ts +11 -5
@@ -0,0 +1,53 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { vi } from 'vitest';
5
+ import { EventSequence, EventSequenceId, type EventEnrichmentProvider } from '../../index.js';
6
+ import { eventType, NamedTag } from '../../../events/index.js';
7
+ import type { ChronicleConnection } from '../../../connection/index.js';
8
+ import type { IUnitOfWorkManager } from '../../../transactions/index.js';
9
+
10
+ export class EnrichedEvent {
11
+ readonly removable = true;
12
+ readonly recordedAt = new Date('2026-01-01T00:00:00.000Z');
13
+ constructor(readonly value = 'original', readonly nested = { value: 'original' }) {}
14
+ }
15
+ eventType('enrichment-event')(EnrichedEvent);
16
+
17
+ export enum AppendMode { single, namedSingle, batch, batchForOneSource, namedBatch }
18
+ export const modes = [AppendMode.single, AppendMode.namedSingle, AppendMode.batch, AppendMode.batchForOneSource, AppendMode.namedBatch];
19
+
20
+ export function a_sequence(providers: readonly EventEnrichmentProvider[] = []) {
21
+ const single = { Response: { SequenceNumber: 0n, ConstraintViolations: [], Errors: [] } };
22
+ const batch = async (request: { Events: unknown[] }) =>
23
+ ({ Response: { SequenceNumbers: request.Events.map((_, index) => BigInt(index)), ConstraintViolations: [], Errors: [] } });
24
+ const append = vi.fn().mockResolvedValue(single);
25
+ const appendWithNamedTags = vi.fn().mockResolvedValue(single);
26
+ const appendManyForEventSources = vi.fn().mockImplementation(batch);
27
+ const appendManyForEventSourcesWithNamedTags = vi.fn().mockImplementation(batch);
28
+ const connection = { eventSequences: { append, appendWithNamedTags, appendManyForEventSources, appendManyForEventSourcesWithNamedTags } } as unknown as ChronicleConnection;
29
+ return {
30
+ sequence: new EventSequence(EventSequenceId.eventLog, 'store', 'tenant', connection, {} as IUnitOfWorkManager, undefined, undefined, undefined, providers),
31
+ calls: [append, appendWithNamedTags, appendManyForEventSources, appendManyForEventSourcesWithNamedTags]
32
+ };
33
+ }
34
+
35
+ export const correlationId = '00000000-0000-0000-0000-000000000211';
36
+
37
+ export async function append_events(sequence: EventSequence, mode: AppendMode, events = [new EnrichedEvent()]) {
38
+ const options = { correlationId, tags: ['kept'], streamType: 'orders', streamId: 'stream' };
39
+ const namedOptions = { ...options, namedTags: [new NamedTag('tenant', 'one')] };
40
+ switch (mode) {
41
+ case AppendMode.single: return sequence.append('source', events[0], options);
42
+ case AppendMode.namedSingle: return sequence.append('source', events[0], namedOptions);
43
+ case AppendMode.batch: return sequence.appendMany(events.map(event => ({ eventSourceId: 'source', event })), options);
44
+ case AppendMode.batchForOneSource: return sequence.appendMany('source', events, options);
45
+ case AppendMode.namedBatch: return sequence.appendMany(events.map(event => ({ eventSourceId: 'source', event })), namedOptions);
46
+ }
47
+ }
48
+
49
+ export function transmitted(calls: ReturnType<typeof a_sequence>['calls']) {
50
+ const request = calls.flatMap(call => call.mock.calls)[0][0];
51
+ const events: { Content: string; Tags: string[]; EventSourceId: string; EventType: { Id: string }; EventStreamId: string }[] = request.Events ?? [request];
52
+ return { request, events, contents: events.map(event => JSON.parse(event.Content) as Record<string, unknown>) };
53
+ }
@@ -0,0 +1,57 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { beforeEach, chai, describe, it, vi } from 'vitest';
5
+ import { a_sequence, append_events, AppendMode, EnrichedEvent, modes } from './given.fixture.js';
6
+
7
+ chai.should();
8
+
9
+ for (const mode of modes) {
10
+ for (const asynchronous of [false, true]) {
11
+ describe(`when a provider ${asynchronous ? 'rejects' : 'throws'} during ${AppendMode[mode]}`, () => {
12
+ let calls: ReturnType<typeof a_sequence>['calls'];
13
+ let result: PromiseSettledResult<unknown>;
14
+ let failure: Error;
15
+ let later: ReturnType<typeof vi.fn>;
16
+ beforeEach(async () => {
17
+ failure = new Error('enrichment failed');
18
+ later = vi.fn();
19
+ const fixture = a_sequence([
20
+ content => { content.enriched = true; },
21
+ () => { if (asynchronous) return Promise.reject(failure); throw failure; },
22
+ later
23
+ ]);
24
+ calls = fixture.calls;
25
+ [result] = await Promise.allSettled([append_events(fixture.sequence, mode)]);
26
+ });
27
+ it('should surface the original provider failure', () => {
28
+ result.status.should.equal('rejected');
29
+ if (result.status === 'rejected') result.reason.should.equal(failure);
30
+ });
31
+ it('should transmit nothing', () => calls.flatMap(call => call.mock.calls).should.have.lengthOf(0));
32
+ it('should not invoke later providers', () => later.mock.calls.should.have.lengthOf(0));
33
+ });
34
+ }
35
+ }
36
+
37
+ describe('when enrichment rejects on a later batch event', () => {
38
+ let calls: ReturnType<typeof a_sequence>['calls'];
39
+ let visited: string[];
40
+ let result: PromiseSettledResult<unknown>;
41
+ beforeEach(async () => {
42
+ visited = [];
43
+ const fixture = a_sequence([async content => {
44
+ visited.push(String(content.value));
45
+ await Promise.resolve();
46
+ if (content.value === 'two') throw new Error('second event failed');
47
+ content.enriched = true;
48
+ }]);
49
+ calls = fixture.calls;
50
+ [result] = await Promise.allSettled([append_events(fixture.sequence, AppendMode.batch, [
51
+ new EnrichedEvent('one'), new EnrichedEvent('two'), new EnrichedEvent('three')
52
+ ])]);
53
+ });
54
+ it('should have enriched the first event before the failure', () => visited.should.deep.equal(['one', 'two']));
55
+ it('should reject the entire append', () => result.status.should.equal('rejected'));
56
+ it('should not transmit even the successfully enriched event', () => calls.flatMap(call => call.mock.calls).should.have.lengthOf(0));
57
+ });
@@ -0,0 +1,58 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { beforeEach, chai, describe, it } from 'vitest';
5
+ import { a_sequence, append_events, AppendMode, EnrichedEvent, modes, transmitted } from './given.fixture.js';
6
+
7
+ chai.should();
8
+
9
+ for (const mode of modes) {
10
+ describe(`when a provider is pending during ${AppendMode[mode]}`, () => {
11
+ let calls: ReturnType<typeof a_sequence>['calls'];
12
+ let pending: Promise<unknown>;
13
+ let release: () => void;
14
+ let order: string[];
15
+ beforeEach(async () => {
16
+ order = [];
17
+ let started!: () => void;
18
+ const entered = new Promise<void>(resolve => { started = resolve; });
19
+ const gate = new Promise<void>(resolve => { release = resolve; });
20
+ const fixture = a_sequence([
21
+ async content => { started(); await gate; content.ready = true; order.push('first'); },
22
+ () => { order.push('second'); }
23
+ ]);
24
+ calls = fixture.calls;
25
+ pending = append_events(fixture.sequence, mode);
26
+ await entered;
27
+ });
28
+ it('should not send a request or invoke the next provider until completion', async () => {
29
+ try {
30
+ calls.flatMap(call => call.mock.calls).should.have.lengthOf(0);
31
+ order.should.have.lengthOf(0);
32
+ } finally { release(); await pending; }
33
+ });
34
+ it('should send enriched content only after completion', async () => {
35
+ release();
36
+ await pending;
37
+ transmitted(calls).contents[0].ready.should.equal(true);
38
+ });
39
+ });
40
+ }
41
+
42
+ describe('when enriching multiple batch events', () => {
43
+ let calls: ReturnType<typeof a_sequence>['calls'];
44
+ let order: string[];
45
+ beforeEach(async () => {
46
+ order = [];
47
+ const fixture = a_sequence([
48
+ async content => { await Promise.resolve(); order.push(`first ${content.value}`); content.enriched = true; },
49
+ content => { order.push(`second ${content.value}`); }
50
+ ]);
51
+ calls = fixture.calls;
52
+ await append_events(fixture.sequence, AppendMode.batch, [new EnrichedEvent('one'), new EnrichedEvent('two')]);
53
+ });
54
+ it('should run every provider in order for each event in input order', () => order.should.deep.equal([
55
+ 'first one', 'second one', 'first two', 'second two'
56
+ ]));
57
+ it('should send all enriched events together', () => transmitted(calls).contents.map(content => content.enriched).should.deep.equal([true, true]));
58
+ });
@@ -0,0 +1,66 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { beforeEach, chai, describe, it } from 'vitest';
5
+ import { EventSequenceId, type EventEnrichmentContext, type EventEnrichmentProvider } from '../../index.js';
6
+ import { a_sequence, append_events, AppendMode, correlationId, EnrichedEvent, modes, transmitted } from './given.fixture.js';
7
+
8
+ chai.should();
9
+
10
+ for (const mode of modes) {
11
+ describe(`when enriching ${AppendMode[mode]} after serialization`, () => {
12
+ let calls: ReturnType<typeof a_sequence>['calls'];
13
+ let event: EnrichedEvent;
14
+ let contexts: EventEnrichmentContext[];
15
+ let observed: Record<string, unknown>[];
16
+ let order: string[];
17
+ beforeEach(async () => {
18
+ event = new EnrichedEvent();
19
+ contexts = [];
20
+ observed = [];
21
+ order = [];
22
+ const first: EventEnrichmentProvider = async (content, context) => {
23
+ observed.push(structuredClone(content));
24
+ contexts.push(context);
25
+ order.push('first started');
26
+ await Promise.resolve();
27
+ content.added = 'from first';
28
+ (content.nested as Record<string, unknown>).value = 'changed';
29
+ delete content.removable;
30
+ order.push('first finished');
31
+ };
32
+ const second: EventEnrichmentProvider = content => {
33
+ order.push('second');
34
+ content.value = content.added;
35
+ };
36
+ const fixture = a_sequence([first, second]);
37
+ calls = fixture.calls;
38
+ await append_events(fixture.sequence, mode, [event]);
39
+ });
40
+ it('should await providers in configured order', () => order.should.deep.equal(['first started', 'first finished', 'second']));
41
+ it('should provide the serialized object rather than the event instance', () => observed.should.deep.equal([
42
+ { value: 'original', nested: { value: 'original' }, recordedAt: '2026-01-01T00:00:00.000Z', removable: true }
43
+ ]));
44
+ it('should transmit additions replacements deletions and nested mutations', () => transmitted(calls).contents.should.deep.equal([
45
+ { value: 'from first', nested: { value: 'changed' }, recordedAt: '2026-01-01T00:00:00.000Z', added: 'from first' }
46
+ ]));
47
+ it('should leave the original event unchanged', () => event.should.deep.equal(new EnrichedEvent()));
48
+ it('should provide event and append context without a wire request', () => {
49
+ const context = contexts[0];
50
+ context.event.should.equal(event);
51
+ context.eventType.id.value.should.equal('enrichment-event');
52
+ context.eventStore.should.equal('store');
53
+ context.namespace.should.equal('tenant');
54
+ context.eventSequenceId.should.equal(EventSequenceId.eventLog);
55
+ context.eventSourceId.should.equal('source');
56
+ context.correlationId.toString().should.equal(correlationId);
57
+ });
58
+ it('should preserve append metadata', () => {
59
+ const { events } = transmitted(calls);
60
+ events[0].Tags.should.deep.equal(['kept']);
61
+ events[0].EventSourceId.should.equal('source');
62
+ events[0].EventType.Id.should.equal('enrichment-event');
63
+ events[0].EventStreamId.should.equal('stream');
64
+ });
65
+ });
66
+ }
@@ -0,0 +1,25 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { beforeEach, chai, describe, it } from 'vitest';
5
+ import { JsonSerializer } from '@cratis/fundamentals';
6
+ import { a_sequence, append_events, AppendMode, EnrichedEvent, modes, transmitted } from './given.fixture.js';
7
+
8
+ chai.should();
9
+
10
+ for (const mode of modes) {
11
+ describe(`when appending ${AppendMode[mode]} without enrichment providers`, () => {
12
+ let calls: ReturnType<typeof a_sequence>['calls'];
13
+ let event: EnrichedEvent;
14
+ beforeEach(async () => {
15
+ event = new EnrichedEvent();
16
+ const fixture = a_sequence();
17
+ calls = fixture.calls;
18
+ await append_events(fixture.sequence, mode, [event]);
19
+ });
20
+ it('should preserve serialized content unchanged', () => {
21
+ transmitted(calls).events[0].Content.should.equal(JsonSerializer.serialize(event));
22
+ });
23
+ it('should transmit exactly one request', () => calls.flatMap(call => call.mock.calls).should.have.lengthOf(1));
24
+ });
25
+ }
@@ -9,6 +9,8 @@ export type { ConstraintViolation } from './ConstraintViolation.js';
9
9
  export type { AppendResult } from './AppendResult.js';
10
10
  export type { AppendedEventWithResult } from './AppendedEventWithResult.js';
11
11
  export type { AppendOptions } from './AppendOptions.js';
12
+ export type { EventEnrichmentProvider } from './EventEnrichmentProvider.js';
13
+ export type { EventEnrichmentContext } from './EventEnrichmentContext.js';
12
14
  export type { CompensateOptions } from './CompensateOptions.js';
13
15
  export { CompleteStreamError } from './CompleteStreamError.js';
14
16
  export { NamedTagsWithRegisteredEventSourceNotSupported } from './NamedTagsWithRegisteredEventSourceNotSupported.js';
@@ -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
+ });
package/index.ts CHANGED
@@ -36,6 +36,7 @@ export type { IChronicleClient } from './IChronicleClient.js';
36
36
  export { ChronicleOptions } from './ChronicleOptions.js';
37
37
  export { ChronicleConnectionString } from './connection/ChronicleConnectionString.js';
38
38
  export { EventStore } from './EventStore.js';
39
+ export type { ArtifactRegistrationResult, ArtifactRegistrationState, ProjectionRegistrationOutcome, ProjectionRegistrationResponse } from './ArtifactRegistrationResult.js';
39
40
  export type { IEventStore } from './IEventStore.js';
40
41
  export { EventStoreName } from './EventStoreName.js';
41
42
  export { EventStoreNamespaceName } from './EventStoreNamespaceName.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.66.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",
@@ -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 {