@cratis/chronicle 6.67.7 → 6.68.1
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 +32 -17
- 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/MeasuredCaseFolding.d.ts +14 -0
- package/dist/testing/MeasuredCaseFolding.d.ts.map +1 -0
- package/dist/testing/MeasuredCaseFolding.js +17 -0
- package/dist/testing/MeasuredCaseFolding.js.map +1 -0
- 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 +34 -15
- package/testing/EventScenario.fixtures.spec.ts +1 -1
- package/testing/EventScenario.ts +120 -66
- package/testing/EventTypeConstraintClaims.ts +68 -0
- package/testing/InProcessConstraints.ts +7 -86
- package/testing/MeasuredCaseFolding.ts +22 -0
- package/testing/PropertyConstraintClaims.ts +75 -0
- package/testing/for_EventScenario/when_appending_case_folded_text/case_folded_text.fixture.ts +160 -0
- package/testing/for_EventScenario/when_appending_case_folded_text/with_case_folded_text.legacy.spec.ts +14 -0
- package/testing/for_EventScenario/when_appending_case_folded_text/with_case_folded_text.standard.spec.ts +13 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
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 { createHash } from 'node:crypto';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import type { Constructor } from '@cratis/fundamentals';
|
|
7
|
+
import { beforeEach, chai, describe, it, vi, type Assertion } from 'vitest';
|
|
8
|
+
import type { AppendResult } from '../../../eventSequences/AppendResult.js';
|
|
9
|
+
import { constraint } from '../../../events/constraints/constraint.js';
|
|
10
|
+
import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
|
|
11
|
+
import { EventScenario, UnsupportedEventSequenceOperation } from '../../index.js';
|
|
12
|
+
import { InProcessConstraints } from '../../InProcessConstraints.js';
|
|
13
|
+
import { measuredLowerInvariant } from '../../MeasuredCaseFolding.js';
|
|
14
|
+
|
|
15
|
+
chai.should();
|
|
16
|
+
const should = (value: unknown): Assertion => (value as { should: Assertion }).should;
|
|
17
|
+
type TextEvent = { key: string };
|
|
18
|
+
type PairEvent = { key: string; other: string };
|
|
19
|
+
type Types = { text: Constructor<TextEvent>; pair: Constructor<PairEvent> };
|
|
20
|
+
type Operation = { mode: string; events: Array<{ source: string; content: string }> };
|
|
21
|
+
type History = { source: string; sequence: string; content: Record<string, unknown>; hash: string | undefined };
|
|
22
|
+
type WireViolation = { ConstraintName: string; Message: string; Details: Record<string, string> };
|
|
23
|
+
type Outcome = { success: boolean; sequences: string[]; wireViolations: WireViolation[]; history: History[]; next: string };
|
|
24
|
+
type Observation = { input: string; lowered: string; utf8Sha256: string };
|
|
25
|
+
const fixture = JSON.parse(readFileSync(new URL('../../fixtures/constraints-ignore-casing-measurements.json', import.meta.url), 'utf8')) as {
|
|
26
|
+
fieldConstraintCases: Array<{ name: string; localSteps: number; operations: Operation[] }>;
|
|
27
|
+
expected: Array<{ steps: Outcome[]; casingObservations: Observation[] }>;
|
|
28
|
+
};
|
|
29
|
+
const unmeasuredNeighbours = ['\u00c8', '\u00e8', '\u00d8', '\u00de', '\u00e0', '\u0300', '\u0302', '\u0130', '\u0131', '\u03a3', '\u03c3',
|
|
30
|
+
'\u03c2', '\u1e9e', '\u212a', '\u6771', '\u4eac', '\u{10400}', '\u{1f600}', '\ud83d', '\ude00', '\ude00\ud83d', '\u00c9\ud83d', '\u00c9\u6771'];
|
|
31
|
+
|
|
32
|
+
function definition(type: Constructor, mode: 'ignoreCasing' | 'scoped' | 'removable' | 'composite' | 'overlapping', name = 'OracleFieldKey'): Constructor {
|
|
33
|
+
class Definition {
|
|
34
|
+
define(builder: IConstraintBuilder) {
|
|
35
|
+
if (mode === 'scoped') builder.perEventSourceType();
|
|
36
|
+
builder.unique(key => {
|
|
37
|
+
if (mode === 'composite') key.on(type as Constructor<PairEvent>, event => event.key, event => event.other);
|
|
38
|
+
else key.on(type as Constructor<TextEvent>, event => event.key);
|
|
39
|
+
key.ignoreCasing();
|
|
40
|
+
if (mode === 'removable') key.removedWith(type);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
constraint(name)(Definition);
|
|
45
|
+
return Definition;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function scenarioFor(types: Types, mode: Parameters<typeof definition>[1] = 'ignoreCasing'): EventScenario {
|
|
49
|
+
const type = mode === 'composite' ? types.pair : types.text;
|
|
50
|
+
const constraints = mode === 'overlapping' ? [definition(type, 'ignoreCasing'), definition(type, 'ignoreCasing', 'OtherCasedKey')] : [definition(type, mode)];
|
|
51
|
+
return new EventScenario({ artifacts: { eventTypes: [type], constraints } });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function textOf(type: Constructor<TextEvent>, content: string): TextEvent {
|
|
55
|
+
return Object.assign(new type(), JSON.parse(content));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function historyOf(scenario: EventScenario): History[] {
|
|
59
|
+
return scenario.appendedEvents.map(event => ({ source: event.context.eventSourceId,
|
|
60
|
+
sequence: event.context.sequenceNumber.toString(), content: event.content, hash: event.context.hash }));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function append(scenario: EventScenario, type: Constructor<TextEvent>, operation: Operation): Promise<AppendResult[]> {
|
|
64
|
+
const events = operation.events.map(entry => ({ eventSourceId: entry.source, event: textOf(type, entry.content) }));
|
|
65
|
+
return operation.mode === 'single' ? [await scenario.append(events[0].eventSourceId, events[0].event)] : scenario.appendMany(events);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function replay(types: Types, index: number): void {
|
|
69
|
+
const test = fixture.fieldConstraintCases[index];
|
|
70
|
+
it(`should match collision details, sequences, hashes and rollback through the production serializer for ${test.name}`, async () => {
|
|
71
|
+
const validate = vi.spyOn(InProcessConstraints.prototype, 'validate');
|
|
72
|
+
const scenario = scenarioFor(types);
|
|
73
|
+
should(test.localSteps).equal(test.operations.length);
|
|
74
|
+
for (const [step, operation] of test.operations.entries()) {
|
|
75
|
+
const results = await append(scenario, types.text, operation);
|
|
76
|
+
const expected = fixture.expected[index].steps[step];
|
|
77
|
+
should(results.every(result => result.isSuccess === expected.success)).equal(true);
|
|
78
|
+
should(results.map(result => result.sequenceNumber.value.toString())).deep.equal(
|
|
79
|
+
expected.success ? expected.sequences : results.map(() => '0'));
|
|
80
|
+
const raw = validate.mock.results.at(-1)!.value as ReturnType<InProcessConstraints['validate']>;
|
|
81
|
+
should(raw.map(violation => ({ ...violation, SequenceNumber: violation.SequenceNumber.toString() }))).deep.equal(expected.wireViolations);
|
|
82
|
+
should(historyOf(scenario)).deep.equal(expected.history);
|
|
83
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value.toString()).equal(expected.next);
|
|
84
|
+
}
|
|
85
|
+
validate.mockRestore();
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function observe(index: number): void {
|
|
90
|
+
const test = fixture.fieldConstraintCases[index];
|
|
91
|
+
it(`should map every ${test.name} input to the lowered text and hash the oracle observed from the kernel operation`, () => {
|
|
92
|
+
const observations = fixture.expected[index].casingObservations;
|
|
93
|
+
should(observations.length).greaterThan(0);
|
|
94
|
+
for (const observation of observations) {
|
|
95
|
+
should(measuredLowerInvariant(observation.input)).equal(observation.lowered);
|
|
96
|
+
should(createHash('sha256').update(measuredLowerInvariant(observation.input)).digest('hex')).equal(observation.utf8Sha256);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function rejectUnmeasured(types: Types): void {
|
|
102
|
+
for (const value of unmeasuredNeighbours) {
|
|
103
|
+
describe(`when the ignoreCasing key is the unmeasured ${JSON.stringify(value)}`, () => {
|
|
104
|
+
let scenario: EventScenario;
|
|
105
|
+
beforeEach(() => { scenario = scenarioFor(types); });
|
|
106
|
+
const good = (key: string) => Object.assign(new types.text(), { key });
|
|
107
|
+
const invalid = (): TextEvent => Object.assign(new types.text(), { key: value });
|
|
108
|
+
for (const mode of ['single', 'batch']) {
|
|
109
|
+
it(`should keep history, results, the next sequence and claim ownership after a rejected ${mode} append`, async () => {
|
|
110
|
+
await scenario.append('A', good('\u00c9'));
|
|
111
|
+
const history = historyOf(scenario);
|
|
112
|
+
const results = [...scenario.results];
|
|
113
|
+
const pending = mode === 'single' ? scenario.append('B', invalid())
|
|
114
|
+
: scenario.appendMany([{ eventSourceId: 'B', event: good('ok') }, { eventSourceId: 'C', event: invalid() }]);
|
|
115
|
+
should(await pending.then(() => undefined, error => error)).instanceOf(UnsupportedEventSequenceOperation);
|
|
116
|
+
should(historyOf(scenario)).deep.equal(history);
|
|
117
|
+
should(scenario.results).deep.equal(results);
|
|
118
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(1n);
|
|
119
|
+
should((await scenario.append('B', good('ok'))).isSuccess).equal(true);
|
|
120
|
+
should((await scenario.append('C', good('\u00e9'))).constraintViolations).have.lengthOf(1);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
it('should reject a failing given atomically and leave its valid key claimable', async () => {
|
|
124
|
+
const error = await scenario.given.forEventSource('A').events(good('\u00c9'), invalid()).then(() => undefined, error => error);
|
|
125
|
+
should(error).instanceOf(UnsupportedEventSequenceOperation);
|
|
126
|
+
should(scenario.appendedEvents).have.lengthOf(0);
|
|
127
|
+
should(scenario.results).have.lengthOf(0);
|
|
128
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(0n);
|
|
129
|
+
should((await scenario.append('B', good('\u00e9'))).isSuccess).equal(true);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function rejectShapes(types: Types): void {
|
|
136
|
+
for (const mode of ['scoped', 'removable', 'composite', 'overlapping'] as const) {
|
|
137
|
+
for (const value of ['\u00c9', '\u00df', '\u00f8', '\u0301']) {
|
|
138
|
+
it(`should keep new ${JSON.stringify(value)} rejected for ${mode} ignoreCasing definitions`, async () => {
|
|
139
|
+
const event = mode === 'composite' ? Object.assign(new types.pair(), { key: value, other: 'x' })
|
|
140
|
+
: Object.assign(new types.text(), { key: value });
|
|
141
|
+
const error = await Promise.resolve().then(() => scenarioFor(types, mode))
|
|
142
|
+
.then(scenario => scenario.append('A', event)).then(() => undefined, error => error);
|
|
143
|
+
should(error).instanceOf(UnsupportedEventSequenceOperation);
|
|
144
|
+
should(String(error)).include('artifacts.constraints');
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
it('should keep the ASCII counterpart of the scoped and composite shapes passing, so the rejections are about the key', async () => {
|
|
149
|
+
should((await scenarioFor(types, 'scoped').append('A', Object.assign(new types.text(), { key: 'Ab' }))).isSuccess).equal(true);
|
|
150
|
+
should((await scenarioFor(types, 'composite').append('A', Object.assign(new types.pair(), { key: 'Ab', other: 'x' }))).isSuccess).equal(true);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function caseFoldedText(types: Types): void {
|
|
155
|
+
describe('when replaying the measured ignoreCasing keys', () => {
|
|
156
|
+
for (const index of fixture.fieldConstraintCases.keys()) { replay(types, index); observe(index); }
|
|
157
|
+
});
|
|
158
|
+
rejectUnmeasured(types);
|
|
159
|
+
describe('when the measured keys are used in an unmeasured definition shape', () => rejectShapes(types));
|
|
160
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
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 { field } from '@cratis/fundamentals';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { caseFoldedText } from './case_folded_text.fixture.js';
|
|
8
|
+
|
|
9
|
+
class TextClaimed { @field(String) key = ''; }
|
|
10
|
+
eventType('OracleFieldText')(TextClaimed);
|
|
11
|
+
class PairClaimed { @field(String) key = ''; @field(String) other = ''; }
|
|
12
|
+
eventType('OracleCasingPair')(PairClaimed);
|
|
13
|
+
|
|
14
|
+
caseFoldedText({ text: TextClaimed, pair: PairClaimed });
|
|
@@ -0,0 +1,13 @@
|
|
|
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 { field } from '@cratis/fundamentals';
|
|
5
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
6
|
+
import { caseFoldedText } from './case_folded_text.fixture.js';
|
|
7
|
+
|
|
8
|
+
@eventType('OracleFieldText')
|
|
9
|
+
class TextClaimed { @field(String) key = ''; }
|
|
10
|
+
@eventType('OracleCasingPair')
|
|
11
|
+
class PairClaimed { @field(String) key = ''; @field(String) other = ''; }
|
|
12
|
+
|
|
13
|
+
caseFoldedText({ text: TextClaimed, pair: PairClaimed });
|