@cratis/chronicle 6.56.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 (67) hide show
  1. package/WellKnownTelemetryNames.ts +2 -0
  2. package/auditing/CausationType.ts +5 -0
  3. package/dist/WellKnownTelemetryNames.d.ts +2 -0
  4. package/dist/WellKnownTelemetryNames.d.ts.map +1 -1
  5. package/dist/WellKnownTelemetryNames.js +2 -0
  6. package/dist/WellKnownTelemetryNames.js.map +1 -1
  7. package/dist/auditing/CausationType.d.ts +4 -0
  8. package/dist/auditing/CausationType.d.ts.map +1 -1
  9. package/dist/auditing/CausationType.js +4 -0
  10. package/dist/auditing/CausationType.js.map +1 -1
  11. package/dist/eventSequences/CompensateOptions.d.ts +7 -0
  12. package/dist/eventSequences/CompensateOptions.d.ts.map +1 -0
  13. package/dist/eventSequences/CompensateOptions.js +4 -0
  14. package/dist/eventSequences/CompensateOptions.js.map +1 -0
  15. package/dist/eventSequences/EventSequence.d.ts +3 -0
  16. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  17. package/dist/eventSequences/EventSequence.js +45 -0
  18. package/dist/eventSequences/EventSequence.js.map +1 -1
  19. package/dist/eventSequences/IEventSequence.d.ts +13 -0
  20. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  21. package/dist/eventSequences/index.d.ts +1 -0
  22. package/dist/eventSequences/index.d.ts.map +1 -1
  23. package/dist/eventSequences/index.js.map +1 -1
  24. package/dist/events/EventContext.d.ts +5 -0
  25. package/dist/events/EventContext.d.ts.map +1 -1
  26. package/dist/events/compensationForDecorator.d.ts +32 -0
  27. package/dist/events/compensationForDecorator.d.ts.map +1 -0
  28. package/dist/events/compensationForDecorator.js +44 -0
  29. package/dist/events/compensationForDecorator.js.map +1 -0
  30. package/dist/events/eventTypeDecorator.d.ts +7 -0
  31. package/dist/events/eventTypeDecorator.d.ts.map +1 -1
  32. package/dist/events/eventTypeDecorator.js +13 -4
  33. package/dist/events/eventTypeDecorator.js.map +1 -1
  34. package/dist/events/index.d.ts +2 -1
  35. package/dist/events/index.d.ts.map +1 -1
  36. package/dist/events/index.js +2 -1
  37. package/dist/events/index.js.map +1 -1
  38. package/dist/events/toClientEventContext.d.ts.map +1 -1
  39. package/dist/events/toClientEventContext.js +20 -0
  40. package/dist/events/toClientEventContext.js.map +1 -1
  41. package/dist/projections/eventContextPropertyExpression.js +1 -1
  42. package/dist/projections/eventContextPropertyExpression.js.map +1 -1
  43. package/dist/schemas/JsonSchema.d.ts +2 -0
  44. package/dist/schemas/JsonSchema.d.ts.map +1 -1
  45. package/dist/testing/InProcessEventSequence.d.ts +1 -0
  46. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  47. package/dist/testing/InProcessEventSequence.js +1 -0
  48. package/dist/testing/InProcessEventSequence.js.map +1 -1
  49. package/dist/tsconfig.tsbuildinfo +1 -1
  50. package/eventSequences/CompensateOptions.ts +10 -0
  51. package/eventSequences/EventSequence.compensate.spec.ts +72 -0
  52. package/eventSequences/EventSequence.ts +51 -0
  53. package/eventSequences/IEventSequence.ts +14 -0
  54. package/eventSequences/index.ts +1 -0
  55. package/events/EventContext.ts +6 -0
  56. package/events/compensationFor.spec.ts +73 -0
  57. package/events/compensationForDecorator.ts +48 -0
  58. package/events/eventTypeDecorator.ts +13 -4
  59. package/events/index.ts +2 -1
  60. package/events/toClientEventContext.ts +21 -0
  61. package/package.json +2 -2
  62. package/projections/eventContextPropertyExpression.ts +2 -2
  63. package/schemas/JsonSchema.ts +2 -0
  64. package/telemetry/for_ChronicleTelemetry/given/a_client.fixture.ts +1 -0
  65. package/telemetry/for_ChronicleTelemetry/given/a_span_name_registry.fixture.ts +2 -0
  66. package/telemetry/for_ChronicleTelemetry/when_naming_spans/with_convention_names.spec.ts +2 -1
  67. package/testing/InProcessEventSequence.ts +1 -0
@@ -0,0 +1,10 @@
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 { AppendOptions } from './AppendOptions.js';
5
+
6
+ /**
7
+ * Options for appending a compensating event.
8
+ * The event source, event stream and subject always come from the event being compensated, so routing options are not available.
9
+ */
10
+ export type CompensateOptions = Pick<AppendOptions, 'correlationId' | 'tags' | 'occurred'>;
@@ -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
+ });
@@ -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';
@@ -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() });
@@ -6,6 +6,7 @@ import type { Guid } from '../connection/Guid.js';
6
6
  import type { AppendedEvent } from '../events/AppendedEvent.js';
7
7
  import { AppendedEventWithResult } from './AppendedEventWithResult.js';
8
8
  import { AppendOptions } from './AppendOptions.js';
9
+ import { CompensateOptions } from './CompensateOptions.js';
9
10
  import { CompleteStreamResult } from './CompleteStreamResult.js';
10
11
  import { EventForEventSourceId } from './EventForEventSourceId.js';
11
12
  import { AppendResult } from './AppendResult.js';
