@cratis/chronicle 6.67.7 → 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.
- package/ChronicleClient.ts +14 -1
- package/ChronicleOptions.ts +12 -0
- package/EventStoreNamespaceResolver.ts +19 -0
- package/dist/ChronicleClient.d.ts +1 -0
- package/dist/ChronicleClient.d.ts.map +1 -1
- package/dist/ChronicleClient.js +14 -1
- package/dist/ChronicleClient.js.map +1 -1
- package/dist/ChronicleOptions.d.ts +8 -0
- package/dist/ChronicleOptions.d.ts.map +1 -1
- package/dist/ChronicleOptions.js +8 -0
- package/dist/ChronicleOptions.js.map +1 -1
- package/dist/EventStoreNamespaceResolver.d.ts +16 -0
- package/dist/EventStoreNamespaceResolver.d.ts.map +1 -0
- package/dist/EventStoreNamespaceResolver.js +4 -0
- package/dist/EventStoreNamespaceResolver.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/testing/ConstraintKey.d.ts.map +1 -1
- package/dist/testing/ConstraintKey.js +24 -14
- package/dist/testing/ConstraintKey.js.map +1 -1
- package/dist/testing/EventScenario.d.ts.map +1 -1
- package/dist/testing/EventScenario.js +100 -67
- package/dist/testing/EventScenario.js.map +1 -1
- package/dist/testing/EventTypeConstraintClaims.d.ts +15 -0
- package/dist/testing/EventTypeConstraintClaims.d.ts.map +1 -0
- package/dist/testing/EventTypeConstraintClaims.js +66 -0
- package/dist/testing/EventTypeConstraintClaims.js.map +1 -0
- package/dist/testing/InProcessConstraints.d.ts.map +1 -1
- package/dist/testing/InProcessConstraints.js +8 -91
- package/dist/testing/InProcessConstraints.js.map +1 -1
- package/dist/testing/PropertyConstraintClaims.d.ts +17 -0
- package/dist/testing/PropertyConstraintClaims.d.ts.map +1 -0
- package/dist/testing/PropertyConstraintClaims.js +69 -0
- package/dist/testing/PropertyConstraintClaims.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/for_ChronicleClient/when_resolving_a_namespace.spec.ts +198 -0
- package/index.ts +1 -0
- package/package.json +1 -1
- package/testing/ConstraintKey.ts +26 -11
- package/testing/EventScenario.ts +120 -66
- package/testing/EventTypeConstraintClaims.ts +68 -0
- package/testing/InProcessConstraints.ts +7 -86
- package/testing/PropertyConstraintClaims.ts +75 -0
package/testing/ConstraintKey.ts
CHANGED
|
@@ -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 (
|
|
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 (
|
|
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
|
|
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.
|
package/testing/EventScenario.ts
CHANGED
|
@@ -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
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
74
|
-
|
|
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 && !
|
|
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
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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]
|
|
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 &&
|
|
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
|
|
152
|
+
const schemas = propertySchemas(entry, constructors);
|
|
125
153
|
validateKeySchemas(name, schemas, { scoped, definitions,
|
|
126
|
-
isolated:
|
|
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
|
-
|
|
172
|
-
|
|
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
|
+
}
|
|
@@ -8,13 +8,12 @@ import { resolveConstraintMessage } from '../events/constraints/Constraints.js';
|
|
|
8
8
|
import type { ConstraintViolation } from '../eventSequences/ConstraintViolation.js';
|
|
9
9
|
import type { JsonSchema } from '../schemas/JsonSchema.js';
|
|
10
10
|
import { UnsupportedEventSequenceOperation } from './UnsupportedEventSequenceOperation.js';
|
|
11
|
-
import { eventTypeScopeKey, propertyScopeKey, scopeIndex } from './ConstraintScope.js';
|
|
12
11
|
import { supportsPropertyOverlap } from './PropertyDefinitionSupport.js';
|
|
13
|
-
import {
|
|
12
|
+
import { PropertyConstraintClaims } from './PropertyConstraintClaims.js';
|
|
13
|
+
import { EventTypeConstraintClaims } from './EventTypeConstraintClaims.js';
|
|
14
14
|
|
|
15
15
|
export type WireConstraintViolation = ContractsConstraintViolation;
|
|
16
16
|
|
|
17
|
-
const unavailable = '18446744073709551615';
|
|
18
17
|
/** Narrow, fixture-backed constraint validation over serialized event snapshots. */
|
|
19
18
|
export class InProcessConstraints {
|
|
20
19
|
private readonly _constrainedProperties = new Map<string, Set<string>>();
|
|
@@ -124,95 +123,17 @@ export class InProcessConstraints {
|
|
|
124
123
|
/** Validate against committed history and all earlier entries of this append, without changing state. */
|
|
125
124
|
validate(history: readonly AppendedEvent[], incoming: readonly AppendedEvent[]): WireConstraintViolation[] {
|
|
126
125
|
const violations: WireConstraintViolation[] = [];
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const owners = new Map<string, Map<string, Map<string, { key: string; sequence: string }>>>();
|
|
130
|
-
for (const [name, definition] of this._definitions) {
|
|
131
|
-
if (!definition.uniqueConstraint) continue;
|
|
132
|
-
const unique = definition.uniqueConstraint;
|
|
133
|
-
const removals = new Set([unique.removedWithEventTypeId, ...(unique.removedWithEventTypeIds ?? [])]);
|
|
134
|
-
for (const prior of history) {
|
|
135
|
-
const type = prior.eventType.id.value;
|
|
136
|
-
const source = prior.context.eventSourceId;
|
|
137
|
-
const claims = scopeIndex(owners, name, propertyScopeKey(definition.scope, prior.context),
|
|
138
|
-
() => new Map<string, { key: string; sequence: string }>());
|
|
139
|
-
if (removals.has(type)) {
|
|
140
|
-
claims.delete(source);
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
const properties = unique.eventDefinitions.find(entry => entry.eventTypeId === type)?.properties;
|
|
144
|
-
if (properties === undefined) continue;
|
|
145
|
-
claims.set(source, { key: claimOf(name, definition, prior, { schema: this._schemas.get(type), isolated: this._definitions.size === 1 })!.key,
|
|
146
|
-
sequence: prior.context.sequenceNumber.toString() });
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
const stagedKeys = new Map<string, Map<string, Map<string, string>>>();
|
|
150
|
-
const stagedCycles = new Map<string, Map<string, Map<string, 'open' | 'released'>>>();
|
|
126
|
+
const propertyClaims = new PropertyConstraintClaims(this._definitions, this._schemas, history);
|
|
127
|
+
const eventTypeClaims = new EventTypeConstraintClaims(this._definitions, history);
|
|
151
128
|
for (const event of incoming) {
|
|
152
|
-
const type = event.eventType.id.value;
|
|
153
|
-
const source = event.context.eventSourceId;
|
|
154
129
|
const violationCount = violations.length;
|
|
155
130
|
for (const [name, definition] of this._definitions) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const key = claim.key;
|
|
159
|
-
const scope = propertyScopeKey(definition.scope, event.context);
|
|
160
|
-
const durableClaims = owners.get(name)?.get(scope);
|
|
161
|
-
const existing = [...(durableClaims?.entries() ?? [])].find(([, claim]) => claim.key === key);
|
|
162
|
-
const batchClaims = scopeIndex(stagedKeys, name, scope, () => new Map<string, string>());
|
|
163
|
-
const batchOwner = batchClaims.get(key);
|
|
164
|
-
if (existing && existing[0] !== source || batchOwner !== undefined && batchOwner !== source) {
|
|
165
|
-
// One violation per declared property, in declared order, each with its own original value.
|
|
166
|
-
const sequence = existing?.[1].sequence ?? unavailable;
|
|
167
|
-
for (const { property, raw } of claim.parts) {
|
|
168
|
-
violations.push({ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 1,
|
|
169
|
-
ConstraintName: name,
|
|
170
|
-
Message: `Event '${type}' on member '${property}' violated a unique constraint on sequence number ${sequence}`,
|
|
171
|
-
Details: { PropertyName: property, PropertyValue: raw } });
|
|
172
|
-
}
|
|
173
|
-
} else {
|
|
174
|
-
batchClaims.set(key, source);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
const uniqueType = definition.uniqueEventType;
|
|
178
|
-
if (uniqueType && (uniqueType.eventTypeIds ?? [uniqueType.eventTypeId]).includes(type)) {
|
|
179
|
-
const covered = uniqueType.eventTypeIds ?? [uniqueType.eventTypeId];
|
|
180
|
-
const removals = uniqueType.removedWithEventTypeIds ?? [];
|
|
181
|
-
// Durable answer: the earliest covered event after the latest removal for this source.
|
|
182
|
-
const scope = eventTypeScopeKey(definition.scope, event.context);
|
|
183
|
-
let first: AppendedEvent | undefined;
|
|
184
|
-
for (const prior of history) {
|
|
185
|
-
if (prior.context.eventSourceId !== source || eventTypeScopeKey(definition.scope, prior.context) !== scope) continue;
|
|
186
|
-
const priorType = prior.eventType.id.value;
|
|
187
|
-
if (removals.includes(priorType)) first = undefined;
|
|
188
|
-
else if (!first && covered.includes(priorType)) first = prior;
|
|
189
|
-
}
|
|
190
|
-
const cycles = scopeIndex(stagedCycles, name, scope, () => new Map<string, 'open' | 'released'>());
|
|
191
|
-
const state = cycles.get(source);
|
|
192
|
-
// A cycle state recorded earlier in this append overrides durable history.
|
|
193
|
-
if (state === 'open' || state === undefined && first) {
|
|
194
|
-
// Durable storage supplies the sequence even when a staged claim causes rejection.
|
|
195
|
-
const sequence = first?.context.sequenceNumber.toString() ?? unavailable;
|
|
196
|
-
violations.push({ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 2,
|
|
197
|
-
ConstraintName: name,
|
|
198
|
-
Message: `Event '${type}' violated a unique event type constraint on sequence number ${sequence}`,
|
|
199
|
-
Details: {} });
|
|
200
|
-
} else {
|
|
201
|
-
cycles.set(source, 'open');
|
|
202
|
-
}
|
|
203
|
-
}
|
|
131
|
+
violations.push(...propertyClaims.validate(name, definition, event));
|
|
132
|
+
violations.push(...eventTypeClaims.validate(name, definition, event));
|
|
204
133
|
}
|
|
205
134
|
// Kernel batch observers release a cycle only after the entire event validates.
|
|
206
135
|
// A covered-and-removal event first attempts its claim, then releases it.
|
|
207
|
-
if (violations.length === violationCount)
|
|
208
|
-
for (const [name, definition] of this._definitions) {
|
|
209
|
-
if (definition.uniqueEventType?.removedWithEventTypeIds?.includes(type)) {
|
|
210
|
-
const cycles = scopeIndex(stagedCycles, name, eventTypeScopeKey(definition.scope, event.context),
|
|
211
|
-
() => new Map<string, 'open' | 'released'>());
|
|
212
|
-
cycles.set(source, 'released');
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
}
|
|
136
|
+
if (violations.length === violationCount) eventTypeClaims.release(event);
|
|
216
137
|
}
|
|
217
138
|
return violations;
|
|
218
139
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
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 type { JsonSchema } from '../schemas/JsonSchema.js';
|
|
8
|
+
import { claimOf } from './ConstraintKey.js';
|
|
9
|
+
import { propertyScopeKey, scopeIndex } from './ConstraintScope.js';
|
|
10
|
+
|
|
11
|
+
const unavailable = '18446744073709551615';
|
|
12
|
+
|
|
13
|
+
/** Rebuilds durable property ownership and keeps append-local claims independent. */
|
|
14
|
+
export class PropertyConstraintClaims {
|
|
15
|
+
private readonly _owners = new Map<string, Map<string, Map<string, { key: string; sequence: string }>>>();
|
|
16
|
+
private readonly _stagedKeys = new Map<string, Map<string, Map<string, string>>>();
|
|
17
|
+
|
|
18
|
+
constructor(private readonly _definitions: ReadonlyMap<string, ConstraintCapture>,
|
|
19
|
+
private readonly _schemas: ReadonlyMap<string, JsonSchema>, history: readonly AppendedEvent[]) {
|
|
20
|
+
// Durable ownership is one claim per source, not one entry per historical value.
|
|
21
|
+
// Batch claims remain independent and are never released.
|
|
22
|
+
for (const [name, definition] of _definitions) {
|
|
23
|
+
if (definition.uniqueConstraint) this.replay(name, definition, history);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
validate(name: string, definition: ConstraintCapture, event: AppendedEvent): ConstraintViolation[] {
|
|
28
|
+
const type = event.eventType.id.value;
|
|
29
|
+
const source = event.context.eventSourceId;
|
|
30
|
+
const claim = definition.uniqueConstraint && claimOf(name, definition, event, this.keyOptions(type));
|
|
31
|
+
if (!claim) return [];
|
|
32
|
+
const key = claim.key;
|
|
33
|
+
const scope = propertyScopeKey(definition.scope, event.context);
|
|
34
|
+
const durableClaims = this._owners.get(name)?.get(scope);
|
|
35
|
+
const existing = [...(durableClaims?.entries() ?? [])].find(([, claim]) => claim.key === key);
|
|
36
|
+
const batchClaims = scopeIndex(this._stagedKeys, name, scope, () => new Map<string, string>());
|
|
37
|
+
if (this.isOtherOwner(existing?.[0], source) || this.isOtherOwner(batchClaims.get(key), source)) {
|
|
38
|
+
// One violation per declared property, in declared order, each with its own original value.
|
|
39
|
+
const sequence = existing?.[1].sequence ?? unavailable;
|
|
40
|
+
return claim.parts.map(({ property, raw }) => ({ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 1,
|
|
41
|
+
ConstraintName: name,
|
|
42
|
+
Message: `Event '${type}' on member '${property}' violated a unique constraint on sequence number ${sequence}`,
|
|
43
|
+
Details: { PropertyName: property, PropertyValue: raw } }));
|
|
44
|
+
}
|
|
45
|
+
batchClaims.set(key, source);
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private replay(name: string, definition: ConstraintCapture, history: readonly AppendedEvent[]): void {
|
|
50
|
+
const unique = definition.uniqueConstraint!;
|
|
51
|
+
const removals = new Set([unique.removedWithEventTypeId, ...(unique.removedWithEventTypeIds ?? [])]);
|
|
52
|
+
for (const prior of history) {
|
|
53
|
+
const type = prior.eventType.id.value;
|
|
54
|
+
const source = prior.context.eventSourceId;
|
|
55
|
+
const claims = scopeIndex(this._owners, name, propertyScopeKey(definition.scope, prior.context),
|
|
56
|
+
() => new Map<string, { key: string; sequence: string }>());
|
|
57
|
+
if (removals.has(type)) {
|
|
58
|
+
claims.delete(source);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const properties = unique.eventDefinitions.find(entry => entry.eventTypeId === type)?.properties;
|
|
62
|
+
if (properties === undefined) continue;
|
|
63
|
+
claims.set(source, { key: claimOf(name, definition, prior, this.keyOptions(type))!.key,
|
|
64
|
+
sequence: prior.context.sequenceNumber.toString() });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private keyOptions(type: string) {
|
|
69
|
+
return { schema: this._schemas.get(type), isolated: this._definitions.size === 1 };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private isOtherOwner(owner: string | undefined, source: string): boolean {
|
|
73
|
+
return owner !== undefined && owner !== source;
|
|
74
|
+
}
|
|
75
|
+
}
|