@cratis/chronicle 6.67.6 → 6.68.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 (61) hide show
  1. package/ChronicleClient.ts +14 -1
  2. package/ChronicleOptions.ts +12 -0
  3. package/EventStoreNamespaceResolver.ts +19 -0
  4. package/dist/ChronicleClient.d.ts +1 -0
  5. package/dist/ChronicleClient.d.ts.map +1 -1
  6. package/dist/ChronicleClient.js +14 -1
  7. package/dist/ChronicleClient.js.map +1 -1
  8. package/dist/ChronicleOptions.d.ts +8 -0
  9. package/dist/ChronicleOptions.d.ts.map +1 -1
  10. package/dist/ChronicleOptions.js +8 -0
  11. package/dist/ChronicleOptions.js.map +1 -1
  12. package/dist/EventStoreNamespaceResolver.d.ts +16 -0
  13. package/dist/EventStoreNamespaceResolver.d.ts.map +1 -0
  14. package/dist/EventStoreNamespaceResolver.js +4 -0
  15. package/dist/EventStoreNamespaceResolver.js.map +1 -0
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/testing/ConstraintKey.d.ts.map +1 -1
  20. package/dist/testing/ConstraintKey.js +24 -14
  21. package/dist/testing/ConstraintKey.js.map +1 -1
  22. package/dist/testing/EventScenario.d.ts.map +1 -1
  23. package/dist/testing/EventScenario.js +100 -67
  24. package/dist/testing/EventScenario.js.map +1 -1
  25. package/dist/testing/EventTypeConstraintClaims.d.ts +15 -0
  26. package/dist/testing/EventTypeConstraintClaims.d.ts.map +1 -0
  27. package/dist/testing/EventTypeConstraintClaims.js +66 -0
  28. package/dist/testing/EventTypeConstraintClaims.js.map +1 -0
  29. package/dist/testing/InProcessConstraints.d.ts.map +1 -1
  30. package/dist/testing/InProcessConstraints.js +8 -91
  31. package/dist/testing/InProcessConstraints.js.map +1 -1
  32. package/dist/testing/InProcessEventPayload.d.ts.map +1 -1
  33. package/dist/testing/InProcessEventPayload.js +2 -1
  34. package/dist/testing/InProcessEventPayload.js.map +1 -1
  35. package/dist/testing/KernelTextHash.d.ts +7 -0
  36. package/dist/testing/KernelTextHash.d.ts.map +1 -0
  37. package/dist/testing/KernelTextHash.js +15 -0
  38. package/dist/testing/KernelTextHash.js.map +1 -0
  39. package/dist/testing/MeasuredConstraintKeys.d.ts.map +1 -1
  40. package/dist/testing/MeasuredConstraintKeys.js +3 -2
  41. package/dist/testing/MeasuredConstraintKeys.js.map +1 -1
  42. package/dist/testing/PropertyConstraintClaims.d.ts +17 -0
  43. package/dist/testing/PropertyConstraintClaims.d.ts.map +1 -0
  44. package/dist/testing/PropertyConstraintClaims.js +69 -0
  45. package/dist/testing/PropertyConstraintClaims.js.map +1 -0
  46. package/dist/tsconfig.tsbuildinfo +1 -1
  47. package/for_ChronicleClient/when_resolving_a_namespace.spec.ts +198 -0
  48. package/index.ts +1 -0
  49. package/package.json +1 -1
  50. package/testing/ConstraintKey.ts +26 -11
  51. package/testing/EventScenario.rejections.spec.ts +1 -1
  52. package/testing/EventScenario.ts +120 -66
  53. package/testing/EventTypeConstraintClaims.ts +68 -0
  54. package/testing/InProcessConstraints.ts +7 -86
  55. package/testing/InProcessEventPayload.ts +2 -1
  56. package/testing/KernelTextHash.ts +17 -0
  57. package/testing/MeasuredConstraintKeys.ts +3 -2
  58. package/testing/PropertyConstraintClaims.ts +75 -0
  59. package/testing/for_EventScenario/when_appending_astral_text/with_plain_text.spec.ts +34 -0
  60. package/testing/for_EventScenario/when_appending_field_types/field_key_measurements.fixture.ts +4 -5
  61. package/testing/for_KernelTextHash/when_escaping_json/with_supplementary_characters.spec.ts +28 -0
