@cratis/chronicle 6.65.0 → 6.66.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 (70) hide show
  1. package/ChronicleClient.ts +2 -1
  2. package/ChronicleOptions.ts +65 -23
  3. package/connection/ChronicleConnection.auth.spec.ts +3 -3
  4. package/connection/ChronicleConnection.ts +7 -0
  5. package/connection/CompatibilityPreflight.ts +22 -4
  6. package/connection/for_ChronicleConnection/when_checking_compatibility/before_append.spec.ts +12 -1
  7. package/connection/for_ChronicleConnection/when_creating_clients/with_correlated_multi_host_callers.spec.ts +1 -1
  8. package/connection/for_ChronicleConnection/when_deferring_client_creation/and_connecting.spec.ts +1 -1
  9. package/connection/for_CompatibilityPreflight/when_verifying/with_concurrent_calls.spec.ts +2 -2
  10. package/connection/for_CompatibilityPreflight/when_verifying/with_kernel_versions.spec.ts +38 -0
  11. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -1
  12. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -1
  13. package/dist/ChronicleClient.d.ts.map +1 -1
  14. package/dist/ChronicleClient.js +2 -1
  15. package/dist/ChronicleClient.js.map +1 -1
  16. package/dist/ChronicleOptions.d.ts +18 -0
  17. package/dist/ChronicleOptions.d.ts.map +1 -1
  18. package/dist/ChronicleOptions.js +55 -23
  19. package/dist/ChronicleOptions.js.map +1 -1
  20. package/dist/connection/ChronicleConnection.d.ts +2 -0
  21. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  22. package/dist/connection/ChronicleConnection.js +6 -0
  23. package/dist/connection/ChronicleConnection.js.map +1 -1
  24. package/dist/connection/CompatibilityPreflight.d.ts +5 -0
  25. package/dist/connection/CompatibilityPreflight.d.ts.map +1 -1
  26. package/dist/connection/CompatibilityPreflight.js +18 -3
  27. package/dist/connection/CompatibilityPreflight.js.map +1 -1
  28. package/dist/eventSequences/EventSequence.d.ts +3 -0
  29. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  30. package/dist/eventSequences/EventSequence.js +12 -3
  31. package/dist/eventSequences/EventSequence.js.map +1 -1
  32. package/dist/eventSequences/IEventSequence.d.ts +2 -0
  33. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  34. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts +1 -1
  35. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts.map +1 -1
  36. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js +3 -3
  37. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js.map +1 -1
  38. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts +2 -2
  39. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts.map +1 -1
  40. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js +10 -3
  41. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js.map +1 -1
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +1 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  47. package/dist/testing/ReactorScenario.js +0 -2
  48. package/dist/testing/ReactorScenario.js.map +1 -1
  49. package/dist/transactions/UnitOfWork.d.ts +1 -0
  50. package/dist/transactions/UnitOfWork.d.ts.map +1 -1
  51. package/dist/transactions/UnitOfWork.js +17 -11
  52. package/dist/transactions/UnitOfWork.js.map +1 -1
  53. package/eventSequences/EventSequence.ts +14 -3
  54. package/eventSequences/IEventSequence.ts +3 -0
  55. package/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.ts +3 -3
  56. package/eventSequences/ensureNamedTagBatchIsSupported.ts +11 -3
  57. package/eventSequences/for_EventSequence/when_appending_named_tags/given.fixture.ts +3 -2
  58. package/eventSequences/for_EventSequence/when_appending_named_tags/with_kernel_versions.spec.ts +92 -0
  59. package/eventSequences/for_EventSequence/when_appending_named_tags/with_registered_sources.spec.ts +28 -22
  60. package/for_ChronicleClient/connectTimeout.spec.ts +29 -0
  61. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -1
  62. package/for_ChronicleOptions/when_configuring_the_connect_timeout/with_connect_timeout.spec.ts +23 -0
  63. package/for_index/when_importing_connection_helpers.spec.ts +13 -0
  64. package/index.ts +1 -0
  65. package/package.json +1 -1
  66. package/patterns/for_Patterns/when_querying_through_the_connection/after_resetting_the_channel.spec.ts +1 -1
  67. package/testing/ReactorScenario.ts +0 -3
  68. package/testing/for_ReactorScenario/when_recording_side_effects/with_named_tags.spec.ts +11 -13
  69. package/transactions/UnitOfWork.ts +18 -14
  70. package/transactions/for_UnitOfWork/when_committing_events_with_named_tags.spec.ts +87 -29
