@cratis/chronicle 6.55.0 → 6.57.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 (108) hide show
  1. package/WellKnownTelemetryNames.ts +4 -0
  2. package/auditing/CausationType.ts +5 -0
  3. package/connection/ChronicleConnection.auth.spec.ts +2 -0
  4. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -0
  5. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -0
  6. package/dist/WellKnownTelemetryNames.d.ts +4 -0
  7. package/dist/WellKnownTelemetryNames.d.ts.map +1 -1
  8. package/dist/WellKnownTelemetryNames.js +4 -0
  9. package/dist/WellKnownTelemetryNames.js.map +1 -1
  10. package/dist/auditing/CausationType.d.ts +4 -0
  11. package/dist/auditing/CausationType.d.ts.map +1 -1
  12. package/dist/auditing/CausationType.js +4 -0
  13. package/dist/auditing/CausationType.js.map +1 -1
  14. package/dist/eventSequences/CompensateOptions.d.ts +7 -0
  15. package/dist/eventSequences/CompensateOptions.d.ts.map +1 -0
  16. package/dist/eventSequences/CompensateOptions.js +4 -0
  17. package/dist/eventSequences/CompensateOptions.js.map +1 -0
  18. package/dist/eventSequences/EventSequence.d.ts +6 -0
  19. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  20. package/dist/eventSequences/EventSequence.js +74 -1
  21. package/dist/eventSequences/EventSequence.js.map +1 -1
  22. package/dist/eventSequences/IEventSequence.d.ts +25 -0
  23. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  24. package/dist/eventSequences/index.d.ts +1 -0
  25. package/dist/eventSequences/index.d.ts.map +1 -1
  26. package/dist/eventSequences/index.js.map +1 -1
  27. package/dist/events/EventContext.d.ts +5 -0
  28. package/dist/events/EventContext.d.ts.map +1 -1
  29. package/dist/events/compensationForDecorator.d.ts +32 -0
  30. package/dist/events/compensationForDecorator.d.ts.map +1 -0
  31. package/dist/events/compensationForDecorator.js +44 -0
  32. package/dist/events/compensationForDecorator.js.map +1 -0
  33. package/dist/events/eventTypeDecorator.d.ts +7 -0
  34. package/dist/events/eventTypeDecorator.d.ts.map +1 -1
  35. package/dist/events/eventTypeDecorator.js +13 -4
  36. package/dist/events/eventTypeDecorator.js.map +1 -1
  37. package/dist/events/index.d.ts +2 -1
  38. package/dist/events/index.d.ts.map +1 -1
  39. package/dist/events/index.js +2 -1
  40. package/dist/events/index.js.map +1 -1
  41. package/dist/events/toClientEventContext.d.ts.map +1 -1
  42. package/dist/events/toClientEventContext.js +20 -0
  43. package/dist/events/toClientEventContext.js.map +1 -1
  44. package/dist/externalServices/ExternalServiceBuilder.js +1 -1
  45. package/dist/externalServices/ExternalServiceBuilder.js.map +1 -1
  46. package/dist/projections/eventContextPropertyExpression.js +1 -1
  47. package/dist/projections/eventContextPropertyExpression.js.map +1 -1
  48. package/dist/reactors/Reactors.d.ts.map +1 -1
  49. package/dist/reactors/Reactors.js +6 -2
  50. package/dist/reactors/Reactors.js.map +1 -1
  51. package/dist/readModels/for_ReadModels/given/a_stored_read_model.d.ts.map +1 -1
  52. package/dist/readModels/for_ReadModels/given/a_stored_read_model.js +1 -1
  53. package/dist/readModels/for_ReadModels/given/a_stored_read_model.js.map +1 -1
  54. package/dist/readModels/indexDecorator.js +1 -1
  55. package/dist/readModels/indexDecorator.js.map +1 -1
  56. package/dist/reducers/Reducers.d.ts.map +1 -1
  57. package/dist/reducers/Reducers.js +2 -1
  58. package/dist/reducers/Reducers.js.map +1 -1
  59. package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
  60. package/dist/reducers/ReductionOutcome.js +4 -1
  61. package/dist/reducers/ReductionOutcome.js.map +1 -1
  62. package/dist/schemas/JsonSchema.d.ts +2 -0
  63. package/dist/schemas/JsonSchema.d.ts.map +1 -1
  64. package/dist/testing/InProcessEventSequence.d.ts +3 -1
  65. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  66. package/dist/testing/InProcessEventSequence.js +2 -0
  67. package/dist/testing/InProcessEventSequence.js.map +1 -1
  68. package/dist/tsconfig.tsbuildinfo +1 -1
  69. package/dist/webhooks/WebhookDefinitionBuilder.d.ts.map +1 -1
  70. package/dist/webhooks/WebhookDefinitionBuilder.js +4 -2
  71. package/dist/webhooks/WebhookDefinitionBuilder.js.map +1 -1
  72. package/dist/webhooks/Webhooks.d.ts.map +1 -1
  73. package/dist/webhooks/Webhooks.js +2 -1
  74. package/dist/webhooks/Webhooks.js.map +1 -1
  75. package/eventSequences/CompensateOptions.ts +10 -0
  76. package/eventSequences/EventSequence.compensate.spec.ts +72 -0
  77. package/eventSequences/EventSequence.spec.ts +55 -0
  78. package/eventSequences/EventSequence.ts +81 -1
  79. package/eventSequences/IEventSequence.ts +27 -0
  80. package/eventSequences/index.ts +1 -0
  81. package/events/EventContext.ts +6 -0
  82. package/events/compensationFor.spec.ts +73 -0
  83. package/events/compensationForDecorator.ts +48 -0
  84. package/events/eventTypeDecorator.ts +13 -4
  85. package/events/index.ts +2 -1
  86. package/events/toClientEventContext.ts +21 -0
  87. package/externalServices/ExternalServiceBuilder.ts +1 -1
  88. package/externalServices/ExternalServices.spec.ts +1 -1
  89. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -0
  90. package/package.json +2 -2
  91. package/projections/eventContextPropertyExpression.ts +2 -2
  92. package/reactors/Reactors.ts +6 -2
  93. package/readModels/for_ReadModels/given/a_stored_read_model.ts +1 -1
  94. package/readModels/indexDecorator.legacy.spec.ts +7 -7
  95. package/readModels/indexDecorator.ts +1 -1
  96. package/readModels/indexRegistration.spec.ts +4 -4
  97. package/readModels/standardFallbacks.standard.spec.ts +2 -2
  98. package/reducers/Reducers.ts +2 -1
  99. package/reducers/ReductionOutcome.ts +4 -1
  100. package/schemas/JsonSchema.ts +2 -0
  101. package/telemetry/for_ChronicleTelemetry/given/a_client.fixture.ts +2 -0
  102. package/telemetry/for_ChronicleTelemetry/given/a_span_name_registry.fixture.ts +4 -0
  103. package/telemetry/for_ChronicleTelemetry/given/an_event_sequence.fixture.ts +2 -1
  104. package/telemetry/for_ChronicleTelemetry/when_naming_spans/with_convention_names.spec.ts +3 -1
  105. package/telemetry/for_ChronicleTelemetry/when_recording_identifiers/with_per_client_privacy.spec.ts +2 -1
  106. package/testing/InProcessEventSequence.ts +2 -0
  107. package/webhooks/WebhookDefinitionBuilder.ts +4 -2
  108. package/webhooks/Webhooks.ts +2 -1