@@ -0,0 +1,198 @@
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 { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { afterEach, beforeEach, chai, describe, it, vi } from 'vitest';
6
+ import { ChronicleClient } from '../ChronicleClient.js';
7
+ import { ChronicleOptions } from '../ChronicleOptions.js';
8
+ import { EventStore } from '../EventStore.js';
9
+ import { EventStoreNamespaceName } from '../EventStoreNamespaceName.js';
10
+ import type { EventStoreNamespaceResolver } from '../EventStoreNamespaceResolver.js';
11
+ import type { IClientArtifactsProvider } from '../artifacts/IClientArtifactsProvider.js';
12
+
13
+ chai.should();
14
+ const transport = vi.hoisted(() => ({
15
+ resetChannel: vi.fn(), connect: vi.fn(), disconnect: vi.fn(),
16
+ getVersionInfo: vi.fn(), ensureEventStore: vi.fn()
17
+ }));
18
+ vi.mock('../connection/ChronicleConnection', () => ({
19
+ ChronicleConnection: class {
20
+ resetChannel = transport.resetChannel;
21
+ connect = transport.connect;
22
+ disconnect = transport.disconnect;
23
+ server = { getVersionInfo: transport.getVersionInfo };
24
+ eventStores = { ensureEventStore: transport.ensureEventStore };
25
+ }
26
+ }));
27
+ const artifacts: IClientArtifactsProvider = {
28
+ eventTypes: [], readModels: [], reactors: [], reducers: [], seeders: [], constraints: [],
29
+ projections: [], webhooks: [], eventTypeMigrations: [], globalForHandlers: []
30
+ };
31
+ let client: ChronicleClient;
32
+
33
+ function create(namespaceResolver?: EventStoreNamespaceResolver) {
34
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000', {
35
+ namespaceResolver, skipKeepAlive: true, discoveryPatterns: [], clientArtifactsProvider: artifacts
36
+ }));
37
+ return client;
38
+ }
39
+
40
+ async function rejection(operation: Promise<unknown>): Promise<Error> {
41
+ const [result] = await Promise.allSettled([operation]);
42
+ result.status.should.equal('rejected');
43
+ if (result.status !== 'rejected') throw new Error('Expected the operation to reject');
44
+ return result.reason as Error;
45
+ }
46
+
47
+ function deferred() {
48
+ let resolve!: () => void;
49
+ const promise = new Promise<void>(complete => { resolve = complete; });
50
+ return { promise, resolve };
51
+ }
52
+
53
+ beforeEach(() => {
54
+ vi.clearAllMocks();
55
+ transport.ensureEventStore.mockResolvedValue({ IsAuthorized: true });
56
+ // Exercise real store construction and caching without registering artifacts with a kernel.
57
+ vi.spyOn(EventStore.prototype, 'registerArtifacts').mockResolvedValue(undefined);
58
+ });
59
+ afterEach(() => { client?.dispose(); vi.restoreAllMocks(); });
60
+
61
+ describe('when resolving a namespace', () => {
62
+ it('should preserve the default namespace when no resolver is configured', async () => {
63
+ const store = await create().getEventStore('store');
64
+ store.namespace.should.equal(EventStoreNamespaceName.default);
65
+ store.should.equal(await client.getEventStore('store', EventStoreNamespaceName.default));
66
+ });
67
+
68
+ it('should bypass the resolver for explicit string and concept namespaces', async () => {
69
+ const resolver = vi.fn(() => { throw new Error('Must not resolve'); });
70
+ create(resolver);
71
+ const store = await client.getEventStore('store', 'explicit');
72
+ store.namespace.value.should.equal('explicit');
73
+ store.should.equal(await client.getEventStore('store', new EventStoreNamespaceName('explicit')));
74
+ resolver.mock.calls.should.have.lengthOf(0);
75
+ });
76
+
77
+ it('should accept a synchronous namespace name', async () => {
78
+ const store = await create(() => 'tenant-a').getEventStore('store');
79
+ store.namespace.value.should.equal('tenant-a');
80
+ });
81
+
82
+ it('should accept a synchronous namespace concept', async () => {
83
+ const namespace = new EventStoreNamespaceName('tenant-a');
84
+ const store = await create(() => namespace).getEventStore('store');
85
+ store.namespace.should.equal(namespace);
86
+ });
87
+
88
+ it('should accept an asynchronous namespace name', async () => {
89
+ const store = await create(async () => 'tenant-a').getEventStore('store');
90
+ store.namespace.value.should.equal('tenant-a');
91
+ });
92
+
93
+ it('should accept an asynchronous namespace concept', async () => {
94
+ const namespace = new EventStoreNamespaceName('tenant-a');
95
+ const store = await create(async () => namespace).getEventStore('store');
96
+ store.namespace.should.equal(namespace);
97
+ });
98
+
99
+ it('should share a cached store between resolved and explicit namespaces', async () => {
100
+ const resolved = await create(() => 'tenant-a').getEventStore('store');
101
+ resolved.should.equal(await client.getEventStore('store', 'tenant-a'));
102
+ resolved.should.equal(await client.getEventStore('store', new EventStoreNamespaceName('tenant-a')));
103
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(1);
104
+ });
105
+
106
+ it('should resolve on every omitted-namespace call, including cache hits', async () => {
107
+ const resolver = vi.fn().mockReturnValueOnce('tenant-a').mockReturnValueOnce('tenant-b').mockReturnValue('tenant-a');
108
+ create(resolver);
109
+ const first = await client.getEventStore('store');
110
+ const second = await client.getEventStore('store');
111
+ const third = await client.getEventStore('store');
112
+ first.should.not.equal(second);
113
+ first.namespace.value.should.equal('tenant-a');
114
+ second.namespace.value.should.equal('tenant-b');
115
+ third.should.equal(first);
116
+ resolver.mock.calls.should.have.lengthOf(3);
117
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(2);
118
+ });
119
+
120
+ it('should preserve the namespace resolver in development options', () => {
121
+ const resolver = () => 'tenant-a';
122
+ ChronicleOptions.development({ namespaceResolver: resolver }).namespaceResolver!.should.equal(resolver);
123
+ });
124
+ });
125
+
126
+ describe('when namespace resolution fails', () => {
127
+ for (const asynchronous of [false, true]) {
128
+ it(`should propagate a ${asynchronous ? 'rejection' : 'throw'} without connecting or caching a default store`, async () => {
129
+ const failure = new Error('Missing tenant');
130
+ const resolver = vi.fn(() => {
131
+ if (asynchronous) return Promise.reject(failure);
132
+ throw failure;
133
+ });
134
+ create(resolver);
135
+ (await rejection(client.getEventStore('store'))).should.equal(failure);
136
+ transport.resetChannel.mock.calls.should.have.lengthOf(0);
137
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(0);
138
+ const explicit = await client.getEventStore('store', 'explicit');
139
+ explicit.namespace.value.should.equal('explicit');
140
+ (await rejection(client.getEventStore('store'))).should.equal(failure);
141
+ resolver.mock.calls.should.have.lengthOf(2);
142
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(1);
143
+ });
144
+ }
145
+
146
+ const invalid: readonly unknown[] = ['', ' \t\n', undefined, null, 42, {}, { value: 'tenant-a' }, new EventStoreNamespaceName('')];
147
+ for (const [index, result] of invalid.entries()) {
148
+ it(`should reject invalid resolver result ${index} without falling back to the default namespace`, async () => {
149
+ const resolver = (() => result) as EventStoreNamespaceResolver;
150
+ create(resolver);
151
+ const error = await rejection(client.getEventStore('store'));
152
+ error.should.be.instanceOf(TypeError);
153
+ error.message.should.equal('namespaceResolver must return a non-empty namespace name.');
154
+ transport.resetChannel.mock.calls.should.have.lengthOf(0);
155
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(0);
156
+ });
157
+ }
158
+ });
159
+
160
+ describe('when resolving concurrent request namespaces', () => {
161
+ it('should isolate interleaved asynchronous application contexts on a shared client', async () => {
162
+ const context = new AsyncLocalStorage<string>();
163
+ const enteredA = deferred();
164
+ const enteredB = deferred();
165
+ const releaseA = deferred();
166
+ const releaseB = deferred();
167
+ create(async () => {
168
+ const tenant = context.getStore();
169
+ if (tenant === 'tenant-a') {
170
+ enteredA.resolve();
171
+ await releaseA.promise;
172
+ } else {
173
+ enteredB.resolve();
174
+ await releaseB.promise;
175
+ }
176
+ // Read after the interleave to prove the caller's context is retained across awaits.
177
+ const current = context.getStore();
178
+ if (!current) throw new Error('Missing tenant');
179
+ return current;
180
+ });
181
+ const requestA = context.run('tenant-a', () => client.getEventStore('store'));
182
+ await enteredA.promise;
183
+ const requestB = context.run('tenant-b', () => client.getEventStore('store'));
184
+ await enteredB.promise;
185
+ releaseB.resolve();
186
+ const storeB = await requestB;
187
+ releaseA.resolve();
188
+ const storeA = await requestA;
189
+ storeA.namespace.value.should.equal('tenant-a');
190
+ storeB.namespace.value.should.equal('tenant-b');
191
+ storeA.should.not.equal(storeB);
192
+ storeA.should.equal(await client.getEventStore('store', 'tenant-a'));
193
+ storeB.should.equal(await client.getEventStore('store', 'tenant-b'));
194
+ // No request context remains; a previous tenant must not become a client default.
195
+ (await rejection(client.getEventStore('store'))).message.should.equal('Missing tenant');
196
+ transport.ensureEventStore.mock.calls.should.have.lengthOf(2);
197
+ });
198
+ });
package/index.ts CHANGED
@@ -40,6 +40,7 @@ export type { ArtifactRegistrationResult, ArtifactRegistrationState, ProjectionR
40
40
  export type { IEventStore } from './IEventStore.js';
41
41
  export { EventStoreName } from './EventStoreName.js';
42
42
  export { EventStoreNamespaceName } from './EventStoreNamespaceName.js';
43
+ export type { EventStoreNamespaceResolver } from './EventStoreNamespaceResolver.js';
43
44
  export { Guid } from '@cratis/fundamentals';
44
45
  export { ReplayState } from '@cratis/chronicle.contracts';
45
46
  export { ChronicleInstrumentationName, ChronicleTracer } from './Tracing.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.67.6",
3
+ "version": "6.68.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",
@@ -15,10 +15,14 @@ type Claim = { key: string; parts: Array<{ property: string; raw: string }> };
15
15
  const provenString = /^[A-Za-z0-9 .@_:\-|{}$\u00e9]*$/;
16
16
 
17
17
  function guidKey(value: unknown, name: string): string {
18
- if (typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value)) return value.toLowerCase();
18
+ if (isDashedGuid(value)) return value.toLowerCase();
19
19
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name, 'Only dashed Guid keys are fixture-backed.');
20
20
  }
