@cratis/chronicle 6.68.1 → 6.70.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 (93) hide show
  1. package/ChronicleClient.ts +1 -1
  2. package/ChronicleOptions.ts +9 -0
  3. package/EventStore.ts +6 -3
  4. package/dist/ChronicleClient.js +1 -1
  5. package/dist/ChronicleClient.js.map +1 -1
  6. package/dist/ChronicleOptions.d.ts +4 -0
  7. package/dist/ChronicleOptions.d.ts.map +1 -1
  8. package/dist/ChronicleOptions.js +5 -0
  9. package/dist/ChronicleOptions.js.map +1 -1
  10. package/dist/EventStore.d.ts +3 -1
  11. package/dist/EventStore.d.ts.map +1 -1
  12. package/dist/EventStore.js +6 -3
  13. package/dist/EventStore.js.map +1 -1
  14. package/dist/eventSequences/AppendMetricsContext.d.ts +7 -0
  15. package/dist/eventSequences/AppendMetricsContext.d.ts.map +1 -0
  16. package/dist/eventSequences/AppendMetricsContext.js +4 -0
  17. package/dist/eventSequences/AppendMetricsContext.js.map +1 -0
  18. package/dist/eventSequences/ConcurrencyScopeStrategies.d.ts +8 -0
  19. package/dist/eventSequences/ConcurrencyScopeStrategies.d.ts.map +1 -0
  20. package/dist/eventSequences/ConcurrencyScopeStrategies.js +11 -0
  21. package/dist/eventSequences/ConcurrencyScopeStrategies.js.map +1 -0
  22. package/dist/eventSequences/ConcurrencyScopeStrategy.d.ts +11 -0
  23. package/dist/eventSequences/ConcurrencyScopeStrategy.d.ts.map +1 -0
  24. package/dist/eventSequences/ConcurrencyScopeStrategy.js +4 -0
  25. package/dist/eventSequences/ConcurrencyScopeStrategy.js.map +1 -0
  26. package/dist/eventSequences/ConcurrencyScopeStrategyContext.d.ts +15 -0
  27. package/dist/eventSequences/ConcurrencyScopeStrategyContext.d.ts.map +1 -0
  28. package/dist/eventSequences/ConcurrencyScopeStrategyContext.js +4 -0
  29. package/dist/eventSequences/ConcurrencyScopeStrategyContext.js.map +1 -0
  30. package/dist/eventSequences/EventLog.d.ts +2 -1
  31. package/dist/eventSequences/EventLog.d.ts.map +1 -1
  32. package/dist/eventSequences/EventLog.js +3 -2
  33. package/dist/eventSequences/EventLog.js.map +1 -1
  34. package/dist/eventSequences/EventSequence.d.ts +3 -1
  35. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  36. package/dist/eventSequences/EventSequence.js +27 -21
  37. package/dist/eventSequences/EventSequence.js.map +1 -1
  38. package/dist/eventSequences/index.d.ts +3 -0
  39. package/dist/eventSequences/index.d.ts.map +1 -1
  40. package/dist/eventSequences/index.js +1 -0
  41. package/dist/eventSequences/index.js.map +1 -1
  42. package/dist/eventSequences/planConcurrencyScopeStrategies.d.ts +12 -0
  43. package/dist/eventSequences/planConcurrencyScopeStrategies.d.ts.map +1 -0
  44. package/dist/eventSequences/planConcurrencyScopeStrategies.js +21 -0
  45. package/dist/eventSequences/planConcurrencyScopeStrategies.js.map +1 -0
  46. package/dist/eventSequences/resolveConcurrencyScope.d.ts +7 -0
  47. package/dist/eventSequences/resolveConcurrencyScope.d.ts.map +1 -0
  48. package/dist/eventSequences/resolveConcurrencyScope.js +16 -0
  49. package/dist/eventSequences/resolveConcurrencyScope.js.map +1 -0
  50. package/dist/externalServices/ExternalServiceBuilder.d.ts +1 -1
  51. package/dist/externalServices/ExternalServiceBuilder.d.ts.map +1 -1
  52. package/dist/externalServices/ExternalServiceBuilder.js +2 -2
  53. package/dist/externalServices/ExternalServiceBuilder.js.map +1 -1
  54. package/dist/externalServices/IExternalServiceBuilder.d.ts +2 -1
  55. package/dist/externalServices/IExternalServiceBuilder.d.ts.map +1 -1
  56. package/dist/externalServices/for_ExternalServices/given/an_external_service_registration.d.ts +8 -0
  57. package/dist/externalServices/for_ExternalServices/given/an_external_service_registration.d.ts.map +1 -0
  58. package/dist/externalServices/for_ExternalServices/given/an_external_service_registration.js +20 -0
  59. package/dist/externalServices/for_ExternalServices/given/an_external_service_registration.js.map +1 -0
  60. package/dist/tsconfig.tsbuildinfo +1 -1
  61. package/dist/webhooks/IWebhookDefinitionBuilder.d.ts +2 -1
  62. package/dist/webhooks/IWebhookDefinitionBuilder.d.ts.map +1 -1
  63. package/dist/webhooks/WebhookDefinitionBuilder.d.ts +1 -1
  64. package/dist/webhooks/WebhookDefinitionBuilder.d.ts.map +1 -1
  65. package/dist/webhooks/WebhookDefinitionBuilder.js +2 -2
  66. package/dist/webhooks/WebhookDefinitionBuilder.js.map +1 -1
  67. package/dist/webhooks/for_Webhooks/given/a_webhook_registration.d.ts +8 -0
  68. package/dist/webhooks/for_Webhooks/given/a_webhook_registration.d.ts.map +1 -0
  69. package/dist/webhooks/for_Webhooks/given/a_webhook_registration.js +20 -0
  70. package/dist/webhooks/for_Webhooks/given/a_webhook_registration.js.map +1 -0
  71. package/eventSequences/AppendMetricsContext.ts +9 -0
  72. package/eventSequences/ConcurrencyScopeStrategies.ts +10 -0
  73. package/eventSequences/ConcurrencyScopeStrategy.ts +15 -0
  74. package/eventSequences/ConcurrencyScopeStrategyContext.ts +18 -0
  75. package/eventSequences/EventLog.ts +5 -2
  76. package/eventSequences/EventSequence.ts +29 -24
  77. package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/from_client_options.spec.ts +60 -0
  78. package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/given.fixture.ts +31 -0
  79. package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/strategies.spec.ts +174 -0
  80. package/eventSequences/index.ts +3 -0
  81. package/eventSequences/planConcurrencyScopeStrategies.ts +30 -0
  82. package/eventSequences/resolveConcurrencyScope.ts +23 -0
  83. package/externalServices/ExternalServiceBuilder.ts +2 -2
  84. package/externalServices/IExternalServiceBuilder.ts +2 -1
  85. package/externalServices/for_ExternalServices/given/an_external_service_registration.ts +23 -0
  86. package/externalServices/for_ExternalServices/when_registering_with_an_oauth_scope.spec.ts +42 -0
  87. package/externalServices/for_ExternalServices/when_registering_without_an_oauth_scope.spec.ts +44 -0
  88. package/package.json +1 -1
  89. package/webhooks/IWebhookDefinitionBuilder.ts +2 -1
  90. package/webhooks/WebhookDefinitionBuilder.ts +2 -2
  91. package/webhooks/for_Webhooks/given/a_webhook_registration.ts +25 -0
  92. package/webhooks/for_Webhooks/when_registering_with_an_oauth_scope.spec.ts +42 -0
  93. package/webhooks/for_Webhooks/when_registering_without_an_oauth_scope.spec.ts +43 -0