@@ -0,0 +1,72 @@
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 type { ChronicleConnection } from '../connection/index.js';
6
+ import type { IUnitOfWorkManager } from '../transactions/IUnitOfWorkManager.js';
7
+ import { compensationFor } from '../events/compensationForDecorator.js';
8
+ import { eventType } from '../events/eventTypeDecorator.js';
9
+ import { EventSequence } from './EventSequence.js';
10
+ import { EventSequenceId } from './EventSequenceId.js';
11
+ import { EventSequenceNumber } from './EventSequenceNumber.js';
12
+
13
+ class EntryPostedForSequence {
14
+ constructor(readonly amount: number = 0) {}
15
+ }
16
+ eventType('entry-posted-for-sequence')(EntryPostedForSequence);
17
+
18
+ class EntryReversedForSequence {
19
+ constructor(readonly reason: string = '') {}
20
+ }
21
+ eventType('entry-reversed-for-sequence')(EntryReversedForSequence);
22
+ compensationFor(EntryPostedForSequence)(EntryReversedForSequence);
23
+
24
+ function createEventSequence(response: object = { SequenceNumber: 8n, ConstraintViolations: [], Errors: [] }) {
25
+ const compensate = vi.fn().mockResolvedValue({ Response: response });
26
+ const connection = { eventSequences: { compensate }, observers: {} } as unknown as ChronicleConnection;
27
+ const eventSequence = new EventSequence(
28
+ EventSequenceId.eventLog, 'my-event-store', 'my-namespace', connection, {} as IUnitOfWorkManager);
29
+ return { eventSequence, compensate };
30
+ }
31
+
32
+ describe('EventSequence', () => {
33
+ describe('when compensating an event', () => {
34
+ const { eventSequence, compensate } = createEventSequence();
35
+ const occurred = new Date('2024-01-15T12:30:00.000Z');
36
+
37
+ it('should send the compensated sequence number, event type and content', async () => {
38
+ const result = await eventSequence.compensate(
39
+ new EventSequenceNumber(3n),
40
+ new EntryReversedForSequence('Wrong account'),
41
+ { tags: ['finance'], occurred });
42
+
43
+ expect(compensate).toHaveBeenCalledTimes(1);
44
+ const request = compensate.mock.calls[0][0];
45
+ expect(request.EventStore).toEqual('my-event-store');
46
+ expect(request.Namespace).toEqual('my-namespace');
47
+ expect(request.EventSequenceId).toEqual(EventSequenceId.eventLog.value);
48
+ expect(request.CompensationFor).toEqual(3n);
49
+ expect(request.EventType.Id).toEqual('entry-reversed-for-sequence');
50
+ expect(JSON.parse(request.Content)).toEqual({ reason: 'Wrong account' });
51
+ expect(request.Tags).toEqual(['finance']);
52
+ expect(request.Occurred).toEqual({ Value: occurred.toISOString() });
53
+ expect(result.isSuccess).toBe(true);
54
+ expect(result.sequenceNumber.value).toEqual(8n);
55
+ });
56
+ });
57
+
58
+ describe('when the kernel rejects the compensation', () => {
59
+ const { eventSequence } = createEventSequence({
60
+ SequenceNumber: 0n,
61
+ ConstraintViolations: [],
62
+ Errors: ['CompensatedEventNotFound']
63
+ });
64
+
65
+ it('should report the error in the result', async () => {
66
+ const result = await eventSequence.compensate(new EventSequenceNumber(99n), new EntryReversedForSequence('x'));
67
+
68
+ expect(result.isSuccess).toBe(false);
69
+ expect(result.errors.map(error => error.message)).toEqual(['CompensatedEventNotFound']);
70
+ });
71
+ });
72
+ });
@@ -3,11 +3,13 @@
3
3
 
