@cratis/chronicle 6.69.0 → 6.70.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 +1 -1
- package/ChronicleOptions.ts +9 -0
- package/EventStore.ts +6 -3
- package/dist/ChronicleClient.js +1 -1
- package/dist/ChronicleClient.js.map +1 -1
- package/dist/ChronicleOptions.d.ts +4 -0
- package/dist/ChronicleOptions.d.ts.map +1 -1
- package/dist/ChronicleOptions.js +5 -0
- package/dist/ChronicleOptions.js.map +1 -1
- package/dist/EventStore.d.ts +3 -1
- package/dist/EventStore.d.ts.map +1 -1
- package/dist/EventStore.js +6 -3
- package/dist/EventStore.js.map +1 -1
- package/dist/eventSequences/AppendMetricsContext.d.ts +7 -0
- package/dist/eventSequences/AppendMetricsContext.d.ts.map +1 -0
- package/dist/eventSequences/AppendMetricsContext.js +4 -0
- package/dist/eventSequences/AppendMetricsContext.js.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategies.d.ts +8 -0
- package/dist/eventSequences/ConcurrencyScopeStrategies.d.ts.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategies.js +11 -0
- package/dist/eventSequences/ConcurrencyScopeStrategies.js.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategy.d.ts +11 -0
- package/dist/eventSequences/ConcurrencyScopeStrategy.d.ts.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategy.js +4 -0
- package/dist/eventSequences/ConcurrencyScopeStrategy.js.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategyContext.d.ts +15 -0
- package/dist/eventSequences/ConcurrencyScopeStrategyContext.d.ts.map +1 -0
- package/dist/eventSequences/ConcurrencyScopeStrategyContext.js +4 -0
- package/dist/eventSequences/ConcurrencyScopeStrategyContext.js.map +1 -0
- package/dist/eventSequences/EventLog.d.ts +2 -1
- package/dist/eventSequences/EventLog.d.ts.map +1 -1
- package/dist/eventSequences/EventLog.js +3 -2
- package/dist/eventSequences/EventLog.js.map +1 -1
- package/dist/eventSequences/EventSequence.d.ts +3 -1
- package/dist/eventSequences/EventSequence.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.js +27 -21
- package/dist/eventSequences/EventSequence.js.map +1 -1
- package/dist/eventSequences/index.d.ts +3 -0
- package/dist/eventSequences/index.d.ts.map +1 -1
- package/dist/eventSequences/index.js +1 -0
- package/dist/eventSequences/index.js.map +1 -1
- package/dist/eventSequences/planConcurrencyScopeStrategies.d.ts +12 -0
- package/dist/eventSequences/planConcurrencyScopeStrategies.d.ts.map +1 -0
- package/dist/eventSequences/planConcurrencyScopeStrategies.js +21 -0
- package/dist/eventSequences/planConcurrencyScopeStrategies.js.map +1 -0
- package/dist/eventSequences/resolveConcurrencyScope.d.ts +7 -0
- package/dist/eventSequences/resolveConcurrencyScope.d.ts.map +1 -0
- package/dist/eventSequences/resolveConcurrencyScope.js +16 -0
- package/dist/eventSequences/resolveConcurrencyScope.js.map +1 -0
- package/dist/testing/MeasuredConstraintKeys.d.ts.map +1 -1
- package/dist/testing/MeasuredConstraintKeys.js +3 -2
- package/dist/testing/MeasuredConstraintKeys.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/eventSequences/AppendMetricsContext.ts +9 -0
- package/eventSequences/ConcurrencyScopeStrategies.ts +10 -0
- package/eventSequences/ConcurrencyScopeStrategy.ts +15 -0
- package/eventSequences/ConcurrencyScopeStrategyContext.ts +18 -0
- package/eventSequences/EventLog.ts +5 -2
- package/eventSequences/EventSequence.ts +29 -24
- package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/from_client_options.spec.ts +60 -0
- package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/given.fixture.ts +31 -0
- package/eventSequences/for_EventSequence/when_resolving_concurrency_scopes/strategies.spec.ts +174 -0
- package/eventSequences/index.ts +3 -0
- package/eventSequences/planConcurrencyScopeStrategies.ts +30 -0
- package/eventSequences/resolveConcurrencyScope.ts +23 -0
- package/package.json +1 -1
- package/testing/EventScenario.fixtures.spec.ts +1 -1
- package/testing/EventScenario.rejections.spec.ts +1 -1
- package/testing/MeasuredConstraintKeys.ts +3 -2
- package/testing/for_EventScenario/when_appending_case_sensitive_unicode/case_sensitive_unicode.fixture.ts +188 -0
- package/testing/for_EventScenario/when_appending_case_sensitive_unicode/with_case_sensitive_unicode.legacy.spec.ts +16 -0
- package/testing/for_EventScenario/when_appending_case_sensitive_unicode/with_case_sensitive_unicode.standard.spec.ts +15 -0
- package/testing/for_EventScenario/when_appending_field_types/field_key_measurements.fixture.ts +1 -1
|
@@ -0,0 +1,31 @@
|
|
|
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 { vi } from 'vitest';
|
|
5
|
+
import type { ChronicleConnection } from '../../../connection/index.js';
|
|
6
|
+
import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
|
|
7
|
+
import { ConcurrencyDimensions, eventSource, eventStream, EventSources } from '../../../eventSources/index.js';
|
|
8
|
+
import { eventType } from '../../../events/index.js';
|
|
9
|
+
import type { IUnitOfWorkManager } from '../../../transactions/index.js';
|
|
10
|
+
import { EventSequence, EventSequenceId, type ConcurrencyScopeStrategy } from '../../index.js';
|
|
11
|
+
|
|
12
|
+
export class Deposited { constructor(readonly amount = 1) {} }
|
|
13
|
+
eventType('ConcurrencyStrategyDeposited')(Deposited);
|
|
14
|
+
|
|
15
|
+
@eventSource({ name: 'Account' })
|
|
16
|
+
@eventStream('Transactions', { concurrency: ConcurrencyDimensions.eventSourceId | ConcurrencyDimensions.eventStreamType | ConcurrencyDimensions.eventStreamId })
|
|
17
|
+
class AccountEventSource {}
|
|
18
|
+
|
|
19
|
+
export const routing = { eventSource: AccountEventSource, eventStream: 'Transactions', streamId: 'tx-1' };
|
|
20
|
+
|
|
21
|
+
export async function create(strategy?: ConcurrencyScopeStrategy, tail = 7n) {
|
|
22
|
+
const append = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['append']>[0]) => ({ Response: { SequenceNumber: 0n } }));
|
|
23
|
+
const appendManyForEventSources = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['appendManyForEventSources']>[0]) => ({ Response: { SequenceNumbers: [0n, 1n] } }));
|
|
24
|
+
const tailSequenceNumber = vi.fn(async (_request: Parameters<ChronicleConnection['eventSequences']['tailSequenceNumber']>[0]) => ({ Data: { SequenceNumber: tail } }));
|
|
25
|
+
const connection = { eventSequences: { append, appendManyForEventSources, tailSequenceNumber } } as unknown as ChronicleConnection;
|
|
26
|
+
const sources = new EventSources('store', connection, { eventSources: [AccountEventSource] } as unknown as IClientArtifactsProvider);
|
|
27
|
+
await sources.discover();
|
|
28
|
+
const sequence = new EventSequence(EventSequenceId.eventLog, 'store', 'ns', connection, {} as IUnitOfWorkManager,
|
|
29
|
+
undefined, undefined, sources, [], strategy);
|
|
30
|
+
return { sequence, append, appendManyForEventSources, tailSequenceNumber };
|
|
31
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
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 { chai, describe, it, vi } from 'vitest';
|
|
5
|
+
import { ConcurrencyScopeStrategies, EventSequenceNumber, type ConcurrencyScopeStrategyContext } from '../../index.js';
|
|
6
|
+
import { create, Deposited, routing } from './given.fixture.js';
|
|
7
|
+
|
|
8
|
+
const should = chai.should();
|
|
9
|
+
|
|
10
|
+
for (const batch of [false, true]) {
|
|
11
|
+
const append = async (sequence: Awaited<ReturnType<typeof create>>['sequence']) => batch
|
|
12
|
+
? sequence.appendMany('a', [new Deposited()], routing)
|
|
13
|
+
: sequence.append('a', new Deposited(), routing);
|
|
14
|
+
|
|
15
|
+
describe(`when resolving ${batch ? 'batch' : 'single'} append concurrency scopes`, () => {
|
|
16
|
+
it('should preserve the default scoped tail and scope when optimistic is selected', async () => {
|
|
17
|
+
const original = await create();
|
|
18
|
+
const optimistic = await create(ConcurrencyScopeStrategies.optimistic);
|
|
19
|
+
await append(original.sequence);
|
|
20
|
+
await append(optimistic.sequence);
|
|
21
|
+
optimistic.tailSequenceNumber.mock.calls.should.deep.equal(original.tailSequenceNumber.mock.calls);
|
|
22
|
+
const tail = optimistic.tailSequenceNumber.mock.calls[0][0];
|
|
23
|
+
tail.EventSourceId.should.equal('a');
|
|
24
|
+
tail.EventStreamType.should.equal('Transactions');
|
|
25
|
+
tail.EventStreamId.should.equal('tx-1');
|
|
26
|
+
tail.EventSourceType.should.equal('');
|
|
27
|
+
if (batch) {
|
|
28
|
+
optimistic.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes.should.deep.equal(
|
|
29
|
+
original.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes);
|
|
30
|
+
} else {
|
|
31
|
+
optimistic.append.mock.calls[0][0].ConcurrencyScope.should.deep.equal(original.append.mock.calls[0][0].ConcurrencyScope);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('should preserve the first append guard on an empty scoped stream', async () => {
|
|
36
|
+
const c = await create(ConcurrencyScopeStrategies.optimistic, EventSequenceNumber.unset.value);
|
|
37
|
+
await append(c.sequence);
|
|
38
|
+
const scope = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
|
|
39
|
+
: c.append.mock.calls[0][0].ConcurrencyScope;
|
|
40
|
+
scope.ExpectsNoMatchingEvent.should.equal(true);
|
|
41
|
+
scope.SequenceNumber.should.equal(EventSequenceNumber.unset.value);
|
|
42
|
+
scope.EventStreamId.should.equal('tx-1');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
for (const strategy of [ConcurrencyScopeStrategies.none, () => undefined, async () => undefined]) {
|
|
46
|
+
it('should send no check and never read the tail when the strategy returns none', async () => {
|
|
47
|
+
const c = await create(strategy);
|
|
48
|
+
await append(c.sequence);
|
|
49
|
+
c.tailSequenceNumber.mock.calls.should.have.length(0);
|
|
50
|
+
const scope = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
|
|
51
|
+
: c.append.mock.calls[0][0].ConcurrencyScope;
|
|
52
|
+
// Preserve the existing wire representation of an absent scope (the no-check sentinel).
|
|
53
|
+
scope.SequenceNumber.should.equal(EventSequenceNumber.unset.value);
|
|
54
|
+
scope.ExpectsNoMatchingEvent.should.equal(false);
|
|
55
|
+
scope.EventSourceId.should.equal(false);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
for (const asynchronous of [false, true]) {
|
|
60
|
+
it(`should use a custom ${asynchronous ? 'async' : 'sync'} scope without default tail reads`, async () => {
|
|
61
|
+
const scope = { sequenceNumber: 3n, eventSourceId: true };
|
|
62
|
+
const strategy = vi.fn((context: ConcurrencyScopeStrategyContext) => {
|
|
63
|
+
context.eventSourceId.should.equal('a');
|
|
64
|
+
context.events.should.have.length(1);
|
|
65
|
+
context.events[0].event.should.be.instanceOf(Deposited);
|
|
66
|
+
context.options.should.equal(routing);
|
|
67
|
+
return asynchronous ? Promise.resolve(scope) : scope;
|
|
68
|
+
});
|
|
69
|
+
const c = await create(strategy);
|
|
70
|
+
await append(c.sequence);
|
|
71
|
+
strategy.mock.calls.should.have.length(1);
|
|
72
|
+
c.tailSequenceNumber.mock.calls.should.have.length(0);
|
|
73
|
+
const sent = batch ? c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope
|
|
74
|
+
: c.append.mock.calls[0][0].ConcurrencyScope;
|
|
75
|
+
sent.SequenceNumber.should.equal(3n);
|
|
76
|
+
sent.EventSourceId.should.equal(true);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it(`should fail closed when a custom strategy ${asynchronous ? 'rejects' : 'throws'}`, async () => {
|
|
80
|
+
const failure = new Error('scope unavailable');
|
|
81
|
+
const c = await create(() => {
|
|
82
|
+
if (asynchronous) return Promise.reject(failure);
|
|
83
|
+
throw failure;
|
|
84
|
+
});
|
|
85
|
+
let caught: unknown;
|
|
86
|
+
try { await append(c.sequence); } catch (error) { caught = error; }
|
|
87
|
+
should.equal(caught, failure);
|
|
88
|
+
c.append.mock.calls.should.have.length(0);
|
|
89
|
+
c.appendManyForEventSources.mock.calls.should.have.length(0);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
describe('when explicit scopes are supplied', () => {
|
|
96
|
+
it('should bypass a custom strategy for a single append', async () => {
|
|
97
|
+
const strategy = vi.fn(() => { throw new Error('must not run'); });
|
|
98
|
+
const c = await create(strategy);
|
|
99
|
+
await c.sequence.append('a', new Deposited(), { ...routing, concurrencyScope: { sequenceNumber: 4n } });
|
|
100
|
+
strategy.mock.calls.should.have.length(0);
|
|
101
|
+
c.tailSequenceNumber.mock.calls.should.have.length(0);
|
|
102
|
+
c.append.mock.calls[0][0].ConcurrencyScope.SequenceNumber.should.equal(4n);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
for (const strategy of [ConcurrencyScopeStrategies.optimistic, ConcurrencyScopeStrategies.none]) {
|
|
106
|
+
it('should preserve explicit scopes under built-in policies', async () => {
|
|
107
|
+
const c = await create(strategy);
|
|
108
|
+
await c.sequence.append('a', new Deposited(), { ...routing, concurrencyScope: { sequenceNumber: 4n } });
|
|
109
|
+
await c.sequence.appendMany('a', [new Deposited()], { ...routing, concurrencyScope: { sequenceNumber: 4n } });
|
|
110
|
+
c.tailSequenceNumber.mock.calls.should.have.length(0);
|
|
111
|
+
c.append.mock.calls[0][0].ConcurrencyScope.SequenceNumber.should.equal(4n);
|
|
112
|
+
c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes[0].Scope.SequenceNumber.should.equal(4n);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
it('should resolve only unscoped ids in a mixed batch and group their events', async () => {
|
|
117
|
+
const strategy = vi.fn(async (context: ConcurrencyScopeStrategyContext) => {
|
|
118
|
+
context.events.should.have.length(2);
|
|
119
|
+
const tail = await context.readTail(context.eventSourceId);
|
|
120
|
+
return { sequenceNumber: tail.value, eventSourceId: true };
|
|
121
|
+
});
|
|
122
|
+
const c = await create(strategy);
|
|
123
|
+
await c.sequence.appendMany([
|
|
124
|
+
{ eventSourceId: 'explicit', event: new Deposited() },
|
|
125
|
+
{ eventSourceId: 'derived', event: new Deposited() },
|
|
126
|
+
{ eventSourceId: 'derived', event: new Deposited() }
|
|
127
|
+
], { ...routing, concurrencyScopes: { explicit: { sequenceNumber: 2n } } });
|
|
128
|
+
strategy.mock.calls.should.have.length(1);
|
|
129
|
+
strategy.mock.calls[0][0].eventSourceId.should.equal('derived');
|
|
130
|
+
const scopes = c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes;
|
|
131
|
+
scopes.map(entry => [entry.EventSourceId, entry.Scope.SequenceNumber]).should.deep.equal([['explicit', 2n], ['derived', 7n]]);
|
|
132
|
+
c.tailSequenceNumber.mock.calls.should.have.length(1);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('should bypass the custom strategy when every id has an explicit shared scope', async () => {
|
|
136
|
+
const strategy = vi.fn(() => { throw new Error('must not run'); });
|
|
137
|
+
const c = await create(strategy);
|
|
138
|
+
await c.sequence.appendMany([
|
|
139
|
+
{ eventSourceId: 'a', event: new Deposited() },
|
|
140
|
+
{ eventSourceId: 'b', event: new Deposited() }
|
|
141
|
+
], { ...routing, concurrencyScope: { sequenceNumber: 4n } });
|
|
142
|
+
strategy.mock.calls.should.have.length(0);
|
|
143
|
+
c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes.map(entry => entry.Scope.SequenceNumber).should.deep.equal([4n, 4n]);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('should not append a partly resolved batch when a later strategy call fails', async () => {
|
|
147
|
+
const failure = new Error('second scope unavailable');
|
|
148
|
+
const c = await create(async context => {
|
|
149
|
+
if (context.eventSourceId === 'b') throw failure;
|
|
150
|
+
return { sequenceNumber: 2n };
|
|
151
|
+
});
|
|
152
|
+
let caught: unknown;
|
|
153
|
+
try {
|
|
154
|
+
await c.sequence.appendMany([
|
|
155
|
+
{ eventSourceId: 'a', event: new Deposited() },
|
|
156
|
+
{ eventSourceId: 'b', event: new Deposited() }
|
|
157
|
+
]);
|
|
158
|
+
} catch (error) { caught = error; }
|
|
159
|
+
should.equal(caught, failure);
|
|
160
|
+
c.appendManyForEventSources.mock.calls.should.have.length(0);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('should retain explicit ids and derive the rest using optimistic routing', async () => {
|
|
164
|
+
const c = await create();
|
|
165
|
+
await c.sequence.appendMany([
|
|
166
|
+
{ eventSourceId: 'explicit', event: new Deposited() },
|
|
167
|
+
{ eventSourceId: 'derived', event: new Deposited() }
|
|
168
|
+
], { ...routing, concurrencyScopes: { explicit: { sequenceNumber: 2n } } });
|
|
169
|
+
const scopes = c.appendManyForEventSources.mock.calls[0][0].ConcurrencyScopes;
|
|
170
|
+
scopes.map(entry => [entry.EventSourceId, entry.Scope.SequenceNumber]).should.deep.equal([['explicit', 2n], ['derived', 7n]]);
|
|
171
|
+
c.tailSequenceNumber.mock.calls.should.have.length(1);
|
|
172
|
+
c.tailSequenceNumber.mock.calls[0][0].EventSourceId.should.equal('derived');
|
|
173
|
+
});
|
|
174
|
+
});
|
package/eventSequences/index.ts
CHANGED
|
@@ -16,6 +16,9 @@ export { CompleteStreamError } from './CompleteStreamError.js';
|
|
|
16
16
|
export { NamedTagsWithRegisteredEventSourceNotSupported } from './NamedTagsWithRegisteredEventSourceNotSupported.js';
|
|
17
17
|
export type { CompleteStreamResult } from './CompleteStreamResult.js';
|
|
18
18
|
export type { ConcurrencyScope } from './ConcurrencyScope.js';
|
|
19
|
+
export { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
|
|
20
|
+
export type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
|
|
21
|
+
export type { ConcurrencyScopeStrategyContext } from './ConcurrencyScopeStrategyContext.js';
|
|
19
22
|
export type { EventForEventSourceId } from './EventForEventSourceId.js';
|
|
20
23
|
export type { WaitForCompletionResult } from './WaitForCompletionResult.js';
|
|
21
24
|
export type { WaitForCompletionOptions } from './WaitForCompletionOptions.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
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 { ResolvedEventRouting } from '../eventSources/ResolvedEventRouting.js';
|
|
5
|
+
import { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
|
|
6
|
+
import type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
|
|
7
|
+
import type { EventForEventSourceId } from './EventForEventSourceId.js';
|
|
8
|
+
import type { PreparedBatchAppend } from './PreparedBatchAppend.js';
|
|
9
|
+
import { planDerivedGuards, type RequiredGuard } from './resolveEventSourceRouting.js';
|
|
10
|
+
|
|
11
|
+
/** Plans one scope per event source id, retaining optimistic guard validation and tail-read order. */
|
|
12
|
+
export function planConcurrencyScopeStrategies(
|
|
13
|
+
strategy: ConcurrencyScopeStrategy,
|
|
14
|
+
prepared: PreparedBatchAppend,
|
|
15
|
+
routings: Array<ResolvedEventRouting | undefined>
|
|
16
|
+
) {
|
|
17
|
+
const { eventsForEventSourceIds, appendOptions, concurrencyScopes } = prepared;
|
|
18
|
+
const explicitIds = new Set([...concurrencyScopes].filter(([, scope]) => scope !== undefined).map(([id]) => id));
|
|
19
|
+
const guards = strategy === ConcurrencyScopeStrategies.optimistic
|
|
20
|
+
? planDerivedGuards(routings, eventsForEventSourceIds, appendOptions?.streamId, explicitIds)
|
|
21
|
+
: new Map<string, RequiredGuard>();
|
|
22
|
+
const groups = new Map<string, EventForEventSourceId[]>();
|
|
23
|
+
for (const entry of eventsForEventSourceIds) {
|
|
24
|
+
const group = groups.get(entry.eventSourceId) ?? [];
|
|
25
|
+
group.push(entry);
|
|
26
|
+
groups.set(entry.eventSourceId, group);
|
|
27
|
+
}
|
|
28
|
+
const ids = strategy === ConcurrencyScopeStrategies.optimistic ? [...guards.keys()] : [...groups.keys()];
|
|
29
|
+
return ids.map(eventSourceId => ({ eventSourceId, events: groups.get(eventSourceId)!, guard: guards.get(eventSourceId) }));
|
|
30
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
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 { ConcurrencyScope } from './ConcurrencyScope.js';
|
|
5
|
+
import { ConcurrencyScopeStrategies } from './ConcurrencyScopeStrategies.js';
|
|
6
|
+
import type { ConcurrencyScopeStrategy } from './ConcurrencyScopeStrategy.js';
|
|
7
|
+
import type { ConcurrencyScopeStrategyContext } from './ConcurrencyScopeStrategyContext.js';
|
|
8
|
+
import { deriveConcurrencyScope, type RequiredGuard } from './resolveEventSourceRouting.js';
|
|
9
|
+
|
|
10
|
+
/** Resolves a single or batch append's scope, always preserving an explicit caller scope. */
|
|
11
|
+
export async function resolveConcurrencyScope(
|
|
12
|
+
strategy: ConcurrencyScopeStrategy,
|
|
13
|
+
explicitScope: ConcurrencyScope | undefined,
|
|
14
|
+
context: ConcurrencyScopeStrategyContext,
|
|
15
|
+
guard?: RequiredGuard
|
|
16
|
+
): Promise<ConcurrencyScope | undefined> {
|
|
17
|
+
if (explicitScope !== undefined) return explicitScope;
|
|
18
|
+
if (typeof strategy === 'function') return await strategy(context);
|
|
19
|
+
if (strategy === ConcurrencyScopeStrategies.optimistic && guard) {
|
|
20
|
+
return await deriveConcurrencyScope(guard.routing, context.eventSourceId, guard.streamId, context.readTail);
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/package.json
CHANGED
|
@@ -61,7 +61,7 @@ const fixtures = readdirSync(directory).filter(name => name.endsWith('.json') &&
|
|
|
61
61
|
'constraints-event-type-siblings.json', 'constraints-composite.json',
|
|
62
62
|
'constraints-ignore-casing.json', 'constraints-scopes.json', 'constraints-field-types.json', 'constraints-event-sequences.json',
|
|
63
63
|
'constraints-field-combinations.json', 'constraints-removal-combinations.json', 'constraints-overlapping-definitions.json',
|
|
64
|
-
'constraints-fractional-field-types.json', 'constraints-fractional-collisions.json', 'constraints-field-key-measurements.json', 'constraints-ignore-casing-measurements.json'].includes(name)).map(name => ({
|
|
64
|
+
'constraints-fractional-field-types.json', 'constraints-fractional-collisions.json', 'constraints-field-key-measurements.json', 'constraints-ignore-casing-measurements.json', 'constraints-case-sensitive-unicode.json'].includes(name)).map(name => ({
|
|
65
65
|
name, fixture: JSON.parse(readFileSync(new URL(name, directory), 'utf8')) as Fixture
|
|
66
66
|
}));
|
|
67
67
|
const artifacts = { eventTypes: [OracleEventRecorded, AlternateRecorded, BoundaryRecorded], constraints: [] };
|
|
@@ -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
|
-
['unmeasured emoji', '\u{1f601}'], ['lone high surrogate', '\ud83d'], ['reversed surrogate pair', '\ude00\ud83d'], ['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();
|
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
|
|
4
4
|
import { UnsupportedEventSequenceOperation } from './UnsupportedEventSequenceOperation.js';
|
|
5
5
|
|
|
6
|
-
// constraints-field-key-measurements.json: exact
|
|
6
|
+
// constraints-field-key-measurements.json and constraints-case-sensitive-unicode.json: exact measured scalars,
|
|
7
|
+
// not general Unicode/control ranges; the latter adds only U+039B, U+03BB, U+0416, U+0436 and U+4E2D.
|
|
7
8
|
// The unicode flag matches whole scalars, so lone or unmeasured surrogate combinations never match.
|
|
8
|
-
const measuredText = /^[\x00\x01\x08-\x0a\x0c\x0d\x20-\x7e\u00c9\u00df\u00e9\u00f8\u0301\u4eac\u6771\u{10000}\u{10400}\u{1d11e}\u{1f600}\u{1f642}\u{20000}\u{10ffff}]*$/u;
|
|
9
|
+
const measuredText = /^[\x00\x01\x08-\x0a\x0c\x0d\x20-\x7e\u00c9\u00df\u00e9\u00f8\u0301\u039b\u03bb\u0416\u0436\u4e2d\u4eac\u6771\u{10000}\u{10400}\u{1d11e}\u{1f600}\u{1f642}\u{20000}\u{10ffff}]*$/u;
|
|
9
10
|
const numericValues: Readonly<Record<string, readonly number[]>> = {
|
|
10
11
|
decimal: [0.1, -1.2345, 1.2345678901234567, 0.000001],
|
|
11
12
|
float: [0.1, -1.2345, 1.2345679]
|
|
@@ -0,0 +1,188 @@
|
|
|
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 { readFileSync } from 'node:fs';
|
|
5
|
+
import type { Constructor } from '@cratis/fundamentals';
|
|
6
|
+
import { chai, describe, it, vi, type Assertion } from 'vitest';
|
|
7
|
+
import type { AppendResult } from '../../../eventSequences/AppendResult.js';
|
|
8
|
+
import { constraint } from '../../../events/constraints/constraint.js';
|
|
9
|
+
import { ConstraintBuilder } from '../../../events/constraints/ConstraintBuilder.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 { claimOf } from '../../ConstraintKey.js';
|
|
14
|
+
|
|
15
|
+
chai.should();
|
|
16
|
+
const should = (value: unknown): Assertion => (value as { should: Assertion }).should;
|
|
17
|
+
type TextEvent = { key: string };
|
|
18
|
+
type PairEvent = TextEvent & { other: string };
|
|
19
|
+
type Types = { text: Constructor<TextEvent>; pair: Constructor<PairEvent>; sibling: Constructor<TextEvent> };
|
|
20
|
+
type Shape = 'plain' | 'scoped' | 'ignoreCasing' | 'composite' | 'removable' | 'overlapping' | 'shared' | 'multiple';
|
|
21
|
+
type Operation = { mode: string; events: Array<{ source: string; content: string }> };
|
|
22
|
+
type History = { source: string; sequence: string; content: Record<string, unknown>; hash: string | undefined };
|
|
23
|
+
type WireViolation = { ConstraintName: string; Message: string; Details: Record<string, string> };
|
|
24
|
+
type Outcome = { success: boolean; sequences: string[]; wireViolations: WireViolation[]; history: History[]; next: string };
|
|
25
|
+
type Observation = { input: string; utf8Sha256: string; scalars: number[] };
|
|
26
|
+
const fixture = JSON.parse(readFileSync(new URL('../../fixtures/constraints-case-sensitive-unicode.json', import.meta.url), 'utf8')) as {
|
|
27
|
+
fieldConstraintCases: Array<{ name: string; localSteps: number; operations: Operation[] }>;
|
|
28
|
+
expected: Array<{ steps: Outcome[]; textObservations: Observation[] }>;
|
|
29
|
+
};
|
|
30
|
+
const candidates = ['Λ', 'λ', 'Ж', 'ж', '中'];
|
|
31
|
+
// Exact neighbours, never ranges. Ω also remains outside the measured payload allowlist.
|
|
32
|
+
const unmeasured = ['Κ', 'μ', 'З', 'з', '丮', 'Ω', '\u{1f601}', '\u{10001}', '\u0002', '\ud83d', '\ude00', '\ude00\ud83d'];
|
|
33
|
+
|
|
34
|
+
function define(builder: IConstraintBuilder, types: Types, shape: Shape, secondary = false): void {
|
|
35
|
+
if (shape === 'scoped') builder.perEventSourceType();
|
|
36
|
+
builder.unique(key => {
|
|
37
|
+
if (shape === 'composite') key.on(types.pair, event => event.key, event => event.other);
|
|
38
|
+
else if (shape === 'overlapping' && secondary) key.on(types.pair, event => event.other);
|
|
39
|
+
else if (shape === 'overlapping') key.on(types.pair, event => event.key);
|
|
40
|
+
else key.on(types.text, event => event.key);
|
|
41
|
+
if (shape === 'shared') key.on(types.sibling, event => event.key);
|
|
42
|
+
if (shape === 'ignoreCasing') key.ignoreCasing();
|
|
43
|
+
if (shape === 'removable') key.removedWith(types.sibling);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function definition(types: Types, shape: Shape, name = 'OracleFieldKey'): Constructor {
|
|
48
|
+
class Definition { define(builder: IConstraintBuilder) { define(builder, types, shape, name === 'OtherKey'); } }
|
|
49
|
+
constraint(name)(Definition);
|
|
50
|
+
return Definition;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function scenarioFor(types: Types, shape: Shape = 'plain'): EventScenario {
|
|
54
|
+
const constraints = [definition(types, shape)];
|
|
55
|
+
if (shape === 'overlapping') constraints.push(definition(types, shape, 'OtherKey'));
|
|
56
|
+
if (shape === 'multiple') constraints.push(definition({ ...types, text: types.sibling }, 'plain', 'OtherKey'));
|
|
57
|
+
return new EventScenario({ artifacts: { eventTypes: Object.values(types), constraints } });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function eventFor(types: Types, key: string, shape: Shape = 'plain'): TextEvent {
|
|
61
|
+
if (shape === 'composite') return Object.assign(new types.pair(), { key, other: 'x' });
|
|
62
|
+
if (shape === 'overlapping') return Object.assign(new types.pair(), { key, other: key });
|
|
63
|
+
return Object.assign(new types.text(), { key });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function historyOf(scenario: EventScenario): History[] {
|
|
67
|
+
return scenario.appendedEvents.map(event => ({ source: event.context.eventSourceId,
|
|
68
|
+
sequence: event.context.sequenceNumber.toString(), content: event.content, hash: event.context.hash }));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function append(scenario: EventScenario, types: Types, operation: Operation): Promise<AppendResult[]> {
|
|
72
|
+
const events = operation.events.map(entry => ({ eventSourceId: entry.source, event: Object.assign(new types.text(), JSON.parse(entry.content)) }));
|
|
73
|
+
return operation.mode === 'single' ? [await scenario.append(events[0].eventSourceId, events[0].event)] : scenario.appendMany(events);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function replay(types: Types, index: number): void {
|
|
77
|
+
const test = fixture.fieldConstraintCases[index];
|
|
78
|
+
it(`should replay every ${test.name} operation with content, hashes, raw and public violations and rollback`, async () => {
|
|
79
|
+
const validate = vi.spyOn(InProcessConstraints.prototype, 'validate');
|
|
80
|
+
try {
|
|
81
|
+
const scenario = scenarioFor(types);
|
|
82
|
+
should(test.localSteps).equal(test.operations.length);
|
|
83
|
+
should(fixture.expected[index].steps).have.lengthOf(test.operations.length);
|
|
84
|
+
for (const [step, operation] of test.operations.entries()) {
|
|
85
|
+
const results = await append(scenario, types, operation);
|
|
86
|
+
const expected = fixture.expected[index].steps[step];
|
|
87
|
+
should(results.every(result => result.isSuccess === expected.success)).equal(true);
|
|
88
|
+
should(results.map(result => result.sequenceNumber.value.toString())).deep.equal(
|
|
89
|
+
expected.success ? expected.sequences : results.map(() => '0'));
|
|
90
|
+
const raw = validate.mock.results.at(-1)!.value as ReturnType<InProcessConstraints['validate']>;
|
|
91
|
+
should(raw.map(violation => ({ ...violation, SequenceNumber: violation.SequenceNumber.toString() }))).deep.equal(expected.wireViolations);
|
|
92
|
+
for (const result of results) {
|
|
93
|
+
should(result.constraintViolations.map(item => ({ id: item.constraintId, message: item.message, details: item.details })))
|
|
94
|
+
.deep.equal(expected.wireViolations.map(item => ({ id: item.ConstraintName, message: item.Message, details: item.Details })));
|
|
95
|
+
}
|
|
96
|
+
should(historyOf(scenario)).deep.equal(expected.history);
|
|
97
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value.toString()).equal(expected.next);
|
|
98
|
+
}
|
|
99
|
+
} finally { validate.mockRestore(); }
|
|
100
|
+
});
|
|
101
|
+
it(`should preserve each ${test.name} input's exact scalar sequence and kernel UTF-8 key hash`, async () => {
|
|
102
|
+
const observations = fixture.expected[index].textObservations;
|
|
103
|
+
should(observations.length).greaterThan(0);
|
|
104
|
+
const builder = new ConstraintBuilder('OracleFieldKey');
|
|
105
|
+
define(builder, types, 'plain');
|
|
106
|
+
for (const observation of observations) {
|
|
107
|
+
const scenario = scenarioFor(types);
|
|
108
|
+
await scenario.append('A', eventFor(types, observation.input));
|
|
109
|
+
const event = scenario.appendedEvents[0];
|
|
110
|
+
should(Array.from(event.content.key as string, scalar => scalar.codePointAt(0)!)).deep.equal(observation.scalars);
|
|
111
|
+
should(claimOf('OracleFieldKey', builder.capture, event, {
|
|
112
|
+
isolated: true, schema: { type: 'object', properties: { key: { type: 'string' } } }
|
|
113
|
+
})!.key).equal(observation.utf8Sha256);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function rejected(pending: Promise<unknown>): Promise<void> {
|
|
119
|
+
const error: unknown = await pending.then(() => undefined, error => error);
|
|
120
|
+
should(error).instanceOf(UnsupportedEventSequenceOperation);
|
|
121
|
+
should(String(error)).match(/append(?:Many)?\.content|artifacts\.constraints/);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function rejectText(types: Types, value: string, shape: Shape = 'plain'): void {
|
|
125
|
+
const good = (key: string): TextEvent => eventFor(types, key, shape);
|
|
126
|
+
for (const mode of ['single', 'batch']) {
|
|
127
|
+
it(`should reject ${JSON.stringify(value)} atomically in a ${shape} ${mode} append without leaking claims`, async () => {
|
|
128
|
+
const scenario = scenarioFor(types, shape);
|
|
129
|
+
await scenario.append('A', good('safe'));
|
|
130
|
+
const history = historyOf(scenario);
|
|
131
|
+
const results = [...scenario.results];
|
|
132
|
+
await rejected(mode === 'single' ? scenario.append('C', good(value))
|
|
133
|
+
: scenario.appendMany([{ eventSourceId: 'B', event: good('fresh') }, { eventSourceId: 'C', event: good(value) }]));
|
|
134
|
+
should(historyOf(scenario)).deep.equal(history);
|
|
135
|
+
should(scenario.results).deep.equal(results);
|
|
136
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(1n);
|
|
137
|
+
should((await scenario.append('B', good('fresh'))).isSuccess).equal(true);
|
|
138
|
+
should((await scenario.append('C', good('safe'))).constraintViolations.length).greaterThan(0);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
it(`should reject ${JSON.stringify(value)} atomically in ${shape} given setup and leave its valid key claimable`, async () => {
|
|
142
|
+
const scenario = scenarioFor(types, shape);
|
|
143
|
+
await rejected(scenario.given.forEventSource('A').events(good('safe'), good(value)));
|
|
144
|
+
should(scenario.appendedEvents).have.lengthOf(0);
|
|
145
|
+
should(scenario.results).have.lengthOf(0);
|
|
146
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(0n);
|
|
147
|
+
should((await scenario.append('B', good('safe'))).isSuccess).equal(true);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function payloads(types: Types): void {
|
|
152
|
+
for (const [index, value] of candidates.entries()) {
|
|
153
|
+
it(`should round-trip unconstrained ${value} payload content and its oracle-measured hash`, async () => {
|
|
154
|
+
const scenario = new EventScenario({ artifacts: { eventTypes: [types.text] }, constraints: 'disabled' });
|
|
155
|
+
await scenario.append('A', eventFor(types, value));
|
|
156
|
+
should(historyOf(scenario)).deep.equal(fixture.expected[index].steps[0].history);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
for (const value of unmeasured) {
|
|
160
|
+
it(`should still reject unconstrained unmeasured ${JSON.stringify(value)} payloads`, async () => {
|
|
161
|
+
const scenario = new EventScenario({ artifacts: { eventTypes: [types.text] }, constraints: 'disabled' });
|
|
162
|
+
await rejected(scenario.append('A', eventFor(types, value)));
|
|
163
|
+
should(scenario.appendedEvents).have.lengthOf(0);
|
|
164
|
+
should(scenario.results).have.lengthOf(0);
|
|
165
|
+
should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(0n);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function caseSensitiveUnicode(types: Types): void {
|
|
171
|
+
describe('when replaying case-sensitive Unicode measurements', () => {
|
|
172
|
+
should(fixture.fieldConstraintCases.length).greaterThan(0);
|
|
173
|
+
should(fixture.expected).have.lengthOf(fixture.fieldConstraintCases.length);
|
|
174
|
+
for (const index of fixture.fieldConstraintCases.keys()) replay(types, index);
|
|
175
|
+
});
|
|
176
|
+
describe('when keys contain unmeasured scalars or malformed surrogates', () => {
|
|
177
|
+
for (const value of unmeasured) {
|
|
178
|
+
rejectText(types, value);
|
|
179
|
+
rejectText(types, `Aλ${value}中z`);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
describe('when measured scalars are used outside the isolated case-sensitive single-property shape', () => {
|
|
183
|
+
for (const shape of ['ignoreCasing', 'scoped', 'composite', 'removable', 'overlapping', 'shared', 'multiple'] as const) {
|
|
184
|
+
for (const value of candidates) rejectText(types, value, shape);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
describe('when plain-string payloads use the shared measured alphabet', () => payloads(types));
|
|
188
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
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 { caseSensitiveUnicode } from './case_sensitive_unicode.fixture.js';
|
|
8
|
+
|
|
9
|
+
class TextClaimed { @field(String) key = ''; }
|
|
10
|
+
eventType('OracleFieldText')(TextClaimed);
|
|
11
|
+
class PairClaimed { @field(String) key = ''; @field(String) other = ''; }
|
|
12
|
+
eventType('OracleUnicodePair')(PairClaimed);
|
|
13
|
+
class SiblingClaimed { @field(String) key = ''; }
|
|
14
|
+
eventType('OracleUnicodeSibling')(SiblingClaimed);
|
|
15
|
+
|
|
16
|
+
caseSensitiveUnicode({ text: TextClaimed, pair: PairClaimed, sibling: SiblingClaimed });
|
|
@@ -0,0 +1,15 @@
|
|
|
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 { caseSensitiveUnicode } from './case_sensitive_unicode.fixture.js';
|
|
7
|
+
|
|
8
|
+
@eventType('OracleFieldText')
|
|
9
|
+
class TextClaimed { @field(String) key = ''; }
|
|
10
|
+
@eventType('OracleUnicodePair')
|
|
11
|
+
class PairClaimed { @field(String) key = ''; @field(String) other = ''; }
|
|
12
|
+
@eventType('OracleUnicodeSibling')
|
|
13
|
+
class SiblingClaimed { @field(String) key = ''; }
|
|
14
|
+
|
|
15
|
+
caseSensitiveUnicode({ text: TextClaimed, pair: PairClaimed, sibling: SiblingClaimed });
|
package/testing/for_EventScenario/when_appending_field_types/field_key_measurements.fixture.ts
CHANGED
|
@@ -104,7 +104,7 @@ export function fieldKeyMeasurements(types: Types): void {
|
|
|
104
104
|
|
|
105
105
|
function rejectUnmeasured(types: Types): void {
|
|
106
106
|
for (const [type, values] of [
|
|
107
|
-
[types.text, ['\u{1f601}', '\u{10001}', '\ud83d', '\ude00', '\ude00\ud83d', '\ud83dx', '
|
|
107
|
+
[types.text, ['\u{1f601}', '\u{10001}', '\ud83d', '\ude00', '\ude00\ud83d', '\ud83dx', 'μ', '\u0002']],
|
|
108
108
|
[types.decimal, [1e-7, 1e21, 1.5]],
|
|
109
109
|
[types.float, [1.23456789, 1e-7, 1e21, 0.000001, 1.5]]
|
|
110
110
|
] as const) {
|