@@ -162,6 +163,19 @@ export interface IEventSequence {
162
163
  */
163
164
  redactForEventSource(eventSourceId: string, reason: string, eventTypes?: Constructor[]): Promise<void>;
164
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
+
165
179
  /**
166
180
  * Copies the events of one event source onto another event source in this sequence, by starting a durable kernel job.
167
181
  * The copies are appended to the target event source with the original event context preserved by the kernel.
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.56.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.123.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' };
@@ -51,4 +51,6 @@ export type JsonSchema = {
51
51
  enum?: Array<string | number | boolean | null>;
52
52
  compliance?: ComplianceSchemaMetadata[];
53
53
  security?: SecuritySchemaMetadata[];
54
+ /** The identifier of the event type this event type compensates for, when it is a compensation. */
55
+ compensationFor?: string;
54
56
  };
@@ -26,6 +26,7 @@ vi.mock('../../../connection/ChronicleConnection.js', () => ({
26
26
  hasEventsForEventSourceId: async (request: { EventSourceId: string }) => ({ IsAuthorized: true, Data: { HasEvents: request.EventSourceId !== 'empty' } }),
27
27
  forEventSourceIdAndEventTypes: async () => ({ IsAuthorized: true, Data: [] }),
28
28
  fromSequenceNumber: async () => ({ IsAuthorized: true, Data: [] }),
29
+ compensate: async () => ({ Response: { SequenceNumber: 43n, ConstraintViolations: [], Errors: [] } }),
29
30
  redact: async () => ({}),
30
31
  redactForEventSource: async () => ({}),
31
32
  copyEventsForEventSource: async () => ({ Response: { lo: 1n, hi: 2n } }),
@@ -9,6 +9,7 @@ export const legacySpans = {
9
9
  hasEventsFor: 'chronicle.event_sequences.has_events_for',
10
10
  getForEventSourceIdAndEventTypes: 'chronicle.event_sequences.get_for_event_source_id_and_event_types',
11
11
  getFromSequenceNumber: 'chronicle.event_sequences.get_from_sequence_number',
12
+ compensate: 'chronicle.event_sequences.compensate',
12
13
  redact: 'chronicle.event_sequences.redact',
13
14
  redactForEventSource: 'chronicle.event_sequences.redact_for_event_source',
14
15
  copyForEventSource: 'chronicle.event_sequences.copy_for_event_source',
@@ -25,6 +26,7 @@ export const conventionSpans = {
25
26
  hasEventsFor: 'cratis.chronicle.client.event_sequence.has_events_for',
26
27
  getForEventSourceIdAndEventTypes: 'cratis.chronicle.client.event_sequence.get_for_event_source_id_and_event_types',
27
28
  getFromSequenceNumber: 'cratis.chronicle.client.event_sequence.get_from_sequence_number',
29
+ compensate: 'cratis.chronicle.client.event_sequence.compensate',
28
30
  redact: 'cratis.chronicle.client.event_sequence.redact',
29
31
  redactForEventSource: 'cratis.chronicle.client.event_sequence.redact_for_event_source',
30
32
  copyForEventSource: 'cratis.chronicle.client.event_sequence.copy_for_event_source',
@@ -25,6 +25,7 @@ const operations = {
25
25
  hasEventsFor: (sequence: IEventSequence) => sequence.hasEventsFor('source'),
26
26
  getForEventSourceIdAndEventTypes: (sequence: IEventSequence) => sequence.getForEventSourceIdAndEventTypes('source', [Recorded]),
27
27
  getFromSequenceNumber: (sequence: IEventSequence) => sequence.getFromSequenceNumber(sequenceNumber),
28
+ compensate: (sequence: IEventSequence) => sequence.compensate(sequenceNumber, new Recorded()),
28
29
  redact: (sequence: IEventSequence) => sequence.redact(sequenceNumber, 'reason'),
29
30
  redactForEventSource: (sequence: IEventSequence) => sequence.redactForEventSource('source', 'reason'),
30
31
  copyForEventSource: (sequence: IEventSequence) => sequence.copy('source', 'target'),
@@ -61,7 +62,7 @@ for (const spanNames of [undefined, 'legacy', 'convention'] as const) {
61
62
  'cratis.event_store.name': 'store', 'cratis.event_store.namespace': 'namespace',
62
63
  'cratis.event_sequence.id': sequenceId.value
63
64
  });
64
- const hasSequenceNumber = ['append', 'getTailSequenceNumber', 'getFromSequenceNumber', 'redact'].includes(operation);
65
+ const hasSequenceNumber = ['append', 'getTailSequenceNumber', 'getFromSequenceNumber', 'redact', 'compensate'].includes(operation);
65
66
  Object.keys(span.attributes).filter(key => key.startsWith('chronicle.')).should.deep.equal(
66
67
  hasSequenceNumber ? ['chronicle.sequence_number'] : []);
67
68
  if (hasSequenceNumber) span.attributes.should.have.property('chronicle.sequence_number', '42');
@@ -393,6 +393,7 @@ export class InProcessEventSequence implements IEventSequence {
393
393
  (!ids.length || ids.includes(event.eventType.id.value))).map(event => this.snapshot(event));
394
394
  }
395
395
 
396
+ async compensate(): Promise<AppendResult> { throw this.unsupported('compensate', this.id.value, 'Compensation requires kernel storage.'); }
396
397
  async redact(): Promise<void> { throw this.unsupported('redact', this.id.value, 'Redaction requires kernel storage.'); }
397
398
  async redactForEventSource(): Promise<void> { throw this.unsupported('redactForEventSource', this.id.value, 'Redaction requires kernel storage.'); }
398
399
  async copy(): Promise<Guid> { throw this.unsupported('copy', this.id.value, 'Copying events requires kernel jobs.'); }