@@ -4,50 +4,56 @@
4
4
  import { beforeEach, chai, describe, it } from 'vitest';
5
5
  import { ConcurrencyDimensions } from '../../../eventSources/index.js';
6
6
  import { NamedTag } from '../../../events/index.js';
7
- import { NamedTagsWithRegisteredEventSourceNotSupported, type AppendOptions, type EventForEventSourceId } from '../../index.js';
7
+ import type { AppendOptions, EventForEventSourceId } from '../../index.js';
8
8
  import { Account, a_sequence, NamedTagRecorded, registered_sources } from './given.fixture.js';
9
9
 
10
10
  chai.should();
11
11
  const namedTags = [new NamedTag('batch', 'b-1')];
12
+ const tagged = [{ Name: 'batch', Value: 'b-1' }];
12
13
  const entry = (options: Partial<EventForEventSourceId> = {}): EventForEventSourceId =>
13
14
  ({ eventSourceId: 'source', event: new NamedTagRecorded(), ...options });
14
15
 
15
- const batches: Array<{ description: string; events: EventForEventSourceId[]; options?: AppendOptions }> = [
16
- { description: 'tags and a registered source on the same entry', events: [entry({ eventSource: Account, namedTags })] },
17
- { description: 'a tagged entry before an untagged registered entry', events: [entry({ namedTags }), entry({ eventSource: 'Account' })] },
18
- { description: 'an untagged registered entry before a tagged entry', events: [entry({ eventSource: 'Account' }), entry({ namedTags })] },
19
- { description: 'shared tags and a registered entry', events: [entry({ eventSource: 'Account' })], options: { namedTags } },
20
- { description: 'per-entry tags and a shared registered source', events: [entry({ namedTags })], options: { eventSource: Account } }
16
+ type WireEvent = { EventSource: string; EventSourceType: string; NamedTags: Array<{ Name: string; Value: string }> };
17
+ type Batch = { description: string; events: EventForEventSourceId[]; options?: AppendOptions; registered: boolean[]; tags: Array<typeof tagged> };
18
+
19
+ const batches: Batch[] = [
20
+ { description: 'tags and a registered source on the same entry', events: [entry({ eventSource: Account, namedTags })], registered: [true], tags: [tagged] },
21
+ { description: 'a tagged entry before an untagged registered entry', events: [entry({ namedTags }), entry({ eventSource: 'Account' })], registered: [false, true], tags: [tagged, []] },
22
+ { description: 'an untagged registered entry before a tagged entry', events: [entry({ eventSource: 'Account' }), entry({ namedTags })], registered: [true, false], tags: [[], tagged] },
23
+ { description: 'shared tags and a registered entry', events: [entry({ eventSource: 'Account' })], options: { namedTags }, registered: [true], tags: [tagged] },
24
+ { description: 'per-entry tags and a shared registered source', events: [entry({ namedTags })], options: { eventSource: Account }, registered: [true], tags: [tagged] }
21
25
  ];
22
26
 
23
27
  for (const batch of batches) {
24
28
  describe(`when appending a batch with ${batch.description}`, () => {
25
29
  let calls: ReturnType<typeof a_sequence>;
26
- let error: unknown;
30
+ let wireEvents: WireEvent[];
27
31
  beforeEach(async () => {
28
32
  calls = a_sequence(registered_sources(ConcurrencyDimensions.eventSourceId));
29
- error = await calls.sequence.appendMany(batch.events, batch.options).catch(caught => caught);
33
+ await calls.sequence.appendMany(batch.events, batch.options);
34
+ wireEvents = calls.appendManyForEventSourcesWithNamedTags.mock.calls[0][0].Events;
30
35
  });
31
- it('should reject with the typed unsupported combination error', () =>
32
- (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
33
- it('should explain the kernel limitation', () => (error as Error).message.should.contain('drops registered event source routing'));
34
- it('should link to the kernel issue', () => (error as Error).message.should.contain('https://github.com/Cratis/Chronicle/issues/4603'));
36
+ it('should send one named-tag batch', () => calls.appendManyForEventSourcesWithNamedTags.mock.calls.should.have.lengthOf(1));
35
37
  it('should not send a plain batch', () => calls.appendManyForEventSources.mock.calls.should.have.lengthOf(0));
36
- it('should not send a named-tag batch', () => calls.appendManyForEventSourcesWithNamedTags.mock.calls.should.have.lengthOf(0));
37
- it('should not read a tail to derive a guard', () => calls.tailSequenceNumber.mock.calls.should.have.lengthOf(0));
38
- it('should not fall back to single appends', () =>
39
- [...calls.append.mock.calls, ...calls.appendWithNamedTags.mock.calls].should.have.lengthOf(0));
38
+ it('should keep the registered event source on every registered event', () =>
39
+ wireEvents.map(wireEvent => wireEvent.EventSource === 'Account').should.deep.equal(batch.registered));
40
+ it('should keep the registered event source type on every registered event', () =>
41
+ wireEvents.filter((_, index) => batch.registered[index]).every(wireEvent => wireEvent.EventSourceType === 'Account').should.be.true);
42
+ it('should carry the named tags of each event', () => wireEvents.map(wireEvent => wireEvent.NamedTags).should.deep.equal(batch.tags));
40
43
  });
41
44
  }
42
45
 
43
46
  describe('when appending a same-source batch with shared named tags and registered routing', () => {
44
- let error: unknown;
47
+ let calls: ReturnType<typeof a_sequence>;
48
+ let wireEvents: WireEvent[];
45
49
  beforeEach(async () => {
46
- const calls = a_sequence(registered_sources());
47
- error = await calls.sequence.appendMany('source', [new NamedTagRecorded()], { eventSource: Account, namedTags }).catch(caught => caught);
50
+ calls = a_sequence(registered_sources());
51
+ await calls.sequence.appendMany('source', [new NamedTagRecorded(), new NamedTagRecorded()], { eventSource: Account, namedTags });
52
+ wireEvents = calls.appendManyForEventSourcesWithNamedTags.mock.calls[0][0].Events;
48
53
  });
49
- it('should reject with the typed unsupported combination error', () =>
50
- (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
54
+ it('should keep the registered event source on every event', () =>
55
+ wireEvents.map(wireEvent => wireEvent.EventSource).should.deep.equal(['Account', 'Account']));
56
+ it('should carry the shared named tags on every event', () => wireEvents.map(wireEvent => wireEvent.NamedTags).should.deep.equal([tagged, tagged]));
51
57
  });
52
58
 
53
59
  describe('when appending a registered-source batch with empty named tags', () => {
@@ -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 { describe, expect, it, vi } from 'vitest';
5
+ import { ChronicleClient } from '../ChronicleClient.js';
6
+ import { ChronicleOptions } from '../ChronicleOptions.js';
7
+
8
+ const connections = vi.hoisted(() => [] as Record<string, unknown>[]);
9
+ vi.mock('../connection/ChronicleConnection.js', () => ({
10
+ ChronicleConnection: class {
11
+ constructor(options: Record<string, unknown>) { connections.push(options); }
12
+ disconnect() {}
13
+ }
14
+ }));
15
+ vi.mock('../connection/KernelKeepAlive.js', () => ({ KernelKeepAlive: class { async start() {} } }));
16
+
17
+ describe('when creating a client with a connect timeout', () => {
18
+ it('should give the connection the default connect timeout', () => {
19
+ const client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [] }));
20
+ client.dispose();
21
+ expect(connections.at(-1)?.connectTimeout).toBe(10_000);
22
+ });
23
+
24
+ it('should give the connection the configured connect timeout', () => {
25
+ const client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { discoveryPatterns: [], connectTimeout: 1_234 }));
26
+ client.dispose();
27
+ expect(connections.at(-1)?.connectTimeout).toBe(1_234);
28
+ });
29
+ });
@@ -60,7 +60,7 @@ beforeEach(async () => {
60
60
  let connections = 0;
61
61
  server.add(ConnectionServiceDefinition, {
62
62
  ...Object.fromEntries(Object.keys(ConnectionServiceDefinition.methods).map(name => [name, unused])),
63
- checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' }),
63
+ checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: '19.37.4' }),
64
64
  connectionKeepAlive: async () => ({}),
65
65
  connect: async function* (request, callContext) {
66
66
  const first = ++connections === 1;
@@ -0,0 +1,23 @@
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 { ChronicleOptions } from '../../ChronicleOptions.js';
6
+
7
+ chai.should();
8
+
9
+ describe('when configuring the connect timeout', () => {
10
+ it('should wait 10 seconds by default', () =>
11
+ ChronicleOptions.fromConnectionString('chronicle://localhost:35000').connectTimeout.should.equal(10_000));
12
+
13
+ it('should use the configured timeout', () =>
14
+ ChronicleOptions.development({ connectTimeout: 2_500 }).connectTimeout.should.equal(2_500));
15
+
16
+ it('should accept the largest supported timeout', () =>
17
+ ChronicleOptions.development({ connectTimeout: 4_294_967_295 }).connectTimeout.should.equal(4_294_967_295));
18
+
19
+ for (const connectTimeout of [0, -1, 0.5, 4_294_967_296, Number.NaN, Number.POSITIVE_INFINITY]) {
20
+ it(`should reject ${connectTimeout}`, () =>
21
+ (() => ChronicleOptions.development({ connectTimeout })).should.throw(TypeError, 'connectTimeout'));
22
+ }
23
+ });
@@ -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,6 +34,7 @@ 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';
38
39
  export type { IEventStore } from './IEventStore.js';
39
40
  export { EventStoreName } from './EventStoreName.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.65.0",
3
+ "version": "6.66.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,
@@ -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.`);
@@ -20,8 +20,9 @@ const eventSources = {
20
20
  function a_unit_of_work() {
21
21
  const appendMany = vi.fn().mockImplementation(async (events: EventForEventSourceId[]) => events.map(() => success));
22
22
  const completed = vi.fn();
23
- const unitOfWork = new UnitOfWork(Guid.create(), completed, { eventSources, getEventSequence: () => ({ appendMany }) } as unknown as IEventStore);
24
- return { unitOfWork, appendMany, completed };
23
+ const getKernelVersion = vi.fn().mockResolvedValue('19.37.4');
24
+ const unitOfWork = new UnitOfWork(Guid.create(), completed, { eventSources, eventLog: { getKernelVersion }, getEventSequence: () => ({ appendMany }) } as unknown as IEventStore);
25
+ return { unitOfWork, appendMany, completed, getKernelVersion };
25
26
  }
26
27
 
27
28
  describe('when committing events with named tags in a unit of work', () => {
@@ -57,47 +58,37 @@ describe('when adding an event with an invalid named tag to a unit of work', ()
57
58
  for (const separateSequences of [false, true]) {
58
59
  describe(`when committing named tags and a registered source in ${separateSequences ? 'different event sequences' : 'one batch'}`, () => {
59
60
  let calls: ReturnType<typeof a_unit_of_work>;
60
- let error: unknown;
61
+ let appended: EventForEventSourceId[];
61
62
  beforeEach(async () => {
62
63
  calls = a_unit_of_work();
63
- // An otherwise valid group must not be written before a later unsupported combination is found.
64
64
  calls.unitOfWork.addEvent(EventSequenceId.eventLog, 'plain', { first: 1 });
65
65
  const sequenceId = separateSequences ? new EventSequenceId('other') : EventSequenceId.eventLog;
66
66
  calls.unitOfWork.addEvent(sequenceId, 'tagged', { second: 2 }, { namedTags: [new NamedTag('batch', 'b-1')] });
67
67
  calls.unitOfWork.addEvent(sequenceId, 'registered', { third: 3 }, { eventSource: Account });
68
- error = await calls.unitOfWork.commit().catch(caught => caught);
68
+ await calls.unitOfWork.commit();
69
+ appended = calls.appendMany.mock.calls.flatMap(call => call[0] as EventForEventSourceId[]);
69
70
  });
70
- it('should reject with the typed unsupported combination error', () =>
71
- (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
72
- it('should not write any group', () => calls.appendMany.mock.calls.should.have.lengthOf(0));
73
- it('should leave the unit of work uncompleted', () => calls.unitOfWork.isCompleted.should.be.false);
74
- it('should not invoke completion callbacks', () => calls.completed.mock.calls.should.have.lengthOf(0));
75
- it('should retain the buffered events for rollback', () => calls.unitOfWork.getEvents().should.have.lengthOf(3));
71
+ it('should write every group', () => calls.appendMany.mock.calls.should.have.lengthOf(separateSequences ? 2 : 1));
72
+ it('should append every event', () => appended.map(event => event.eventSourceId).should.deep.equal(['plain', 'tagged', 'registered']));
73
+ it('should keep the named tags on the tagged event', () =>
74
+ appended[1].namedTags!.map(tag => `${tag.name}=${tag.value}`).should.deep.equal(['batch=b-1']));
75
+ it('should keep the registered source on the registered event', () => appended[2].eventSource!.should.equal(Account));
76
+ it('should complete the unit of work', () => calls.unitOfWork.isCompleted.should.be.true);
77
+ it('should invoke completion callbacks', () => calls.completed.mock.calls.should.have.lengthOf(1));
76
78
  });
77
79
  }
78
80
 
79
- describe('when committing tags and registered sources on different event sequences', () => {
81
+ describe('when committing a registered source and named tags on one event', () => {
80
82
  let calls: ReturnType<typeof a_unit_of_work>;
81
- let error: unknown;
82
83
  beforeEach(async () => {
83
84
  calls = a_unit_of_work();
84
- calls.unitOfWork.addEvent(EventSequenceId.eventLog, 'tagged', {}, { namedTags: [new NamedTag('batch', 'b-1')] });
85
- calls.unitOfWork.addEvent(new EventSequenceId('other'), 'registered', {}, { eventSource: 'Account' });
86
- error = await calls.unitOfWork.commit().catch(caught => caught);
87
- });
88
- it('should reject the entire commit', () => (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
89
- it('should not append the first event sequence', () => calls.appendMany.mock.calls.should.have.lengthOf(0));
90
- });
91
-
92
- describe('when committing a registered source and named tags on one event', () => {
93
- let error: unknown;
94
- beforeEach(async () => {
95
- const { unitOfWork } = a_unit_of_work();
96
- unitOfWork.addEvent(EventSequenceId.eventLog, 'registered', {}, { eventSource: 'Account', namedTags: [new NamedTag('batch', 'b-1')] });
97
- error = await unitOfWork.commit().catch(caught => caught);
85
+ calls.unitOfWork.addEvent(EventSequenceId.eventLog, 'registered', {}, { eventSource: 'Account', namedTags: [new NamedTag('batch', 'b-1')] });
86
+ await calls.unitOfWork.commit();
98
87
  });
99
- it('should reject with the typed unsupported combination error', () =>
100
- (error as Error).should.be.instanceOf(NamedTagsWithRegisteredEventSourceNotSupported));
88
+ it('should append the registered source', () => calls.appendMany.mock.calls[0][0][0].eventSource.should.equal('Account'));
89
+ it('should append the named tags', () =>
90
+ calls.appendMany.mock.calls[0][0][0].namedTags.map((tag: NamedTag) => `${tag.name}=${tag.value}`).should.deep.equal(['batch=b-1']));
91
+ it('should complete the unit of work', () => calls.unitOfWork.isCompleted.should.be.true);
101
92
  });
102
93
 
103
94
  describe('when committing a registered source with an empty named tag array', () => {
@@ -110,3 +101,70 @@ describe('when committing a registered source with an empty named tag array', ()
110
101
  it('should append the registered source', () => calls.appendMany.mock.calls[0][0][0].eventSource.should.equal('Account'));
111
102
  it('should complete the unit of work', () => calls.unitOfWork.isCompleted.should.be.true);
112
103
  });
104
+
105
+ for (const version of ['19.37.4', '19.37.4-development', '19.38.0']) {
106
+ describe(`when committing named tags and a registered source on kernel ${version}`, () => {
107
+ let calls: ReturnType<typeof a_unit_of_work>;
108
+
109
+ beforeEach(async () => {
110
+ calls = a_unit_of_work();
111
+ calls.getKernelVersion.mockResolvedValue(version);
112
+ calls.unitOfWork.addEvent(EventSequenceId.eventLog, 'registered', {}, { eventSource: Account, namedTags: [new NamedTag('batch', 'b-1')] });
113
+ await calls.unitOfWork.commit();
114
+ });
115
+
116
+ it('should send the batch', () => calls.appendMany.mock.calls.should.have.lengthOf(1));
117
+ it('should preserve the registered source', () => calls.appendMany.mock.calls[0][0][0].eventSource.should.equal(Account));
118
+ it('should complete', () => calls.completed.mock.calls.should.have.lengthOf(1));
119
+ });
120
+ }
121
+
122
+ for (const version of ['19.37.3', '1.0.0', undefined, '', 'unknown']) {
123
+ for (const separateSequences of [false, true]) {
124
+ describe(`when committing named tags and a registered source in ${separateSequences ? 'different sequences' : 'one batch'} on kernel ${version ?? 'unknown'}`, () => {
125
+ let calls: ReturnType<typeof a_unit_of_work>;
126
+ let error: unknown;
127
+
128
+ beforeEach(async () => {
129
+ calls = a_unit_of_work();
130
+ calls.getKernelVersion.mockResolvedValue(version);
131
+ calls.unitOfWork.addEvent(EventSequenceId.eventLog, 'registered', {}, { eventSource: Account });
132
+ const sequenceId = separateSequences ? new EventSequenceId('other') : EventSequenceId.eventLog;
133
+ calls.unitOfWork.addEvent(sequenceId, 'tagged', {}, { namedTags: [new NamedTag('batch', 'b-1')] });
134
+ try {
135
+ await calls.unitOfWork.commit();
136
+ } catch (caught) {
137
+ error = caught;
138
+ }
139
+ });
140
+
141
+ it('should throw the public operation-specific error', () => (error instanceof NamedTagsWithRegisteredEventSourceNotSupported).should.equal(true));
142
+ it('should not write even the first group', () => calls.appendMany.mock.calls.should.have.lengthOf(0));
143
+ it('should retain all pending events', () => calls.unitOfWork.getEvents().should.have.lengthOf(2));
144
+ it('should not complete', () => calls.completed.mock.calls.should.have.lengthOf(0));
145
+ });
146
+ }
147
+
148
+ describe(`when committing unaffected batches on kernel ${version ?? 'unknown'}`, () => {
149
+ let tagged: ReturnType<typeof a_unit_of_work>;
150
+ let registered: ReturnType<typeof a_unit_of_work>;
151
+
152
+ beforeEach(async () => {
153
+ tagged = a_unit_of_work();
154
+ registered = a_unit_of_work();
155
+ tagged.getKernelVersion.mockResolvedValue(version);
156
+ registered.getKernelVersion.mockResolvedValue(version);
157
+ tagged.unitOfWork.addEvent(EventSequenceId.eventLog, 'tagged', {}, { namedTags: [new NamedTag('batch', 'b-1')] });
158
+ registered.unitOfWork.addEvent(EventSequenceId.eventLog, 'registered', {}, { eventSource: Account, namedTags: [] });
159
+ await tagged.unitOfWork.commit();
160
+ await registered.unitOfWork.commit();
161
+ });
162
+
163
+ it('should send named tags without registered sources', () => tagged.appendMany.mock.calls.should.have.lengthOf(1));
164
+ it('should send registered sources without tags', () => registered.appendMany.mock.calls.should.have.lengthOf(1));
165
+ it('should not need the kernel version for either', () => {
166
+ tagged.getKernelVersion.mock.calls.should.have.lengthOf(0);
167
+ registered.getKernelVersion.mock.calls.should.have.lengthOf(0);
168
+ });
169
+ });
170
+ }