4
4
  import { describe, expect, it, vi } from 'vitest';
5
5
  import { ConstraintType, type ConstraintViolation as ContractsConstraintViolation } from '@cratis/chronicle.contracts';
6
+ import { Guid } from '@cratis/fundamentals';
6
7
  import type { ChronicleConnection } from '../connection/index.js';
7
8
  import { causationManager, CausationType } from '../auditing/index.js';
8
9
  import type { IUnitOfWorkManager } from '../transactions/IUnitOfWorkManager.js';
9
10
  import { eventType } from '../events/eventTypeDecorator.js';
10
11
  import { CompleteStreamError } from './CompleteStreamError.js';
12
+ import { fromContractsGuid } from '../connection/Guid.js';
11
13
  import { EventSequence } from './EventSequence.js';
12
14
  import { EventSequenceId } from './EventSequenceId.js';
13
15
  import { EventSequenceNumber } from './EventSequenceNumber.js';
@@ -29,6 +31,7 @@ function createEventSequence(
29
31
  const eventSequences = {
30
32
  redact: vi.fn().mockResolvedValue({}),
31
33
  redactForEventSource: vi.fn().mockResolvedValue({}),
34
+ copyEventsForEventSource: vi.fn().mockResolvedValue({ Response: { lo: 0x0123456789abcdefn, hi: 0x0f1e2d3c4b5a6978n } }),
32
35
  forEventSourceIdAndEventTypes: vi.fn().mockResolvedValue({ Data: [] }),
33
36
  fromSequenceNumber: vi.fn().mockResolvedValue({ Data: [] }),
34
37
  tailSequenceNumber: vi.fn().mockResolvedValue({ Data: { SequenceNumber: EventSequenceNumber.unset.value } }),
@@ -57,6 +60,7 @@ function createEventSequence(
57
60
  eventSequence,
58
61
  redact: eventSequences.redact,
59
62
  redactForEventSource: eventSequences.redactForEventSource,
63
+ copyEventsForEventSource: eventSequences.copyEventsForEventSource,
60
64
  forEventSourceIdAndEventTypes: eventSequences.forEventSourceIdAndEventTypes,
61
65
  fromSequenceNumber: eventSequences.fromSequenceNumber,
62
66
  tailSequenceNumber: eventSequences.tailSequenceNumber,
@@ -154,6 +158,57 @@ describe('EventSequence', () => {
154
158
  });
155
159
  });
156
160
 
161
+ describe('when copying all events of an event source without event types', () => {
162
+ const { eventSequence, copyEventsForEventSource } = createEventSequence();
163
+
164
+ it('should call the CopyEventsForEventSource RPC with an empty event type filter', async () => {
165
+ await eventSequence.copy('source-id', 'target-id');
166
+
167
+ expect(copyEventsForEventSource).toHaveBeenCalledTimes(1);
168
+ const request = copyEventsForEventSource.mock.calls[0][0];
169
+ expect(request.EventStore).toEqual('my-event-store');
170
+ expect(request.Namespace).toEqual('my-namespace');
171
+ expect(request.EventSequenceId).toEqual(EventSequenceId.eventLog.value);
172
+ expect(request.SourceId).toEqual('source-id');
173
+ expect(request.TargetId).toEqual('target-id');
174
+ expect(request.EventTypes).toEqual([]);
175
+ });
176
+
177
+ it('should return the id of the started job', async () => {
178
+ const jobId = await eventSequence.copy('source-id', 'target-id');
179
+
180
+ expect(jobId.toString()).toEqual(fromContractsGuid({ lo: 0x0123456789abcdefn, hi: 0x0f1e2d3c4b5a6978n }).toString());
181
+ expect(jobId.toString()).not.toEqual(Guid.empty.toString());
182
+ });
183
+ });
184
+
185
+ describe('when copying events of an event source filtered to specific event types', () => {
186
+ const { eventSequence, copyEventsForEventSource } = createEventSequence();
187
+
188
+ it('should call the CopyEventsForEventSource RPC with the resolved event type filter', async () => {
189
+ await eventSequence.copy('source-id', 'target-id', SomethingHappened, SomethingElseHappened);
190
+
191
+ const request = copyEventsForEventSource.mock.calls[0][0];
192
+ expect(request.EventTypes).toEqual([
193
+ 'a3f6a2f0-6f2f-4a3c-9d3f-6f2f4a3c9d3f',
194
+ 'b3f6a2f0-6f2f-4a3c-9d3f-6f2f4a3c9d3g'
195
+ ]);
196
+ });
197
+ });
198
+
199
+ describe('when the kernel rejects copying events of an event source', () => {
200
+ const { eventSequence } = createEventSequence({
201
+ copyEventsForEventSource: vi.fn().mockResolvedValue({
202
+ ValidationResults: [{ Message: 'Target already has events', Members: [] }],
203
+ ExceptionMessages: []
204
+ })
205
+ });
206
+
207
+ it('should fail with the kernel reasons', async () => {
208
+ await expect(eventSequence.copy('source-id', 'target-id')).rejects.toThrow('Target already has events');
209
+ });
210
+ });
211
+
157
212
  describe('when getting events for an event source and event types', () => {
158
213
  const { eventSequence, forEventSourceIdAndEventTypes } = createEventSequence({
159
214
  forEventSourceIdAndEventTypes: vi.fn().mockResolvedValue({ Data: [wireAppendedEvent()] })
@@ -28,6 +28,7 @@ import { AppendOperationsBroadcaster } from './AppendOperationsBroadcaster.js';
28
28
  import { AppendOptions } from './AppendOptions.js';
29
29
  import { AppendResult } from './AppendResult.js';
30
30
  import { createAppendResult } from './createAppendResult.js';
31
+ import { CompensateOptions } from './CompensateOptions.js';
31
32
  import { CompleteStreamError } from './CompleteStreamError.js';
32
33
  import { CompleteStreamResult } from './CompleteStreamResult.js';
33
34
  import { ConstraintViolation } from './ConstraintViolation.js';
@@ -49,7 +50,7 @@ import { WellKnownTelemetryNames as names } from '../WellKnownTelemetryNames.js'
49
50
  import { ChronicleConventionMetrics } from '../Metrics.js';
50
51
  import { identityProvider, Identity } from '../identity/index.js';
51
52
  import { causationManager, CausationType } from '../auditing/index.js';
52
- import { toContractsGuid } from '../connection/Guid.js';
53
+ import { fromContractsGuid, toContractsGuid, type Guid } from '../connection/Guid.js';
53
54
  import { ensureCommandResponse, ensureCommandSuccess, ensureQuerySuccess, type CallResultLike } from '../connection/callResults.js';
54
55
  import type { ConcurrencyScope } from './ConcurrencyScope.js';
55
56
  import type { IEventSources } from '../eventSources/IEventSources.js';
@@ -506,6 +507,56 @@ export class EventSequence implements IEventSequence {
506
507
  });
507
508
  }
508
509
 
510
+ /** @inheritdoc */
511
+ async compensate(compensationFor: EventSequenceNumber, event: object, options?: CompensateOptions): Promise<AppendResult> {
512
+ causationManager.add(CausationType.compensate, { compensationFor: compensationFor.value.toString() });
513
+ const prepared = prepareSingleAppend(event, options);
514
+ const { eventType, correlationId, content, tags, causationChain, identity } = prepared;
515
+ const metricAttributes = { ...this.sequenceMetricAttributes, [names.attributes.eventTypeId]: eventType.id.value };
516
+
517
+ return observeOperation('compensate', async span => {
518
+ this.setSequenceAttributes(span);
519
+ setSequenceNumber(span, compensationFor.value);
520
+ setTelemetryAttribute(span, 'eventTypeId', eventType.id.value);
521
+ setTelemetryAttribute(span, 'eventTypeGeneration', eventType.generation.value);
522
+ const startTime = performance.now();
523
+ try {
524
+ const response = ensureCommandResponse('compensate event', await this._connection.eventSequences.compensate({
525
+ EventStore: this._eventStoreName,
526
+ Namespace: this._namespace,
527
+ EventSequenceId: this.id.value,
528
+ CompensationFor: compensationFor.value,
529
+ EventType: {
530
+ Id: eventType.id.value,
531
+ Generation: eventType.generation.value,
532
+ Tombstone: eventType.tombstone
533
+ },
534
+ Content: content,
535
+ CorrelationId: toContractsGuid(correlationId),
536
+ Tags: tags,
537
+ Occurred: toContractsOccurred(options?.occurred),
538
+ Causation: toContractsCausation(causationChain),
539
+ CausedBy: toContractsCausedBy(identity)
540
+ }));
541
+ const result = this.mapAppendResponse(
542
+ response.SequenceNumber,
543
+ response.ConstraintViolations ?? [],
544
+ response.Errors ?? [],
545
+ response.ConcurrencyViolation
546
+ );
547
+ span.setStatus({ code: SpanStatusCode.OK });
548
+ this.recordAppendMetrics(result, (performance.now() - startTime) / 1000, metricAttributes, this.sequenceMetricAttributes);
549
+ return result;
550
+ } catch (error) {
551
+ recordSafeException(span, error);
552
+ ChronicleConventionMetrics.appendErrors.add(1, this.sequenceMetricAttributes);
553
+ throw error;
554
+ } finally {
555
+ span.end();
556
+ }
557
+ }, correlationId);
558
+ }
559
+
509
560
  /** @inheritdoc */
510
561
  async redact(sequenceNumber: EventSequenceNumber, reason: string): Promise<void> {
511
562
  causationManager.add(CausationType.redact, { sequenceNumber: sequenceNumber.value.toString() });
@@ -540,6 +591,35 @@ export class EventSequence implements IEventSequence {
540
591
  }));
541
592
  }
542
593
 
594
+ /** @inheritdoc */
595
+ async copy(sourceId: string, targetId: string, ...eventTypes: Constructor[]): Promise<Guid> {
596
+ const wireEventTypeIds = eventTypes.map(constructor => getEventTypeFor(constructor as unknown as Function).id.value);
597
+
598
+ return observeOperation('copyForEventSource', async span => {
599
+ this.setSequenceAttributes(span);
600
+ setEventSourceId(span, sourceId, this._telemetry);
601
+ try {
602
+ const response = await this._connection.eventSequences.copyEventsForEventSource({
603
+ EventStore: this._eventStoreName,
604
+ Namespace: this._namespace,
605
+ EventSequenceId: this.id.value,
606
+ SourceId: sourceId,
607
+ TargetId: targetId,
608
+ EventTypes: wireEventTypeIds
609
+ });
610
+
611
+ const jobId = fromContractsGuid(ensureCommandResponse('copy events for event source', response));
612
+ span.setStatus({ code: SpanStatusCode.OK });
613
+ return jobId;
614
+ } catch (error) {
615
+ recordSafeException(span, error);
616
+ throw error;
617
+ } finally {
618
+ span.end();
619
+ }
620
+ });
621
+ }
622
+
543
623
  private async sendRedaction(
544
624
  operationName: 'redact' | 'redactForEventSource',
545
625
  description: string,
@@ -2,9 +2,11 @@
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
4
  import type { Constructor } from '@cratis/fundamentals';
5
+ import type { Guid } from '../connection/Guid.js';
5
6
  import type { AppendedEvent } from '../events/AppendedEvent.js';
6
7
  import { AppendedEventWithResult } from './AppendedEventWithResult.js';
7
8
  import { AppendOptions } from './AppendOptions.js';
9
+ import { CompensateOptions } from './CompensateOptions.js';
8
10
  import { CompleteStreamResult } from './CompleteStreamResult.js';
9
11
  import { EventForEventSourceId } from './EventForEventSourceId.js';
10
12
  import { AppendResult } from './AppendResult.js';
@@ -161,6 +163,31 @@ export interface IEventSequence {
161
163
  */
162
164
  redactForEventSource(eventSourceId: string, reason: string, eventTypes?: Constructor[]): Promise<void>;
163
165
 
166
+ /**
167
+ * Appends a compensating event that offsets an earlier event in this sequence.
168
+ * The compensation is appended to the event source, event stream and subject of the compensated event,
169
+ * so none of them are given. The event type of the compensation must be declared with `@compensationFor`
170
+ * for the type of the compensated event.
171
+ * @param compensationFor - The sequence number of the event to compensate for.
172
+ * @param event - The compensation event instance.
173
+ * @param options - Optional correlation identifier, tags and occurred time. Routing options are not used.
174
+ * @returns The append result. A rejected compensation, such as a missing compensated event or an event type
175
+ * that does not compensate for the type of the compensated event, is reported in `errors`.
176
+ */
177
+ compensate(compensationFor: EventSequenceNumber, event: object, options?: CompensateOptions): Promise<AppendResult>;
178
+
179
+ /**
180
+ * Copies the events of one event source onto another event source in this sequence, by starting a durable kernel job.
181
+ * The copies are appended to the target event source with the original event context preserved by the kernel.
182
+ * @param sourceId - The event source identifier to copy events from.
183
+ * @param targetId - The event source identifier to copy events onto.
184
+ * @param eventTypes - Event type constructors to limit the copy to; when none are given, events of every type are copied.
185
+ * @returns A promise that resolves with the identifier of the started copy job once the kernel has accepted the request.
186
+ * Resolving does not mean the copy has finished.
187
+ * @throws ChronicleCallFailed When the kernel rejects the request.
188
+ */
189
+ copy(sourceId: string, targetId: string, ...eventTypes: Constructor[]): Promise<Guid>;
190
+
164
191
  /**
165
192
  * Completes a stream so that no further events can be appended to it.
166
193
  * @param eventStreamType - The event stream type identifying the stream's type.
@@ -9,6 +9,7 @@ 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 { CompensateOptions } from './CompensateOptions.js';
12
13
  export { CompleteStreamError } from './CompleteStreamError.js';
13
14
  export { NamedTagsWithRegisteredEventSourceNotSupported } from './NamedTagsWithRegisteredEventSourceNotSupported.js';
14
15
  export type { CompleteStreamResult } from './CompleteStreamResult.js';
@@ -50,6 +50,12 @@ export interface EventContext {
50
50
  /** The observation state carried by the delivery. */
51
51
  readonly observationState?: number;
52
52
 
53
+ /**
54
+ * The sequence number of the event this event compensates for.
55
+ * Undefined for events that are not compensations.
56
+ */
57
+ readonly compensationFor?: bigint;
58
+
53
59
  /** The type of the event. */
54
60
  readonly eventType: EventType;
55
61
 
@@ -0,0 +1,73 @@
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 } from 'vitest';
5
+ import { compensationFor, getCompensatedTypeFor } from './compensationForDecorator.js';
6
+ import { eventType, getEventTypeJsonSchemaFor } from './eventTypeDecorator.js';
7
+ import { toClientEventContext } from './toClientEventContext.js';
8
+ import type { WireEventContext } from './WireEventContext.js';
9
+
10
+ class LedgerEntryPosted {
11
+ constructor(readonly amount: number = 0) {}
12
+ }
13
+ eventType('ledger-entry-posted')(LedgerEntryPosted);
14
+
15
+ class LedgerEntryReversed {
16
+ constructor(readonly reason: string = '') {}
17
+ }
18
+ // Applied in the opposite order to the documented usage to prove that order does not matter.
19
+ compensationFor(LedgerEntryPosted)(LedgerEntryReversed);
20
+ eventType('ledger-entry-reversed')(LedgerEntryReversed);
21
+
22
+ class LedgerEntryNoted {
23
+ constructor(readonly note: string = '') {}
24
+ }
25
+ eventType('ledger-entry-noted')(LedgerEntryNoted);
26
+
27
+ function wireContext(eventTypeId: string, compensationForValue: bigint): WireEventContext {
28
+ return {
29
+ EventType: { Id: eventTypeId, Generation: 1, Tombstone: false },
30
+ SequenceNumber: 10n,
31
+ EventSourceId: 'source',
32
+ Occurred: { Value: '2024-01-15T12:30:00.0000000+00:00' },
33
+ Causation: [],
34
+ Tags: [],
35
+ NamedTags: [],
36
+ ObservationState: 0,
37
+ CompensationFor: compensationForValue
38
+ } as unknown as WireEventContext;
39
+ }
40
+
41
+ describe('compensationFor', () => {
42
+ describe('when a class is declared as a compensation', () => {
43
+ it('should expose the compensated class', () => {
44
+ expect(getCompensatedTypeFor(LedgerEntryReversed)).toBe(LedgerEntryPosted);
45
+ });
46
+
47
+ it('should register the compensated event type id in the schema', () => {
48
+ expect(getEventTypeJsonSchemaFor(LedgerEntryReversed).compensationFor).toEqual('ledger-entry-posted');
49
+ });
50
+ });
51
+
52
+ describe('when a class is not a compensation', () => {
53
+ it('should not add compensation to the schema', () => {
54
+ expect(getEventTypeJsonSchemaFor(LedgerEntryNoted).compensationFor).toBeUndefined();
55
+ });
56
+ });
57
+
58
+ describe('when converting the context of a compensation', () => {
59
+ it('should carry the compensated sequence number', () => {
60
+ expect(toClientEventContext(wireContext('ledger-entry-reversed', 4n)).compensationFor).toEqual(4n);
61
+ });
62
+
63
+ it('should keep a compensation of the first event', () => {
64
+ expect(toClientEventContext(wireContext('ledger-entry-reversed', 0n)).compensationFor).toEqual(0n);
65
+ });
66
+ });
67
+
68
+ describe('when converting the context of an event that is not a compensation', () => {
69
+ it('should leave the compensation undefined for an unset wire value', () => {
70
+ expect(toClientEventContext(wireContext('ledger-entry-noted', 0n)).compensationFor).toBeUndefined();
71
+ });
72
+ });
73
+ });
@@ -0,0 +1,48 @@
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 'reflect-metadata';
5
+ import { Constructor } from '@cratis/fundamentals';
6
+
7
+ /** Metadata key used to store the compensated event type on a class. */
8
+ const COMPENSATION_FOR_METADATA_KEY = 'chronicle:compensationFor';
9
+
10
+ /**
11
+ * TypeScript decorator that declares an event type as a compensation for another event type.
12
+ * This is the TypeScript equivalent of the C# `[CompensationFor<TEventType>]` attribute.
13
+ *
14
+ * Chronicle registers the link with the event type's schema. A compensation event type can compensate
15
+ * for one event type, and is appended with `IEventSequence.compensate()`.
16
+ *
17
+ * Apply it together with {@link eventType}; the order of the decorators does not matter.
18
+ *
19
+ * @param compensated - The class of the event type being compensated for.
20
+ * @returns A class decorator.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * @eventType()
25
+ * class EntryPosted { constructor(readonly amount: number) {} }
26
+ *
27
+ * @eventType()
28
+ * @compensationFor(EntryPosted)
29
+ * class EntryReversed { constructor(readonly reason: string) {} }
30
+ * ```
31
+ */
32
+ export function compensationFor(compensated: Constructor): (target: object, context?: ClassDecoratorContext) => void {
33
+ return (target: object, context?: ClassDecoratorContext) => {
34
+ Reflect.defineMetadata(COMPENSATION_FOR_METADATA_KEY, compensated, target);
35
+ context?.addInitializer(function () {
36
+ Reflect.defineMetadata(COMPENSATION_FOR_METADATA_KEY, compensated, this as object);
37
+ });
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Gets the class of the event type that a class declared as a compensation with {@link compensationFor} compensates for.
43
+ * @param target - The class constructor to inspect.
44
+ * @returns The compensated event class, or undefined when the class is not a compensation.
45
+ */
46
+ export function getCompensatedTypeFor(target: Function): Constructor | undefined {
47
+ return Reflect.getMetadata(COMPENSATION_FOR_METADATA_KEY, target) as Constructor | undefined;
48
+ }
@@ -6,6 +6,7 @@ import { Constructor } from '@cratis/fundamentals';
6
6
  import { EventType } from './EventType.js';
7
7
  import { EventTypeId } from './EventTypeId.js';
8
8
  import { EventTypeGeneration } from './EventTypeGeneration.js';
9
+ import { getCompensatedTypeFor } from './compensationForDecorator.js';
9
10
  import { DecoratorType, TypeDiscoverer, TypeIntrospector } from '../types/index.js';
10
11
  import { JsonSchema, JsonSchemaGenerator } from '../schemas/index.js';
11
12
  import { ChronicleClassDecorator } from '../types/standardDecoratorMetadata.js';
@@ -162,9 +163,17 @@ export function getEventTypeMetadata(target: Function): EventTypeMetadata | unde
162
163
  */
163
164
  export function getEventTypeJsonSchemaFor(target: Function): JsonSchema {
164
165
  const metadata = getEventTypeMetadata(target);
165
- if (metadata) {
166
- return metadata.schema;
167
- }
166
+ const schema = metadata ? metadata.schema : JsonSchemaGenerator.createEmptySchema(target.name);
167
+ const compensated = getCompensatedEventTypeIdFor(target);
168
+ return compensated ? { ...schema, compensationFor: compensated.value } : schema;
169
+ }
168
170
 
169
- return JsonSchemaGenerator.createEmptySchema(target.name);
171
+ /**
172
+ * Gets the identifier of the event type that a class declared with `@compensationFor` compensates for.
173
+ * @param target - The class constructor to inspect.
174
+ * @returns The compensated event type identifier, or undefined when the class is not a compensation.
175
+ */
176
+ export function getCompensatedEventTypeIdFor(target: Function): EventTypeId | undefined {
177
+ const compensated = getCompensatedTypeFor(target);
178
+ return compensated ? getEventTypeFor(compensated as unknown as Function).id : undefined;
170
179
  }
package/events/index.ts CHANGED
@@ -7,7 +7,8 @@ export { handles } from './handles.js';
7
7
  export { EventType } from './EventType.js';
8
8
  export { EventTypeId } from './EventTypeId.js';
9
9
  export { EventTypeGeneration } from './EventTypeGeneration.js';
10
- export { eventType, getEventTypeFor, hasEventType, getEventTypeMetadata, getEventTypeJsonSchemaFor } from './eventTypeDecorator.js';
10
+ export { eventType, getEventTypeFor, hasEventType, getEventTypeMetadata, getEventTypeJsonSchemaFor, getCompensatedEventTypeIdFor } from './eventTypeDecorator.js';
11
+ export { compensationFor, getCompensatedTypeFor } from './compensationForDecorator.js';
11
12
  export type { EventTypeMetadata } from './eventTypeDecorator.js';
12
13
  export type { EventContext } from './EventContext.js';
13
14
  export type { CausationEntry } from './CausationEntry.js';
@@ -10,6 +10,9 @@ import { EventTypeId } from './EventTypeId.js';
10
10
  import { Tag } from './Tag.js';
11
11
  import { NamedTag } from './NamedTag.js';
12
12
  import type { WireEventContext } from './WireEventContext.js';
13
+ import { DecoratorType } from '../types/DecoratorType.js';
14
+ import { TypeDiscoverer } from '../types/TypeDiscoverer.js';
15
+ import { getCompensatedTypeFor } from './compensationForDecorator.js';
13
16
 
14
17
  /** Converts kernel metadata identically for reads, reactors, and reducers. */
15
18
  export function toClientEventContext(context: WireEventContext): EventContext {
@@ -38,6 +41,7 @@ export function toClientEventContext(context: WireEventContext): EventContext {
38
41
  occurred: causation.Occurred ? new Date(causation.Occurred.Value) : undefined,
39
42
  properties: { ...causation.Properties }
40
43
  })),
44
+ compensationFor: toClientCompensationFor(context),
41
45
  tags: (context.Tags ?? []).map(value => new Tag(value)),
42
46
  namedTags: (context.NamedTags ?? []).map(tag => new NamedTag(tag.Name, tag.Value))
43
47
  };
@@ -46,3 +50,20 @@ export function toClientEventContext(context: WireEventContext): EventContext {
46
50
  function toClientIdentity(identity: WireEventContext['CausedBy']): Identity | undefined {
47
51
  return identity ? new Identity(identity.Subject, identity.Name, identity.UserName, toClientIdentity(identity.OnBehalfOf)) : undefined;
48
52
  }
53
+
54
+ /**
55
+ * The wire format carries an unset compensation as zero, which is also a valid sequence number. Zero is therefore
56
+ * only a compensation when the event type is a registered compensation event type.
57
+ */
58
+ function toClientCompensationFor(context: WireEventContext): bigint | undefined {
59
+ const compensationFor = context.CompensationFor;
60
+ if (compensationFor === undefined) {
61
+ return undefined;
62
+ }
63
+ if (compensationFor !== 0n) {
64
+ return compensationFor;
65
+ }
66
+ const eventTypeId = context.EventType?.Id;
67
+ const type = eventTypeId ? TypeDiscoverer.default.getTypeByDecoratorTypeAndName(DecoratorType.EventType, eventTypeId) : undefined;
68
+ return type && getCompensatedTypeFor(type) ? 0n : undefined;
69
+ }
@@ -56,7 +56,7 @@ export class ExternalServiceBuilder implements IExternalServiceBuilder {
56
56
  this._authorization = {
57
57
  Value0: undefined,
58
58
  Value1: undefined,
59
- Value2: { Authority: authority, ClientId: clientId, ClientSecret: clientSecret }
59
+ Value2: { Authority: authority, ClientId: clientId, ClientSecret: clientSecret, Scope: '' }
60
60
  };
61
61
  return this;
62
62
  }
@@ -53,7 +53,7 @@ describe('ExternalServices registration', () => {
53
53
  const request = await requestFor(builder => builder.http('https://example.com').withOAuth('https://auth', 'client', 'secret'));
54
54
  expect(request.ExternalServices[0].Endpoint?.Http?.Authorization).toEqual({
55
55
  Value0: undefined, Value1: undefined,
56
- Value2: { Authority: 'https://auth', ClientId: 'client', ClientSecret: 'secret' }
56
+ Value2: { Authority: 'https://auth', ClientId: 'client', ClientSecret: 'secret', Scope: '' }
57
57
  });
58
58
  });
59
59
 
@@ -74,6 +74,7 @@ beforeEach(async () => {
74
74
  getVersionInfo: async () => ({})
75
75
  } as ServiceImplementation<typeof ServerDefinition>);
76
76
  server.add(EventStoresDefinition, {
77
+ ...Object.fromEntries(Object.keys(EventStoresDefinition.methods).map(name => [name, unused])),
77
78
  allEventStores: unused, ensureEventStore: success, observeEventStores: unused
78
79
  } as ServiceImplementation<typeof EventStoresDefinition>);
79
80
  server.add(ReadModelsDefinition, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.55.0",
3
+ "version": "6.57.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",
@@ -178,7 +178,7 @@
178
178
  },
179
179
  "dependencies": {
180
180
  "@bufbuild/protobuf": "^2.16.0",
181
- "@cratis/chronicle.contracts": "19.70.0",
181
+ "@cratis/chronicle.contracts": "19.125.2",
182
182
  "@grpc/grpc-js": "^1.14.5",
183
183
  "@opentelemetry/api": "^1.9.1",
184
184
  "glob": "^13.0.6",
@@ -23,9 +23,9 @@ const contextProperties = {
23
23
  correlationId: true,
24
24
  causation: true,
25
25
  tags: true
26
- // eventSource and namedTags are deliberately not projectable: their kernel resolution is not part of the
26
+ // eventSource, namedTags and compensationFor are deliberately not projectable: their kernel resolution is not part of the
27
27
  // supported expression set.
28
- } satisfies Record<Exclude<keyof EventContext, 'eventSource' | 'namedTags'>, true>;
28
+ } satisfies Record<Exclude<keyof EventContext, 'eventSource' | 'namedTags' | 'compensationFor'>, true>;
29
29
 
30
30
  // Mirror the kernel's DerivedPropertyFunctions registry: Week() applies to dates only.
31
31
  const derivedFunctions: Record<string, string> = { week: 'Week' };
@@ -289,7 +289,8 @@ export class Reactors implements IReactors {
289
289
  EventSourceType: getEventSourceTypeFor(reactorType),
290
290
  EventStreamType: getEventStreamTypeFor(reactorType)
291
291
  }
292
- }
292
+ },
293
+ PageDelivery: undefined
293
294
  },
294
295
  Value1: undefined
295
296
  }
@@ -441,7 +442,10 @@ export class Reactors implements IReactors {
441
442
  State: state,
442
443
  LastSuccessfulObservation: lastSuccessfullyObservedEvent,
443
444
  ExceptionMessages: exceptionMessages,
444
- ExceptionStackTrace: exceptionStackTrace
445
+ ExceptionStackTrace: exceptionStackTrace,
446
+ DeliveryId: 0n,
447
+ RetryAfterMilliseconds: 0n,
448
+ Partitions: []
445
449
  }
446
450
  }
447
451
  });
@@ -44,7 +44,7 @@ export class AccountDocument {
44
44
 
45
45
  export class a_stored_read_model {
46
46
  readonly release = vi.fn<(request: ReleaseRequest) => Promise<ReleaseResponse>>()
47
- .mockImplementation(async request => ({ HasError: false, Error: '', Payload: request.Payload }));
47
+ .mockImplementation(async request => ({ HasError: false, Error: '', Payload: request.Payload, FailedProperties: [], Strict: false }));
48
48
  readonly readModels: IReadModels;
49
49
 
50
50
  constructor() {