@@ -30,6 +30,7 @@ import { AppendedEventWithResult } from './AppendedEventWithResult.js';
30
30
  import { AppendOperationsBroadcaster } from './AppendOperationsBroadcaster.js';
31
31
  import { AppendOptions } from './AppendOptions.js';
32
32
  import { AppendResult } from './AppendResult.js';
33
+ import type { AppendMetricsContext } from './AppendMetricsContext.js';
33
34
  import { createAppendResult } from './createAppendResult.js';
34
35
  import { CompensateOptions } from './CompensateOptions.js';
35
36
  import { CompleteStreamError } from './CompleteStreamError.js';
@@ -57,7 +58,11 @@ import { fromContractsGuid, toContractsGuid, type Guid } from '../connection/Gui
57
58
  import { ensureCommandResponse, ensureCommandSuccess, ensureQuerySuccess, type CallResultLike } from '../connection/callResults.js';
58
59
  import type { ConcurrencyScope } from './ConcurrencyScope.js';
59
60
  import type { IEventSources } from '../eventSources/IEventSources.js';
60
- import { deriveConcurrencyScope, planDerivedGuards, resolveBatchRouting, resolveSingleRouting } from './resolveEventSourceRouting.js';
61
+ import { resolveBatchRouting, resolveSingleRouting } from './resolveEventSourceRouting.js';
62
+ import { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
63
+ import type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
64
+ import { resolveConcurrencyScope } from './resolveConcurrencyScope.js';
65
+ import { planConcurrencyScopeStrategies } from './planConcurrencyScopeStrategies.js';
61
66
  import { IUnitOfWorkManager } from '../transactions/IUnitOfWorkManager.js';
62
67
  import { beginEventImport } from '../imports/beginEventImport.js';
63
68
  import { importEvents } from '../imports/importEvents.js';
@@ -85,7 +90,8 @@ export class EventSequence implements IEventSequence {
85
90
  private readonly _resolveConstraintMessage?: (violation: ConstraintViolation) => ConstraintViolation,
86
91
  private readonly _telemetry?: ChronicleTelemetryOptions,
87
92
  private readonly _eventSources?: IEventSources,
88
- private readonly _eventEnrichmentProviders: readonly EventEnrichmentProvider[] = []
93
+ private readonly _eventEnrichmentProviders: readonly EventEnrichmentProvider[] = [],
94
+ private readonly _concurrencyScopeStrategy: ConcurrencyScopeStrategy = ConcurrencyScopeStrategies.optimistic
89
95
  ) {
90
96
  this.transactional = new TransactionalEventSequence(this, this._unitOfWorkManager);
91
97
  }
@@ -123,7 +129,7 @@ export class EventSequence implements IEventSequence {
123
129
  setSequenceNumber(span, result.sequenceNumber.value);
124
130
  span.setStatus({ code: SpanStatusCode.OK });
125
131
 
126
- this.recordAppendMetrics(result, durationInSeconds, metricAttributes, sequenceMetricAttributes);
132
+ this.recordAppendMetrics(result, { eventCount: 1, durationInSeconds, attributes: metricAttributes }, sequenceMetricAttributes);
127
133
 
128
134
  if (this.appendOperations.hasSubscribers) {
129
135
  this.appendOperations.publish([createAppendNotification(eventSourceId, event, result,
@@ -155,9 +161,9 @@ export class EventSequence implements IEventSequence {
155
161
  options?: AppendOptions
156
162
  ) {
157
163
  const { eventSourceId } = prepared;
158
- const concurrencyScope = options?.concurrencyScope ?? (routing
159
- ? await deriveConcurrencyScope(routing, eventSourceId, options?.streamId, this.tailReader)
160
- : undefined);
164
+ const concurrencyScope = await resolveConcurrencyScope(this._concurrencyScopeStrategy, options?.concurrencyScope, {
165
+ eventSourceId, events: [{ eventSourceId, event: prepared.event }], options, readTail: this.tailReader
166
+ }, routing ? { routing, streamId: options?.streamId } : undefined);
161
167
  const request = this.createAppendRequest(prepared, concurrencyScope, this.toAppendRouteFields(routing, options));
162
168
  // Named tags travel on the dedicated call so a kernel without support rejects them instead of dropping them.
163
169
  return prepared.namedTags.length === 0
@@ -203,12 +209,11 @@ export class EventSequence implements IEventSequence {
203
209
 
204
210
  private recordAppendMetrics(
205
211
  result: AppendResult,
206
- durationInSeconds: number,
207
- metricAttributes: Record<string, string>,
212
+ { eventCount, durationInSeconds, attributes }: AppendMetricsContext,
208
213
  sequenceMetricAttributes: Record<string, string>
209
214
  ): void {
210
- ChronicleConventionMetrics.eventsAppended.add(1, metricAttributes);
211
- ChronicleConventionMetrics.appendDuration.record(durationInSeconds, metricAttributes);
215
+ ChronicleConventionMetrics.eventsAppended.add(eventCount, attributes);
216
+ ChronicleConventionMetrics.appendDuration.record(durationInSeconds, attributes);
212
217
  if (result.constraintViolations.length > 0) {
213
218
  ChronicleConventionMetrics.constraintViolations.add(result.constraintViolations.length, sequenceMetricAttributes);
214
219
  }
@@ -241,8 +246,7 @@ export class EventSequence implements IEventSequence {
241
246
  }
242
247
  }
243
248
  await this.verifyNamedTagBatch(prepared, routings);
244
- const explicitIds = new Set([...concurrencyScopes].filter(([, scope]) => scope !== undefined).map(([id]) => id));
245
- const derivedGuards = planDerivedGuards(routings, eventsForEventSourceIds, appendOptions?.streamId, explicitIds);
249
+ const scopePlans = planConcurrencyScopeStrategies(this._concurrencyScopeStrategy, prepared, routings);
246
250
  const distinctEventSourceIds = [...new Set(eventsForEventSourceIds.map(_ => _.eventSourceId))];
247
251
 
248
252
  const batchMetricAttributes = this.sequenceMetricAttributes;
@@ -256,8 +260,9 @@ export class EventSequence implements IEventSequence {
256
260
  const startTime = performance.now();
257
261
  try {
258
262
  this.applyBatchRouting(wireEvents, routings);
259
- for (const [id, { routing, streamId }] of derivedGuards) {
260
- concurrencyScopes.set(id, await deriveConcurrencyScope(routing, id, streamId, this.tailReader));
263
+ for (const { eventSourceId, events, guard } of scopePlans) {
264
+ concurrencyScopes.set(eventSourceId, await resolveConcurrencyScope(this._concurrencyScopeStrategy,
265
+ concurrencyScopes.get(eventSourceId), { eventSourceId, events, options: appendOptions, readTail: this.tailReader }, guard));
261
266
  }
262
267
  const response = await this.sendAppendMany(prepared, wireEvents);
263
268
 
@@ -266,7 +271,7 @@ export class EventSequence implements IEventSequence {
266
271
  const result = this.toAppendManyResults(appendManyResponse, prepared);
267
272
  span.setStatus({ code: SpanStatusCode.OK });
268
273
 
269
- this.recordAppendManyMetrics(result, eventsForEventSourceIds.length, durationInSeconds, batchMetricAttributes);
274
+ this.recordAppendManyMetrics(result, { eventCount: eventsForEventSourceIds.length, durationInSeconds, attributes: batchMetricAttributes });
270
275
  this.publishAppendMany(prepared, result);
271
276
 
272
277
  return result;
@@ -364,21 +369,19 @@ export class EventSequence implements IEventSequence {
364
369
 
365
370
  private recordAppendManyMetrics(
366
371
  result: AppendResult[],
367
- eventCount: number,
368
- durationInSeconds: number,
369
- batchMetricAttributes: Record<string, string>
372
+ { eventCount, durationInSeconds, attributes }: AppendMetricsContext
370
373
  ): void {
371
- ChronicleConventionMetrics.batchAppendsPerformed.add(1, batchMetricAttributes);
372
- ChronicleConventionMetrics.eventsAppended.add(eventCount, batchMetricAttributes);
373
- ChronicleConventionMetrics.appendManyDuration.record(durationInSeconds, batchMetricAttributes);
374
+ ChronicleConventionMetrics.batchAppendsPerformed.add(1, attributes);
375
+ ChronicleConventionMetrics.eventsAppended.add(eventCount, attributes);
376
+ ChronicleConventionMetrics.appendManyDuration.record(durationInSeconds, attributes);
374
377
 
375
378
  const totalViolations = result.reduce((sum: number, appendResult: AppendResult) => sum + appendResult.constraintViolations.length, 0);
376
379
  if (totalViolations > 0) {
377
- ChronicleConventionMetrics.constraintViolations.add(totalViolations, batchMetricAttributes);
380
+ ChronicleConventionMetrics.constraintViolations.add(totalViolations, attributes);
378
381
  }
379
382
  const totalErrors = result.reduce((sum: number, appendResult: AppendResult) => sum + appendResult.errors.length, 0);
380
383
  if (totalErrors > 0) {
381
- ChronicleConventionMetrics.appendErrors.add(totalErrors, batchMetricAttributes);
384
+ ChronicleConventionMetrics.appendErrors.add(totalErrors, attributes);
382
385
  }
383
386
  }
384
387
 
@@ -607,7 +610,9 @@ export class EventSequence implements IEventSequence {
607
610
  response.ConcurrencyViolation
608
611
  );
609
612
  span.setStatus({ code: SpanStatusCode.OK });
610
- this.recordAppendMetrics(result, (performance.now() - startTime) / 1000, metricAttributes, this.sequenceMetricAttributes);
613
+ this.recordAppendMetrics(result, {
614
+ eventCount: 1, durationInSeconds: (performance.now() - startTime) / 1000, attributes: metricAttributes
615
+ }, this.sequenceMetricAttributes);
611
616
  return result;
612
617
  } catch (error) {
613
618
  recordSafeException(span, error);
@@ -0,0 +1,60 @@
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, chai, describe, it, vi } from 'vitest';
5
+ import { ChronicleClient, ChronicleOptions, ConcurrencyScopeStrategies, EventSequenceId } from '../../../index.js';
6
+ import { Deposited } from './given.fixture.js';
7
+
8
+ chai.should();
9
+ const transport = vi.hoisted(() => ({
10
+ register: vi.fn().mockResolvedValue({}),
11
+ append: vi.fn().mockResolvedValue({ Response: { SequenceNumber: 0n } })
12
+ }));
13
+ vi.mock('../../../connection/ChronicleConnection.js', () => ({
14
+ ChronicleConnection: class {
15
+ async resetChannel() {}
16
+ async connect() {}
17
+ async disconnect() {}
18
+ server = { getVersionInfo: transport.register };
19
+ eventStores = { ensureEventStore: transport.register };
20
+ eventTypes = { register: transport.register };
21
+ eventSources = { register: transport.register };
22
+ constraints = { register: transport.register };
23
+ projections = { register: transport.register };
24
+ readModels = { registerMany: transport.register };
25
+ webhooks = { register: transport.register };
26
+ eventSeeding = { seed: transport.register };
27
+ eventSequences = { append: transport.append };
28
+ }
29
+ }));
30
+
31
+ describe('when configuring the concurrency scope strategy through client options', () => {
32
+ let client: ChronicleClient | undefined;
33
+ afterEach(() => client?.dispose());
34
+
35
+ it('should default options to optimistic', () => {
36
+ ChronicleOptions.fromConnectionString('chronicle://localhost:35000').concurrencyScopeStrategy.should.equal(ConcurrencyScopeStrategies.optimistic);
37
+ });
38
+
39
+ for (const strategy of [ConcurrencyScopeStrategies.none, vi.fn(() => ({ sequenceNumber: 11n }))]) {
40
+ it('should carry the configured policy to the event log and later sequences', async () => {
41
+ vi.clearAllMocks();
42
+ const options = ChronicleOptions.fromConnectionString('chronicle://localhost:35000', {
43
+ skipKeepAlive: true, discoveryPatterns: [], concurrencyScopeStrategy: strategy,
44
+ clientArtifactsProvider: {
45
+ eventTypes: [], readModels: [], reactors: [], reducers: [], seeders: [],
46
+ constraints: [], projections: [], webhooks: [], eventTypeMigrations: [], globalForHandlers: []
47
+ }
48
+ });
49
+ options.concurrencyScopeStrategy.should.equal(strategy);
50
+ client = new ChronicleClient(options);
51
+ const store = await client.getEventStore('store', 'tenant');
52
+ await store.eventLog.append('source', new Deposited());
53
+ await store.getEventSequence(new EventSequenceId('custom')).append('source', new Deposited());
54
+ const expected = strategy === ConcurrencyScopeStrategies.none ? 18446744073709551615n : 11n;
55
+ transport.append.mock.calls.map(([request]) => request.ConcurrencyScope.SequenceNumber).should.deep.equal([expected, expected]);
56
+ transport.append.mock.calls.map(([request]) => request.EventSequenceId).should.deep.equal(['event-log', 'custom']);
57
+ if (typeof strategy === 'function') strategy.mock.calls.should.have.length(2);
58
+ });
59
+ }
60
+ });
@@ -0,0 +1,31 @@
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 type { ChronicleConnection } from '../../../connection/index.js';
6
+ import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
7
+ import { ConcurrencyDimensions, eventSource, eventStream, EventSources } from '../../../eventSources/index.js';
8
+ import { eventType } from '../../../events/index.js';
9
+ import type { IUnitOfWorkManager } from '../../../transactions/index.js';
10
+ import { EventSequence, EventSequenceId, type ConcurrencyScopeStrategy } from '../../index.js';
11
+
12
+ export class Deposited { constructor(readonly amount = 1) {} }
13
+ eventType('ConcurrencyStrategyDeposited')(Deposited);
14
+
15
+ @eventSource({ name: 'Account' })
16
+ @eventStream('Transactions', { concurrency: ConcurrencyDimensions.eventSourceId | ConcurrencyDimensions.eventStreamType | ConcurrencyDimensions.eventStreamId })
17
+ class AccountEventSource {}
18
+
19
+ export const routing = { eventSource: AccountEventSource, eventStream: 'Transactions', streamId: 'tx-1' };
20
+
21
+ export async function create(strategy?: ConcurrencyScopeStrategy, tail = 7n) {
22
+ const append = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['append']>[0]) => ({ Response: { SequenceNumber: 0n } }));
23
+ const appendManyForEventSources = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['appendManyForEventSources']>[0]) => ({ Response: { SequenceNumbers: [0n, 1n] } }));
24
+ const tailSequenceNumber = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['tailSequenceNumber']>[0]) => ({ Data: { SequenceNumber: tail } }));
25
+ const connection = { eventSequences: { append, appendManyForEventSources, tailSequenceNumber } } as unknown as ChronicleConnection;
26
+ const sources = new EventSources('store', connection, { eventSources: [AccountEventSource] } as unknown as IClientArtifactsProvider);
27
+ await sources.discover();
28
+ const sequence = new EventSequence(EventSequenceId.eventLog, 'store', 'ns', connection, {} as IUnitOfWorkManager,
29
+ undefined, undefined, sources, [], strategy);
30
+ return { sequence, append, appendManyForEventSources, tailSequenceNumber };
31
+ }
@@ -0,0 +1,174 @@
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, vi } from 'vitest';
5
+ import { ConcurrencyScopeStrategies, EventSequenceNumber, type ConcurrencyScopeStrategyContext } from '../../index.js';
6
+ import { create, Deposited, routing } from './given.fixture.js';
7
+
8
+ const should = chai.should();
9
+
10
+ for (const batch of [false, true]) {
11
+ const append = async (sequence: Awaited<ReturnType<typeof create>>['sequence']) => batch
12
+ ? sequence.appendMany('a', [new Deposited()], routing)
13
+ : sequence.append('a', new Deposited(), routing);
14
+
15
+ describe(`when resolving ${batch ? 'batch' : 'single'} append concurrency scopes`, () => {
16
+ it('should preserve the default scoped tail and scope when optimistic is selected', async () => {
17
+ const original = await create();
18
+ const optimistic = await create(ConcurrencyScopeStrategies.optimistic);
19
+ await append(original.sequence);
20
+ await append(optimistic.sequence);
21
+ optimistic.tailSequenceNumber.mock.calls.should.deep.equal(original.tailSequenceNumber.mock.calls);
22
+ const tail = optimistic.tailSequenceNumber.mock.calls[0][0];
23
+ tail.EventSourceId.should.equal('a');
24
+ tail.EventStreamType.should.equal('Transactions');
25
+ tail.EventStreamId.should.equal('tx-1');
26
+ tail.EventSourceType.should.equal('');
27
+ if (batch) {
28
+ optimistic.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes.should.deep.equal(
29
+ original.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes);
30
+ } else {
31
+ optimistic.append.mock.calls[0][0].ConcurrencyScope.should.deep.equal(original.append.mock.calls[0][0].ConcurrencyScope);
32
+ }
33
+ });
34
+
35
+ it('should preserve the first append guard on an empty scoped stream', async () => {
36
+ const c = await create(ConcurrencyScopeStrategies.optimistic, EventSequenceNumber.unset.value);
37
+ await append(c.sequence);
38
+ const scope = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
39
+ : c.append.mock.calls[0][0].ConcurrencyScope;
40
+ scope.ExpectsNoMatchingEvent.should.equal(true);
41
+ scope.SequenceNumber.should.equal(EventSequenceNumber.unset.value);
42
+ scope.EventStreamId.should.equal('tx-1');
43
+ });
44
+
45
+ for (const strategy of [ConcurrencyScopeStrategies.none, () => undefined, async () => undefined]) {
46
+ it('should send no check and never read the tail when the strategy returns none', async () => {
47
+ const c = await create(strategy);
48
+ await append(c.sequence);
49
+ c.tailSequenceNumber.mock.calls.should.have.length(0);
50
+ const scope = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
51
+ : c.append.mock.calls[0][0].ConcurrencyScope;
52
+ // Preserve the existing wire representation of an absent scope (the no-check sentinel).
53
+ scope.SequenceNumber.should.equal(EventSequenceNumber.unset.value);
54
+ scope.ExpectsNoMatchingEvent.should.equal(false);
55
+ scope.EventSourceId.should.equal(false);
56
+ });
57
+ }
58
+
59
+ for (const asynchronous of [false, true]) {
60
+ it(`should use a custom ${asynchronous ? 'async' : 'sync'} scope without default tail reads`, async () => {
61
+ const scope = { sequenceNumber: 3n, eventSourceId: true };
62
+ const strategy = vi.fn((context: ConcurrencyScopeStrategyContext) => {
63
+ context.eventSourceId.should.equal('a');
64
+ context.events.should.have.length(1);
65
+ context.events[0].event.should.be.instanceOf(Deposited);
66
+ context.options.should.equal(routing);
67
+ return asynchronous ? Promise.resolve(scope) : scope;
68
+ });
69
+ const c = await create(strategy);
70
+ await append(c.sequence);
71
+ strategy.mock.calls.should.have.length(1);
72
+ c.tailSequenceNumber.mock.calls.should.have.length(0);
73
+ const sent = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
74
+ : c.append.mock.calls[0][0].ConcurrencyScope;
75
+ sent.SequenceNumber.should.equal(3n);
76
+ sent.EventSourceId.should.equal(true);
77
+ });
78
+
79
+ it(`should fail closed when a custom strategy ${asynchronous ? 'rejects' : 'throws'}`, async () => {
80
+ const failure = new Error('scope unavailable');
81
+ const c = await create(() => {
82
+ if (asynchronous) return Promise.reject(failure);
83
+ throw failure;
84
+ });
85
+ let caught: unknown;
86
+ try { await append(c.sequence); } catch (error) { caught = error; }
87
+ should.equal(caught, failure);
88
+ c.append.mock.calls.should.have.length(0);
89
+ c.appendManyForEventSources.mock.calls.should.have.length(0);
90
+ });
91
+ }
92
+ });
93
+ }
94
+
95
+ describe('when explicit scopes are supplied', () => {
96
+ it('should bypass a custom strategy for a single append', async () => {
97
+ const strategy = vi.fn(() => { throw new Error('must not run'); });
98
+ const c = await create(strategy);
99
+ await c.sequence.append('a', new Deposited(), { ...routing, concurrencyScope: { sequenceNumber: 4n } });
100
+ strategy.mock.calls.should.have.length(0);
101
+ c.tailSequenceNumber.mock.calls.should.have.length(0);
102
+ c.append.mock.calls[0][0].ConcurrencyScope.SequenceNumber.should.equal(4n);
103
+ });
104
+
105
+ for (const strategy of [ConcurrencyScopeStrategies.optimistic, ConcurrencyScopeStrategies.none]) {
106
+ it('should preserve explicit scopes under built-in policies', async () => {
107
+ const c = await create(strategy);
108
+ await c.sequence.append('a', new Deposited(), { ...routing, concurrencyScope: { sequenceNumber: 4n } });
109
+ await c.sequence.appendMany('a', [new Deposited()], { ...routing, concurrencyScope: { sequenceNumber: 4n } });
110
+ c.tailSequenceNumber.mock.calls.should.have.length(0);
111
+ c.append.mock.calls[0][0].ConcurrencyScope.SequenceNumber.should.equal(4n);
112
+ c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope.SequenceNumber.should.equal(4n);
113
+ });
114
+ }
115
+
116
+ it('should resolve only unscoped ids in a mixed batch and group their events', async () => {
117
+ const strategy = vi.fn(async (context: ConcurrencyScopeStrategyContext) => {
118
+ context.events.should.have.length(2);
119
+ const tail = await context.readTail(context.eventSourceId);
120
+ return { sequenceNumber: tail.value, eventSourceId: true };
121
+ });
122
+ const c = await create(strategy);
123
+ await c.sequence.appendMany([
124
+ { eventSourceId: 'explicit', event: new Deposited() },
125
+ { eventSourceId: 'derived', event: new Deposited() },
126
+ { eventSourceId: 'derived', event: new Deposited() }
127
+ ], { ...routing, concurrencyScopes: { explicit: { sequenceNumber: 2n } } });
128
+ strategy.mock.calls.should.have.length(1);
129
+ strategy.mock.calls[0][0].eventSourceId.should.equal('derived');
130
+ const scopes = c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes;
131
+ scopes.map(entry => [entry.EventSourceId, entry.Scope.SequenceNumber]).should.deep.equal([['explicit', 2n], ['derived', 7n]]);
132
+ c.tailSequenceNumber.mock.calls.should.have.length(1);
133
+ });
134
+
135
+ it('should bypass the custom strategy when every id has an explicit shared scope', async () => {
136
+ const strategy = vi.fn(() => { throw new Error('must not run'); });
137
+ const c = await create(strategy);
138
+ await c.sequence.appendMany([
139
+ { eventSourceId: 'a', event: new Deposited() },
140
+ { eventSourceId: 'b', event: new Deposited() }
141
+ ], { ...routing, concurrencyScope: { sequenceNumber: 4n } });
142
+ strategy.mock.calls.should.have.length(0);
143
+ c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes.map(entry => entry.Scope.SequenceNumber).should.deep.equal([4n, 4n]);
144
+ });
145
+
146
+ it('should not append a partly resolved batch when a later strategy call fails', async () => {
147
+ const failure = new Error('second scope unavailable');
148
+ const c = await create(async context => {
149
+ if (context.eventSourceId === 'b') throw failure;
150
+ return { sequenceNumber: 2n };
151
+ });
152
+ let caught: unknown;
153
+ try {
154
+ await c.sequence.appendMany([
155
+ { eventSourceId: 'a', event: new Deposited() },
156
+ { eventSourceId: 'b', event: new Deposited() }
157
+ ]);
158
+ } catch (error) { caught = error; }
159
+ should.equal(caught, failure);
160
+ c.appendManyForEventSources.mock.calls.should.have.length(0);
161
+ });
162
+
163
+ it('should retain explicit ids and derive the rest using optimistic routing', async () => {
164
+ const c = await create();
165
+ await c.sequence.appendMany([
166
+ { eventSourceId: 'explicit', event: new Deposited() },
167
+ { eventSourceId: 'derived', event: new Deposited() }
168
+ ], { ...routing, concurrencyScopes: { explicit: { sequenceNumber: 2n } } });
169
+ const scopes = c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes;
170
+ scopes.map(entry => [entry.EventSourceId, entry.Scope.SequenceNumber]).should.deep.equal([['explicit', 2n], ['derived', 7n]]);
171
+ c.tailSequenceNumber.mock.calls.should.have.length(1);
172
+ c.tailSequenceNumber.mock.calls[0][0].EventSourceId.should.equal('derived');
173
+ });
174
+ });
@@ -16,6 +16,9 @@ export { CompleteStreamError } from './CompleteStreamError.js';
16
16
  export { NamedTagsWithRegisteredEventSourceNotSupported } from './NamedTagsWithRegisteredEventSourceNotSupported.js';
17
17
  export type { CompleteStreamResult } from './CompleteStreamResult.js';
18
18
  export type { ConcurrencyScope } from './ConcurrencyScope.js';
19
+ export { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
20
+ export type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
21
+ export type { ConcurrencyScopeStrategyContext } from './ConcurrencyScopeStrategyContext.js';
19
22
  export type { EventForEventSourceId } from './EventForEventSourceId.js';
20
23
  export type { WaitForCompletionResult } from './WaitForCompletionResult.js';
21
24
  export type { WaitForCompletionOptions } from './WaitForCompletionOptions.js';
@@ -0,0 +1,30 @@
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 { ResolvedEventRouting } from '../eventSources/ResolvedEventRouting.js';
5
+ import { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
6
+ import type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
7
+ import type { EventForEventSourceId } from './EventForEventSourceId.js';
8
+ import type { PreparedBatchAppend } from './PreparedBatchAppend.js';
9
+ import { planDerivedGuards, type RequiredGuard } from './resolveEventSourceRouting.js';
10
+
11
+ /** Plans one scope per event source id, retaining optimistic guard validation and tail-read order. */
12
+ export function planConcurrencyScopeStrategies(
13
+ strategy: ConcurrencyScopeStrategy,
14
+ prepared: PreparedBatchAppend,
15
+ routings: Array<ResolvedEventRouting | undefined>
16
+ ) {
17
+ const { eventsForEventSourceIds, appendOptions, concurrencyScopes } = prepared;
18
+ const explicitIds = new Set([...concurrencyScopes].filter(([, scope]) => scope !== undefined).map(([id]) => id));
19
+ const guards = strategy === ConcurrencyScopeStrategies.optimistic
20
+ ? planDerivedGuards(routings, eventsForEventSourceIds, appendOptions?.streamId, explicitIds)
21
+ : new Map<string, RequiredGuard>();
22
+ const groups = new Map<string, EventForEventSourceId[]>();
23
+ for (const entry of eventsForEventSourceIds) {
24
+ const group = groups.get(entry.eventSourceId) ?? [];
25
+ group.push(entry);
26
+ groups.set(entry.eventSourceId, group);
27
+ }
28
+ const ids = strategy === ConcurrencyScopeStrategies.optimistic ? [...guards.keys()] : [...groups.keys()];
29
+ return ids.map(eventSourceId => ({ eventSourceId, events: groups.get(eventSourceId)!, guard: guards.get(eventSourceId) }));
30
+ }
@@ -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 type { ConcurrencyScope } from './ConcurrencyScope.js';
5
+ import { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
6
+ import type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
7
+ import type { ConcurrencyScopeStrategyContext } from './ConcurrencyScopeStrategyContext.js';
8
+ import { deriveConcurrencyScope, type RequiredGuard } from './resolveEventSourceRouting.js';
9
+
10
+ /** Resolves a single or batch append's scope, always preserving an explicit caller scope. */
11
+ export async function resolveConcurrencyScope(
12
+ strategy: ConcurrencyScopeStrategy,
13
+ explicitScope: ConcurrencyScope | undefined,
14
+ context: ConcurrencyScopeStrategyContext,
15
+ guard?: RequiredGuard
16
+ ): Promise<ConcurrencyScope | undefined> {
17
+ if (explicitScope !== undefined) return explicitScope;
18
+ if (typeof strategy === 'function') return await strategy(context);
19
+ if (strategy === ConcurrencyScopeStrategies.optimistic && guard) {
20
+ return await deriveConcurrencyScope(guard.routing, context.eventSourceId, guard.streamId, context.readTail);
21
+ }
22
+ return undefined;
23
+ }
@@ -52,11 +52,11 @@ export class ExternalServiceBuilder implements IExternalServiceBuilder {
52
52
  }
53
53
 
54
54
  /** @inheritdoc */
55
- withOAuth(authority: string, clientId: string, clientSecret: string): IExternalServiceBuilder {
55
+ withOAuth(authority: string, clientId: string, clientSecret: string, scope?: string): IExternalServiceBuilder {
56
56
  this._authorization = {
57
57
  Value0: undefined,
58
58
  Value1: undefined,
59
- Value2: { Authority: authority, ClientId: clientId, ClientSecret: clientSecret, Scope: '' }
59
+ Value2: { Authority: authority, ClientId: clientId, ClientSecret: clientSecret, Scope: scope ?? '' }
60
60
  };
61
61
  return this;
62
62
  }
@@ -32,9 +32,10 @@ export interface IExternalServiceBuilder {
32
32
  * @param authority - The OAuth authority.
33
33
  * @param clientId - The OAuth client id.
34
34
  * @param clientSecret - The OAuth client secret.
35
+ * @param scope - Optional space-delimited OAuth scope.
35
36
  * @returns The builder for chaining.
36
37
  */
37
- withOAuth(authority: string, clientId: string, clientSecret: string): IExternalServiceBuilder;
38
+ withOAuth(authority: string, clientId: string, clientSecret: string, scope?: string): IExternalServiceBuilder;
38
39
 
39
40
  /**
40
41
  * Adds a header to send with every HTTP request.
@@ -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 { AddExternalServicesRequest } from '@cratis/chronicle.contracts';
5
+ import type { ChronicleConnection } from '../../../connection/index.js';
6
+ import { ExternalServices } from '../../ExternalServices.js';
7
+
8
+ export class an_external_service_registration {
9
+ sent = AddExternalServicesRequest.fromPartial({});
10
+ readonly services: ExternalServices;
11
+
12
+ constructor() {
13
+ const connection = {
14
+ externalServices: {
15
+ addExternalServices: async (request: AddExternalServicesRequest) => {
16
+ this.sent = request;
17
+ return { IsAuthorized: true, ValidationResults: [], ExceptionMessages: [] };
18
+ }
19
+ }
20
+ } as unknown as ChronicleConnection;
21
+ this.services = new ExternalServices('store', connection);
22
+ }
23
+ }
@@ -0,0 +1,42 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { AddExternalServicesRequest, OAuthAuthorization } from '@cratis/chronicle.contracts';
5
+ import { beforeEach, chai, describe, it } from 'vitest';
6
+ import type { IExternalServiceBuilder } from '../IExternalServiceBuilder.js';
7
+ import { an_external_service_registration } from './given/an_external_service_registration.js';
8
+
9
+ chai.should();
10
+
11
+ describe.each(['orders.read orders.write', ' orders.read orders.write '])('when registering an external service with OAuth scope "%s"', scope => {
12
+ let context: an_external_service_registration;
13
+ let oauth: OAuthAuthorization;
14
+ let request: AddExternalServicesRequest;
15
+ let builder: IExternalServiceBuilder;
16
+ let returnedBuilder: IExternalServiceBuilder;
17
+
18
+ beforeEach(async () => {
19
+ context = new an_external_service_registration();
20
+ await context.services.register('OrdersApi', configuration => {
21
+ builder = configuration.http('https://example.test');
22
+ returnedBuilder = builder.withOAuth('https://auth.example.test', 'fake-client', 'fake-secret', scope);
23
+ returnedBuilder.withHeader('x-source', 'fake-app');
24
+ });
25
+ request = AddExternalServicesRequest.decode(AddExternalServicesRequest.encode(context.sent).finish());
26
+ oauth = request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value2!;
27
+ });
28
+
29
+ it('should return the original builder', () => returnedBuilder.should.equal(builder));
30
+ it('should keep the event store', () => request.EventStore.should.equal('store'));
31
+ it('should select OAuth authorization', () => chai.expect(oauth).not.to.be.undefined);
32
+ it('should leave basic authorization unset', () => chai.expect(request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value0).to.be.undefined);
33
+ it('should leave bearer authorization unset', () => chai.expect(request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value1).to.be.undefined);
34
+ it('should preserve credentials and scope through the request codec', () => oauth.should.deep.equal({
35
+ Authority: 'https://auth.example.test', ClientId: 'fake-client', ClientSecret: 'fake-secret', Scope: scope
36
+ }));
37
+ it('should retain chained headers', () => request.ExternalServices[0].Endpoint!.Http!.Headers['x-source'].should.equal('fake-app'));
38
+ // The pinned 19.153.0 externalservices contract uses length-delimited field 4 (tag 0x22) for Scope.
39
+ it('should encode scope as protobuf field four', () => OAuthAuthorization.encode({
40
+ ...oauth, Authority: '', ClientId: '', ClientSecret: ''
41
+ }).finish().should.deep.equal(Uint8Array.from([0x22, scope.length, ...new TextEncoder().encode(scope)])));
42
+ });
@@ -0,0 +1,44 @@
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 { AddExternalServicesRequest, OAuthAuthorization } from '@cratis/chronicle.contracts';
5
+ import { beforeEach, chai, describe, it } from 'vitest';
6
+ import { an_external_service_registration } from './given/an_external_service_registration.js';
7
+
8
+ chai.should();
9
+
10
+ describe.each([
11
+ { condition: 'omitted', scope: undefined },
12
+ { condition: 'empty', scope: '' },
13
+ { condition: 'undefined', scope: undefined },
14
+ { condition: 'null at runtime', scope: null as unknown as string }
15
+ ])('when registering an external service with $condition OAuth scope', ({ condition, scope }) => {
16
+ let context: an_external_service_registration;
17
+ let oauth: OAuthAuthorization;
18
+ let request: AddExternalServicesRequest;
19
+
20
+ beforeEach(async () => {
21
+ context = new an_external_service_registration();
22
+ await context.services.register('OrdersApi', builder => {
23
+ builder.http('https://example.test');
24
+ const configured = condition === 'omitted'
25
+ ? builder.withOAuth('https://auth.example.test', 'fake-client', 'fake-secret')
26
+ : builder.withOAuth('https://auth.example.test', 'fake-client', 'fake-secret', scope);
27
+ configured.withHeader('x-source', 'fake-app');
28
+ });
29
+ request = AddExternalServicesRequest.decode(AddExternalServicesRequest.encode(context.sent).finish());
30
+ oauth = request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value2!;
31
+ });
32
+
33
+ it('should normalize scope before encoding', () => context.sent.ExternalServices[0].Endpoint!.Http!.Authorization!.Value2!.Scope.should.equal(''));
34
+ it('should select OAuth authorization', () => chai.expect(oauth).not.to.be.undefined);
35
+ it('should leave basic authorization unset', () => chai.expect(request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value0).to.be.undefined);
36
+ it('should leave bearer authorization unset', () => chai.expect(request.ExternalServices[0].Endpoint!.Http!.Authorization!.Value1).to.be.undefined);
37
+ it('should preserve credentials and default scope through the request codec', () => oauth.should.deep.equal({
38
+ Authority: 'https://auth.example.test', ClientId: 'fake-client', ClientSecret: 'fake-secret', Scope: ''
39
+ }));
40
+ it('should retain chained headers', () => request.ExternalServices[0].Endpoint!.Http!.Headers['x-source'].should.equal('fake-app'));
41
+ it('should omit the default scope field from the wire', () => OAuthAuthorization.encode({
42
+ ...oauth, Authority: '', ClientId: '', ClientSecret: ''
43
+ }).finish().should.deep.equal(new Uint8Array()));
44
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.68.1",
3
+ "version": "6.70.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",
@@ -35,9 +35,10 @@ export interface IWebhookDefinitionBuilder {
35
35
  * @param authority - OAuth authority.
36
36
  * @param clientId - OAuth client id.
37
37
  * @param clientSecret - OAuth client secret.
38
+ * @param scope - Optional space-delimited OAuth scope.
38
39
  * @returns The builder for chaining.
39
40
  */
40
- withOAuth(authority: string, clientId: string, clientSecret: string): IWebhookDefinitionBuilder;
41
+ withOAuth(authority: string, clientId: string, clientSecret: string, scope?: string): IWebhookDefinitionBuilder;
41
42
 
42
43
  /**
43
44
  * Adds a target header.