21
21
 
22
+ function isDashedGuid(value: unknown): value is string {
23
+ return typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value);
24
+ }
25
+
22
26
  function isDecimalFraction(value: number): boolean {
23
27
  // constraints-fractional-field-types.json: below 0.0001 .NET uses exponent strings, unlike JS.
24
28
  // The rounding/boundary vectors match JS below 1e15; keep larger fractions conservatively rejected.
@@ -26,16 +30,18 @@ function isDecimalFraction(value: number): boolean {
26
30
  }
27
31
 
28
32
  function numericKey(value: unknown, context: KeyContext): string {
29
- if (typeof value === 'number') {
30
- if (Number.isSafeInteger(value)) return String(value);
31
- if (context.fractions && isDecimalFraction(value)) return String(value);
32
- }
33
+ if (isSupportedNumber(value, context.fractions)) return String(value);
33
34
  const reason = context.fractions
34
35
  ? 'Only safe-integer or fractional numeric keys with magnitude at least 0.0001 and below 1e15 are fixture-backed; other values require a kernel-backed test.'
35
36
  : 'Only safe-integer numeric keys are fixture-backed; fractional, exponential and unsafe-integer comparisons require a kernel-backed test.';
36
37
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', context.name, reason);
37
38
  }
38
39
 
40
+ function isSupportedNumber(value: unknown, fractions: boolean): value is number {
41
+ if (typeof value !== 'number') return false;
42
+ return Number.isSafeInteger(value) || fractions && isDecimalFraction(value);
43
+ }
44
+
39
45
  function kernelKeyString(value: unknown, context: KeyContext, schema?: JsonSchema): string {
40
46
  if (schema?.format === 'guid') return guidKey(value, context.name);
41
47
  if (schema?.type === 'number') return schemaNumericKey(value, context, schema.format);
@@ -48,22 +54,31 @@ function schemaNumericKey(value: unknown, context: KeyContext, format: string |
48
54
  }
49
55
 
50
56
  function scalarKey(value: unknown, context: KeyContext): string {
51
- if (typeof value === 'string') {
52
- const accepted = provenString.test(value) || context.measured && isMeasuredText(value);
53
- if (accepted) return value;
54
- }
57
+ if (typeof value === 'string' && isSupportedString(value, context.measured)) return value;
55
58
  if (typeof value === 'boolean') return value ? 'True' : 'False';
56
59
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', context.name,
57
60
  'Only fixture-backed scalar string and boolean keys are supported.');
58
61
  }
59
62
 
63
+ function isSupportedString(value: string, measured: boolean): boolean {
64
+ return provenString.test(value) || measured && isMeasuredText(value);
65
+ }
66
+
60
67
  function supportsFractions(capture: ConstraintCapture): boolean {
61
68
  const unique = capture.uniqueConstraint!;
62
- return !Object.values(capture.scope).some(Boolean) && !unique.ignoreCasing &&
63
- unique.removedWithEventTypeId === undefined && !unique.removedWithEventTypeIds?.length &&
69
+ return isUnscopedCaseSensitive(capture) && !hasPropertyRemovals(capture) &&
64
70
  unique.eventDefinitions.every(entry => entry.properties.length === 1);
65
71
  }
66
72
 
73
+ function isUnscopedCaseSensitive(capture: ConstraintCapture): boolean {
74
+ return !Object.values(capture.scope).some(Boolean) && !capture.uniqueConstraint!.ignoreCasing;
75
+ }
76
+
77
+ function hasPropertyRemovals(capture: ConstraintCapture): boolean {
78
+ const unique = capture.uniqueConstraint!;
79
+ return unique.removedWithEventTypeId !== undefined || !!unique.removedWithEventTypeIds?.length;
80
+ }
81
+
67
82
  function normalizedKey(joined: string, ignoreCasing: boolean, name: string): string {
68
83
  if (!ignoreCasing) return joined;
69
84
  // The pinned kernel's ToLowerInvariant is proven only for the existing ASCII domain.
@@ -196,7 +196,7 @@ describe('when the fixture-bounded event sequence encounters unproven operations
196
196
  }
197
197
  for (const [name, value] of [
198
198
  ['DEL', '\u007f'], ['Japanese outside measured characters', '日本'], ['unmeasured control', '\u0002'],
199
- ['emoji', '😀'], ['Greek outside measured letters', 'λ']
199
+ ['unmeasured emoji', '\u{1f601}'], ['lone high surrogate', '\ud83d'], ['reversed surrogate pair', '\ude00\ud83d'], ['Greek outside measured letters', 'λ']
200
200
  ] as const) {
201
201
  it(`should reject ${name} outside the fixture-backed content domain`, async () => {
202
202
  const subject = scenario();
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) Cratis. All rights reserved.
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
+ import type { Constructor } from '@cratis/fundamentals';
4
5
  import { DefaultClientArtifactsProvider } from '../artifacts/DefaultClientArtifactsProvider.js';
5
6
  import { TypeDiscoverer } from '../types/TypeDiscoverer.js';
6
7
  import { TypeIntrospector } from '../types/TypeIntrospector.js';
@@ -44,8 +45,7 @@ function isGuidOrNumericKey(schema: { type?: string; format?: string } | undefin
44
45
  function validateExtendedDefinition(name: string, unique: UniqueConstraintCapture | undefined,
45
46
  constructors: ReadonlyMap<string, Function>): void {
46
47
  if (!unique) return;
47
- const schemas = unique.eventDefinitions.flatMap(entry => entry.properties.map(property =>
48
- getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]));
48
+ const schemas = unique.eventDefinitions.flatMap(entry => propertySchemas(entry, constructors));
49
49
  if (!schemas.some(isGuidOrNumericKey)) return;
50
50
  if (schemas.some(schema => schema?.type === 'boolean')) {
51
51
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
@@ -56,8 +56,7 @@ function validateExtendedDefinition(name: string, unique: UniqueConstraintCaptur
56
56
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
57
57
  'Guid and numeric keys with covered-and-removal events are not fixture-backed.');
58
58
  }
59
- if (!supportsFieldlessPropertyRemoval(unique, constructors) &&
60
- removers.some(id => isFieldless(id, constructors))) {
59
+ if (hasUnsupportedFieldlessRemoval(unique, constructors, removers)) {
61
60
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
62
61
  'Guid and numeric keys with fieldless removal events are not fixture-backed.');
63
62
  }
@@ -66,30 +65,59 @@ function validateExtendedDefinition(name: string, unique: UniqueConstraintCaptur
66
65
  function validateKeySchemas(name: string, schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
67
66
  options: { scoped: boolean; isolated: boolean; definitions: number; ignoreCasing: boolean }): void {
68
67
  const fail = (reason: string) => { throw new UnsupportedEventSequenceOperation('artifacts.constraints', name, reason); };
69
- const plainStrings = schemas.every(schema => schema?.type === 'string' && schema.format === undefined);
70
- if (options.scoped && !hasPlainScalarSchemas(schemas) && !hasCombinedKeySchemas(schemas)) {
68
+ if (options.scoped && !hasSupportedScopeSchemas(schemas)) {
71
69
  fail('Scoped property keys must be schema-backed strings, booleans, Guids or unformatted numbers.');
72
70
  }
73
- for (const schema of schemas) {
74
- const supported = supportsMeasuredKeySchema(schema, options, schemas.length);
75
- if (!supported) fail(`Unique keys with schema ${schema?.type ?? 'missing'}/${schema?.format ?? 'unformatted'} are not fixture-backed; date, object and other numeric formats require a kernel-backed test.`);
76
- }
77
- if (schemas.some(isGuidOrNumericKey) &&
78
- (options.definitions !== 1 || !options.isolated && !hasCombinedKeySchemas(schemas))) {
71
+ validateIndividualKeySchemas(name, schemas, options);
72
+ if (schemas.some(isGuidOrNumericKey) && !supportsGuidNumericDefinition(schemas, options)) {
79
73
  fail('Guid and numeric keys require one definition; combined keys require unformatted numbers or Guids.');
80
74
  }
81
- if (options.ignoreCasing && !plainStrings) fail('Case-insensitive keys must be schema-backed strings.');
75
+ if (options.ignoreCasing && !hasPlainStringSchemas(schemas)) fail('Case-insensitive keys must be schema-backed strings.');
82
76
  if (schemas.length > 1 && !hasCombinedKeySchemas(schemas)) {
83
77
  fail('Every property of a composite key must be a schema-backed string, Guid or unformatted number.');
84
78
  }
85
79
  }
86
80
 
81
+ function propertySchemas(entry: UniqueConstraintCapture['eventDefinitions'][number], constructors: ReadonlyMap<string, Function>) {
82
+ return entry.properties.map(property => getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]);
83
+ }
84
+
85
+ function validateIndividualKeySchemas(name: string, schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
86
+ options: { scoped: boolean; isolated: boolean; definitions: number; ignoreCasing: boolean }): void {
87
+ for (const schema of schemas) {
88
+ if (!supportsMeasuredKeySchema(schema, options, schemas.length)) {
89
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
90
+ `Unique keys with schema ${schema?.type ?? 'missing'}/${schema?.format ?? 'unformatted'} are not fixture-backed; date, object and other numeric formats require a kernel-backed test.`);
91
+ }
92
+ }
93
+ }
94
+
95
+ function hasSupportedScopeSchemas(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>): boolean {
96
+ return hasPlainScalarSchemas(schemas) || hasCombinedKeySchemas(schemas);
97
+ }
98
+
99
+ function supportsGuidNumericDefinition(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
100
+ options: { definitions: number; isolated: boolean }): boolean {
101
+ return options.definitions === 1 && (options.isolated || hasCombinedKeySchemas(schemas));
102
+ }
103
+
104
+ function hasPlainStringSchemas(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>): boolean {
105
+ return schemas.every(schema => schema?.type === 'string' && schema.format === undefined);
106
+ }
107
+
87
108
  function supportsFieldlessPropertyRemoval(unique: UniqueConstraintCapture | undefined, constructors: ReadonlyMap<string, Function>): boolean {
88
- return !!unique && !unique.ignoreCasing && unique.eventDefinitions.every(entry => {
89
- if (entry.properties.length !== 1) return false;
90
- const field = getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[entry.properties[0]];
91
- return field?.type === 'string' || field?.type === 'number';
92
- });
109
+ return !!unique && !unique.ignoreCasing && unique.eventDefinitions.every(entry => supportsFieldlessProperty(entry, constructors));
110
+ }
111
+
112
+ function supportsFieldlessProperty(entry: UniqueConstraintCapture['eventDefinitions'][number], constructors: ReadonlyMap<string, Function>): boolean {
113
+ if (entry.properties.length !== 1) return false;
114
+ const field = propertySchemas(entry, constructors)[0];
115
+ return field?.type === 'string' || field?.type === 'number';
116
+ }
117
+
118
+ function hasUnsupportedFieldlessRemoval(unique: UniqueConstraintCapture | undefined, constructors: ReadonlyMap<string, Function>,
119
+ removedWith: readonly (string | undefined)[]): boolean {
120
+ return !supportsFieldlessPropertyRemoval(unique, constructors) && removedWith.some(id => isFieldless(id, constructors));
93
121
  }
94
122
 
95
123
  function isFieldless(id: string | undefined, constructors: ReadonlyMap<string, Function>): boolean {
@@ -110,24 +138,32 @@ function validateScenarioDefinition(name: string, capture: ConstraintCapture,
110
138
  options: { selectedIds: ReadonlySet<string>; constructors: ReadonlyMap<string, Function>; definitions: number }): void {
111
139
  const { selectedIds, constructors, definitions } = options;
112
140
  const { ids, removedWith } = constraintReferences(capture);
113
- if ([...ids, ...removedWith].some(id => id !== undefined && !selectedIds.has(id))) {
141
+ if (hasUnselectedReferences([...ids, ...removedWith], selectedIds)) {
114
142
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
115
143
  'Every constrained event type must be in the selected catalog. Claiming and removal references must be complete.');
116
144
  }
117
145
  const scoped = Object.values(capture.scope).some(Boolean);
118
- if (scoped && !supportsFieldlessPropertyRemoval(capture.uniqueConstraint, constructors) && removedWith.some(id => isFieldless(id, constructors))) {
146
+ if (scoped && hasUnsupportedFieldlessRemoval(capture.uniqueConstraint, constructors, removedWith)) {
119
147
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
120
148
  'Scoped fieldless removers require a case-sensitive single-property unique constraint with string, Guid or numeric keys; other combinations are not fixture-backed.');
121
149
  }
122
150
  validateExtendedDefinition(name, capture.uniqueConstraint, constructors);
123
151
  for (const entry of capture.uniqueConstraint?.eventDefinitions ?? []) {
124
- const schemas = entry.properties.map(property => getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]);
152
+ const schemas = propertySchemas(entry, constructors);
125
153
  validateKeySchemas(name, schemas, { scoped, definitions,
126
- isolated: !scoped && capture.uniqueConstraint!.eventDefinitions.length === 1 && !removedWith.some(id => id !== undefined),
154
+ isolated: isIsolatedPropertyDefinition(capture.uniqueConstraint!, scoped, removedWith),
127
155
  ignoreCasing: capture.uniqueConstraint!.ignoreCasing });
128
156
  }
129
157
  }
130
158
 
159
+ function hasUnselectedReferences(ids: readonly (string | undefined)[], selectedIds: ReadonlySet<string>): boolean {
160
+ return ids.some(id => id !== undefined && !selectedIds.has(id));
161
+ }
162
+
163
+ function isIsolatedPropertyDefinition(unique: UniqueConstraintCapture, scoped: boolean, removedWith: readonly (string | undefined)[]): boolean {
164
+ return !scoped && unique.eventDefinitions.length === 1 && !removedWith.some(id => id !== undefined);
165
+ }
166
+
131
167
  function scenarioConstraints(definitions: ReadonlyMap<string, ConstraintCapture>, selectedIds: ReadonlySet<string>,
132
168
  constructors: ReadonlyMap<string, Function>): InProcessConstraints {
133
169
  // Other-sequence definitions neither validate nor index this scenario's event log.
@@ -150,6 +186,66 @@ function hasConstraintDecorators(type: Function): boolean {
150
186
  TypeIntrospector.getTrackedProperties(type).some(property => getUniquePropertyMetadata(type, property) !== undefined);
151
187
  }
152
188
 
189
+ function compileScenarioConstraints(eventTypes: Constructor[], discoveredArtifacts: DefaultClientArtifactsProvider | undefined,
190
+ discovered: Constructor[] | undefined): InProcessConstraints {
191
+ validateConstraintMetadata(discovered ?? []);
192
+ try {
193
+ // Keep global decorator contributions. A shadowed ID is accepted only when neither
194
+ // constructor has constraint decorators, so either one compiles to the same constraints.
195
+ const compiledEventTypes = [...new Set([...(discoveredArtifacts?.eventTypes ?? []), ...eventTypes])];
196
+ const constructorsById = constraintConstructors(compiledEventTypes);
197
+ const compiled = compileConstraints({ eventTypes: [...constructorsById.values()], constraints: discovered ?? [] });
198
+ const selectedIds = new Set(eventTypes.map(type => getEventTypeFor(type).id.value));
199
+ const definitions = discoveredArtifacts ? new Map([...compiled].filter(([, capture]) => referencesSelectedType(capture, selectedIds))) : compiled;
200
+ validateRemovalReferences(eventTypes, definitions);
201
+ return scenarioConstraints(definitions, selectedIds, constructorsById);
202
+ } catch (error) {
203
+ if (error instanceof UnsupportedEventSequenceOperation) throw error;
204
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', 'compiler', `Invalid constraint definition: ${String(error)}.`);
205
+ }
206
+ }
207
+
208
+ function validateConstraintMetadata(discovered: Constructor[]): void {
209
+ for (const type of discovered) {
210
+ if (!getConstraintMetadata(type)) throw new UnsupportedEventSequenceOperation('artifacts.constraints', type.name,
211
+ 'Every selected constraint must have @constraint metadata.');
212
+ }
213
+ }
214
+
215
+ function constraintConstructors(eventTypes: Constructor[]): Map<string, Constructor> {
216
+ const constructors = new Map<string, Constructor>();
217
+ for (const type of eventTypes) {
218
+ const id = getEventTypeFor(type).id.value;
219
+ const previous = constructors.get(id);
220
+ if (hasConflictingConstraintDecorators(previous, type)) {
221
+ throw new UnsupportedEventSequenceOperation('artifacts.eventTypes', id,
222
+ 'Conflicting constructors share an event type ID; constraint discovery cannot choose one.');
223
+ }
224
+ constructors.set(id, type);
225
+ }
226
+ return constructors;
227
+ }
228
+
229
+ function hasConflictingConstraintDecorators(previous: Function | undefined, type: Function): boolean {
230
+ return previous !== undefined && previous !== type && (hasConstraintDecorators(previous) || hasConstraintDecorators(type));
231
+ }
232
+
233
+ function referencesSelectedType(capture: ConstraintCapture, selectedIds: ReadonlySet<string>): boolean {
234
+ const { ids, removedWith } = constraintReferences(capture);
235
+ return [...ids, ...removedWith].some(id => id !== undefined && selectedIds.has(id));
236
+ }
237
+
238
+ function validateRemovalReferences(eventTypes: Constructor[], definitions: ReadonlyMap<string, ConstraintCapture>): void {
239
+ for (const type of eventTypes) {
240
+ for (const name of getRemovedConstraintNames(type)) {
241
+ if (!definitions.has(name)) {
242
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
243
+ 'Unresolved removal constraint name in the selected catalog.');
244
+ }
245
+ }
246
+ }
247
+ }
248
+
153
249
  /** A kernel-free, fixture-bounded append scenario. No observer runs automatically. */
154
250
  export class EventScenario {
155
251
  readonly eventSequence: IEventSequence;
@@ -168,50 +264,8 @@ export class EventScenario {
168
264
  const discoveredArtifacts = selectedArtifacts && selectedConstraints === undefined
169
265
  ? new DefaultClientArtifactsProvider(TypeDiscoverer.default) : undefined;
170
266
  const discovered = selectedConstraints ?? discoveredArtifacts?.constraints ?? artifacts.constraints;
171
- let constraints: InProcessConstraints | undefined;
172
- if (options.constraints !== 'disabled') {
173
- for (const type of discovered ?? []) {
174
- if (!getConstraintMetadata(type)) throw new UnsupportedEventSequenceOperation('artifacts.constraints', type.name,
175
- 'Every selected constraint must have @constraint metadata.');
176
- }
177
- try {
178
- // Keep global decorator contributions. A shadowed ID is accepted only when neither
179
- // constructor has constraint decorators, so either one compiles to the same constraints.
180
- const compiledEventTypes = [...new Set([...(discoveredArtifacts?.eventTypes ?? []), ...eventTypes])];
181
- const constructorsById = new Map<string, (typeof eventTypes)[number]>();
182
- for (const type of compiledEventTypes) {
183
- const id = getEventTypeFor(type).id.value;
184
- const previous = constructorsById.get(id);
185
- if (previous && previous !== type && (hasConstraintDecorators(previous) || hasConstraintDecorators(type))) {
186
- throw new UnsupportedEventSequenceOperation('artifacts.eventTypes', id,
187
- 'Conflicting constructors share an event type ID; constraint discovery cannot choose one.');
188
- }
189
- constructorsById.set(id, type);
190
- }
191
- const compiled = compileConstraints({ eventTypes: [...constructorsById.values()], constraints: discovered ?? [] });
192
- const selectedIds = new Set(eventTypes.map(type => getEventTypeFor(type).id.value));
193
- const definitions = discoveredArtifacts ? new Map([...compiled].filter(([, capture]) => {
194
- const constrained = capture.uniqueConstraint?.eventDefinitions.map(entry => entry.eventTypeId) ??
195
- capture.uniqueEventType?.eventTypeIds ?? [capture.uniqueEventType?.eventTypeId];
196
- const removedWith = [...(capture.uniqueConstraint?.removedWithEventTypeIds ?? []),
197
- capture.uniqueConstraint?.removedWithEventTypeId,
198
- ...(capture.uniqueEventType?.removedWithEventTypeIds ?? [])];
199
- return [...constrained, ...removedWith].some(id => id !== undefined && selectedIds.has(id));
200
- })) : compiled;
201
- for (const type of eventTypes) {
202
- for (const name of getRemovedConstraintNames(type)) {
203
- if (!definitions.has(name)) {
204
- throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
205
- 'Unresolved removal constraint name in the selected catalog.');
206
- }
207
- }
208
- }
209
- constraints = scenarioConstraints(definitions, selectedIds, constructorsById);
210
- } catch (error) {
211
- if (error instanceof UnsupportedEventSequenceOperation) throw error;
212
- throw new UnsupportedEventSequenceOperation('artifacts.constraints', 'compiler', `Invalid constraint definition: ${String(error)}.`);
213
- }
214
- }
267
+ const constraints = options.constraints === 'disabled' ? undefined
268
+ : compileScenarioConstraints(eventTypes, discoveredArtifacts, discovered);
215
269
  if (artifacts.eventTypeMigrations?.length) {
216
270
  throw new UnsupportedEventSequenceOperation('artifacts.eventTypeMigrations', artifacts.eventTypeMigrations.map(type => type.name).join(', '),
217
271
  'Migrations are not fixture-backed.');
@@ -0,0 +1,68 @@
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 { ConstraintViolation } from '@cratis/chronicle.contracts';
5
+ import type { AppendedEvent } from '../events/AppendedEvent.js';
6
+ import type { ConstraintCapture } from '../events/constraints/ConstraintBuilder.js';
7
+ import { eventTypeScopeKey, scopeIndex } from './ConstraintScope.js';
8
+
9
+ const unavailable = '18446744073709551615';
10
+
11
+ /** Tracks unique event type cycles within one append over committed history. */
12
+ export class EventTypeConstraintClaims {
13
+ private readonly _stagedCycles = new Map<string, Map<string, Map<string, 'open' | 'released'>>>();
14
+
15
+ constructor(private readonly _definitions: ReadonlyMap<string, ConstraintCapture>,
16
+ private readonly _history: readonly AppendedEvent[]) { }
17
+
18
+ validate(name: string, definition: ConstraintCapture, event: AppendedEvent): ConstraintViolation[] {
19
+ const uniqueType = definition.uniqueEventType;
20
+ if (!uniqueType) return [];
21
+ const type = event.eventType.id.value;
22
+ if (!(uniqueType.eventTypeIds ?? [uniqueType.eventTypeId]).includes(type)) return [];
23
+ const source = event.context.eventSourceId;
24
+ const scope = eventTypeScopeKey(definition.scope, event.context);
25
+ const first = this.firstCoveredEvent(definition, source, scope);
26
+ const cycles = scopeIndex(this._stagedCycles, name, scope, () => new Map<string, 'open' | 'released'>());
27
+ // A cycle state recorded earlier in this append overrides durable history.
28
+ if (this.isClaimed(cycles.get(source), first)) {
29
+ // Durable storage supplies the sequence even when a staged claim causes rejection.
30
+ const sequence = first?.context.sequenceNumber.toString() ?? unavailable;
31
+ return [{ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 2,
32
+ ConstraintName: name,
33
+ Message: `Event '${type}' violated a unique event type constraint on sequence number ${sequence}`,
34
+ Details: {} }];
35
+ }
36
+ cycles.set(source, 'open');
37
+ return [];
38
+ }
39
+
40
+ release(event: AppendedEvent): void {
41
+ for (const [name, definition] of this._definitions) {
42
+ if (definition.uniqueEventType?.removedWithEventTypeIds?.includes(event.eventType.id.value)) {
43
+ const cycles = scopeIndex(this._stagedCycles, name, eventTypeScopeKey(definition.scope, event.context),
44
+ () => new Map<string, 'open' | 'released'>());
45
+ cycles.set(event.context.eventSourceId, 'released');
46
+ }
47
+ }
48
+ }
49
+
50
+ private firstCoveredEvent(definition: ConstraintCapture, source: string, scope: string): AppendedEvent | undefined {
51
+ const uniqueType = definition.uniqueEventType!;
52
+ const covered = uniqueType.eventTypeIds ?? [uniqueType.eventTypeId];
53
+ const removals = uniqueType.removedWithEventTypeIds ?? [];
54
+ // Durable answer: the earliest covered event after the latest removal for this source.
55
+ let first: AppendedEvent | undefined;
56
+ for (const prior of this._history) {
57
+ if (prior.context.eventSourceId !== source || eventTypeScopeKey(definition.scope, prior.context) !== scope) continue;
58
+ const priorType = prior.eventType.id.value;
59
+ if (removals.includes(priorType)) first = undefined;
60
+ else if (!first && covered.includes(priorType)) first = prior;
61
+ }
62
+ return first;
63
+ }
64
+
65
+ private isClaimed(state: 'open' | 'released' | undefined, first: AppendedEvent | undefined): boolean {
66
+ return state === 'open' || state === undefined && first !== undefined;
67
+ }
68
+ }