@cratis/chronicle 6.31.0 → 6.31.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.
Files changed (24) hide show
  1. package/connection/ChronicleConnection.ts +1 -0
  2. package/connection/encodeExplicitFalse.ts +56 -0
  3. package/connection/for_encodeExplicitFalse/when_encoding_reactor_definition.spec.ts +34 -0
  4. package/connection/for_encodeExplicitFalse/when_encoding_webhook_definition.spec.ts +39 -0
  5. package/connection/for_encodeExplicitFalse/wireFields.ts +24 -0
  6. package/dist/connection/ChronicleConnection.d.ts +1 -0
  7. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  8. package/dist/connection/ChronicleConnection.js +1 -0
  9. package/dist/connection/ChronicleConnection.js.map +1 -1
  10. package/dist/connection/encodeExplicitFalse.d.ts +6 -0
  11. package/dist/connection/encodeExplicitFalse.d.ts.map +1 -0
  12. package/dist/connection/encodeExplicitFalse.js +45 -0
  13. package/dist/connection/encodeExplicitFalse.js.map +1 -0
  14. package/dist/connection/for_encodeExplicitFalse/wireFields.d.ts +6 -0
  15. package/dist/connection/for_encodeExplicitFalse/wireFields.d.ts.map +1 -0
  16. package/dist/connection/for_encodeExplicitFalse/wireFields.js +24 -0
  17. package/dist/connection/for_encodeExplicitFalse/wireFields.js.map +1 -0
  18. package/dist/tsconfig.tsbuildinfo +1 -1
  19. package/events/constraints/for_Constraints/against_a_kernel/when_appending_unique_values_concurrently.integration.spec.ts +189 -0
  20. package/events/migrations/for_EventTypeMigrators/against_a_kernel/when_replaying_an_older_generation.integration.spec.ts +156 -0
  21. package/jobs/for_Jobs/against_a_kernel/when_managing_a_replay_job.integration.spec.ts +114 -0
  22. package/package.json +1 -1
  23. package/reactors/for_Reactors/against_a_kernel/when_replaying_once_only_reactors.integration.spec.ts +111 -0
  24. package/webhooks/for_Webhooks/against_a_kernel/when_registering_and_removing_a_webhook.integration.spec.ts +88 -0
@@ -0,0 +1,189 @@
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 { randomUUID } from 'node:crypto';
5
+ import { afterAll, beforeAll, chai, describe, it } from 'vitest';
6
+ import { field } from '@cratis/fundamentals';
7
+ import { ChronicleClient } from '../../../../ChronicleClient.js';
8
+ import { ChronicleOptions } from '../../../../ChronicleOptions.js';
9
+ import type { IClientArtifactsProvider } from '../../../../artifacts/index.js';
10
+ import type { AppendResult } from '../../../../eventSequences/index.js';
11
+ import type { IEventStore } from '../../../../IEventStore.js';
12
+ import { eventType } from '../../../eventTypeDecorator.js';
13
+ import { constraint } from '../../constraint.js';
14
+ import type { IConstraint } from '../../IConstraint.js';
15
+ import type { IConstraintBuilder } from '../../IConstraintBuilder.js';
16
+ import { unique } from '../../unique.js';
17
+
18
+ chai.should();
19
+
20
+ // Runs against a real Chronicle kernel; skipped locally unless the connection string is set (see vitest.integration.config.ts).
21
+ // In CI it never skips, so a missing connection string or unreachable kernel fails instead of passing vacuously.
22
+ const connectionString = process.env.CHRONICLE_INTEGRATION_CONNECTION_STRING;
23
+
24
+ const constraintName = 'UniqueUserName';
25
+ const constraintMessage = 'The user name is already taken';
26
+
27
+ @eventType()
28
+ class UserRegistered {
29
+ @field(String) userName = '';
30
+ }
31
+
32
+ @eventType()
33
+ class UserRemoved {
34
+ @field(String) userName = '';
35
+ }
36
+
37
+ @eventType()
38
+ @unique('OneAccountPerUser', 'The user already has an account')
39
+ class AccountOpened {
40
+ @field(String) accountName = '';
41
+ }
42
+
43
+ @constraint(constraintName)
44
+ class UniqueUserName implements IConstraint {
45
+ define(builder: IConstraintBuilder): void {
46
+ builder.unique(_ => _
47
+ .on(UserRegistered, e => e.userName)
48
+ .removedWith(UserRemoved)
49
+ .withMessage(constraintMessage));
50
+ }
51
+ }
52
+
53
+ const artifacts: IClientArtifactsProvider = {
54
+ eventTypes: [UserRegistered, UserRemoved, AccountOpened],
55
+ readModels: [],
56
+ reactors: [],
57
+ reducers: [],
58
+ seeders: [],
59
+ constraints: [UniqueUserName],
60
+ projections: [],
61
+ webhooks: [],
62
+ eventTypeMigrations: [],
63
+ globalForHandlers: []
64
+ };
65
+
66
+ const registered = (userName: string) => Object.assign(new UserRegistered(), { userName });
67
+ const opened = (accountName: string) => Object.assign(new AccountOpened(), { accountName });
68
+ const createClient = () => new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
69
+ discoveryPatterns: [],
70
+ clientArtifactsProvider: artifacts
71
+ }));
72
+
73
+ function shouldHaveExactlyOneWinner(results: AppendResult[], name: string, message: string) {
74
+ results.filter(_ => _.isSuccess).length.should.equal(1);
75
+ const losers = results.filter(_ => !_.isSuccess);
76
+ losers.length.should.equal(results.length - 1);
77
+ for (const loser of losers) {
78
+ loser.constraintViolations.length.should.equal(1);
79
+ loser.constraintViolations[0].constraintId.should.equal(name);
80
+ loser.constraintViolations[0].message.should.equal(message);
81
+ }
82
+ }
83
+
84
+ describe.skipIf(!connectionString && !process.env.CI)('when appending unique values concurrently against a kernel', () => {
85
+ const storeName = `Unique${randomUUID().replaceAll('-', '').slice(0, 12)}`;
86
+ let first: ChronicleClient;
87
+ let second: ChronicleClient;
88
+ let store: IEventStore;
89
+ let otherClientStore: IEventStore;
90
+
91
+ beforeAll(async () => {
92
+ first = createClient();
93
+ second = createClient();
94
+ store = await first.getEventStore(storeName);
95
+ otherClientStore = await second.getEventStore(storeName);
96
+ });
97
+
98
+ afterAll(() => {
99
+ first?.dispose();
100
+ second?.dispose();
101
+ });
102
+
103
+ it('lets exactly one of two clients claim the same value on different event sources', async () => {
104
+ const results = await Promise.all([
105
+ store.eventLog.append(randomUUID(), registered('alice')),
106
+ otherClientStore.eventLog.append(randomUUID(), registered('alice'))
107
+ ]);
108
+ shouldHaveExactlyOneWinner(results, constraintName, constraintMessage);
109
+ });
110
+
111
+ it('lets exactly one of many parallel appends claim the same value', async () => {
112
+ const results = await Promise.all(Array.from({ length: 10 }, () => store.eventLog.append(randomUUID(), registered('bob'))));
113
+ shouldHaveExactlyOneWinner(results, constraintName, constraintMessage);
114
+ });
115
+
116
+ it('lets exactly one of two parallel appends open an account on the same event source', async () => {
117
+ const eventSourceId = randomUUID();
118
+ const results = await Promise.all([
119
+ store.eventLog.append(eventSourceId, opened('checking')),
120
+ otherClientStore.eventLog.append(eventSourceId, opened('savings'))
121
+ ]);
122
+ shouldHaveExactlyOneWinner(results, 'OneAccountPerUser', 'The user already has an account');
123
+ });
124
+
125
+ it('lets parallel appends open accounts on separate event sources', async () => {
126
+ const results = await Promise.all([
127
+ store.eventLog.append(randomUUID(), opened('checking')),
128
+ otherClientStore.eventLog.append(randomUUID(), opened('checking'))
129
+ ]);
130
+ results.every(_ => _.isSuccess).should.be.true;
131
+ });
132
+
133
+ it('lets the same value be claimed once in each namespace', async () => {
134
+ const [tenantA, tenantB] = await Promise.all([
135
+ first.getEventStore(storeName, `a${randomUUID().slice(0, 8)}`),
136
+ second.getEventStore(storeName, `b${randomUUID().slice(0, 8)}`)
137
+ ]);
138
+ const results = await Promise.all([
139
+ tenantA.eventLog.append(randomUUID(), registered('carol')),
140
+ tenantB.eventLog.append(randomUUID(), registered('carol'))
141
+ ]);
142
+ results.every(_ => _.isSuccess).should.be.true;
143
+ });
144
+
145
+ it('lets a released value be claimed again', async () => {
146
+ const owner = randomUUID();
147
+ (await store.eventLog.append(owner, registered('dave'))).isSuccess.should.be.true;
148
+ (await otherClientStore.eventLog.append(randomUUID(), registered('dave'))).isSuccess.should.be.false;
149
+
150
+ (await store.eventLog.append(owner, Object.assign(new UserRemoved(), { userName: 'dave' }))).isSuccess.should.be.true;
151
+
152
+ const results = await Promise.all([
153
+ store.eventLog.append(randomUUID(), registered('dave')),
154
+ otherClientStore.eventLog.append(randomUUID(), registered('dave'))
155
+ ]);
156
+ shouldHaveExactlyOneWinner(results, constraintName, constraintMessage);
157
+ });
158
+
159
+ it('commits no part of a batch that loses a race', async () => {
160
+ const batchSource = randomUUID();
161
+ const singleSource = randomUUID();
162
+ const [batch, single] = await Promise.all([
163
+ store.eventLog.appendMany([
164
+ { eventSourceId: batchSource, event: registered(`erin-${batchSource}`) },
165
+ { eventSourceId: batchSource, event: registered('erin') }
166
+ ]),
167
+ otherClientStore.eventLog.append(singleSource, registered('erin'))
168
+ ]);
169
+
170
+ const batchSucceeded = batch.every(_ => _.isSuccess);
171
+ batchSucceeded.should.not.equal(single.isSuccess);
172
+
173
+ const committed = await store.eventLog.getForEventSourceIdAndEventTypes(batchSource, [UserRegistered]);
174
+ committed.length.should.equal(batchSucceeded ? 2 : 0);
175
+ });
176
+
177
+ it('rejects a batch where two event sources claim the same value without committing any of it', async () => {
178
+ const firstSource = randomUUID();
179
+ const secondSource = randomUUID();
180
+ const results = await store.eventLog.appendMany([
181
+ { eventSourceId: firstSource, event: registered('frank') },
182
+ { eventSourceId: secondSource, event: registered('frank') }
183
+ ]);
184
+ results.some(_ => !_.isSuccess).should.be.true;
185
+ (await store.eventLog.getForEventSourceIdAndEventTypes(firstSource, [UserRegistered])).length.should.equal(0);
186
+ (await store.eventLog.getForEventSourceIdAndEventTypes(secondSource, [UserRegistered])).length.should.equal(0);
187
+ (await store.eventLog.append(randomUUID(), registered('frank'))).isSuccess.should.be.true;
188
+ });
189
+ });
@@ -0,0 +1,156 @@
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 { randomUUID } from 'node:crypto';
5
+ import { afterAll, beforeAll, chai, describe, it } from 'vitest';
6
+ import { field } from '@cratis/fundamentals';
7
+ import { ChronicleClient } from '../../../../ChronicleClient.js';
8
+ import { ChronicleOptions } from '../../../../ChronicleOptions.js';
9
+ import type { IClientArtifactsProvider } from '../../../../artifacts/index.js';
10
+ import type { AppendedEvent, EventContext } from '../../../../events/index.js';
11
+ import { eventType } from '../../../../events/index.js';
12
+ import type { IEventStore } from '../../../../IEventStore.js';
13
+ import { fromEvent } from '../../../../projections/index.js';
14
+ import { reactor } from '../../../../reactors/index.js';
15
+ import { eventTypeMigration } from '../../eventTypeMigration.js';
16
+ import type { IEventMigrationBuilder } from '../../IEventMigrationBuilder.js';
17
+ import type { IEventTypeMigration } from '../../IEventTypeMigration.js';
18
+
19
+ chai.should();
20
+
21
+ // Runs against a real Chronicle kernel; skipped locally unless the connection string is set (see vitest.integration.config.ts).
22
+ // In CI it never skips, so a missing connection string or unreachable kernel fails instead of passing vacuously.
23
+ const connectionString = process.env.CHRONICLE_INTEGRATION_CONNECTION_STRING;
24
+
25
+ const eventTypeId = 'migration-replay-author-registered';
26
+
27
+ @eventType(eventTypeId, 1)
28
+ class AuthorRegisteredV1 {
29
+ @field(String) name = '';
30
+ }
31
+
32
+ @eventType(eventTypeId, 2)
33
+ class AuthorRegistered {
34
+ @field(String) firstName = '';
35
+ @field(String) lastName = '';
36
+ }
37
+
38
+ @eventTypeMigration(AuthorRegistered, AuthorRegisteredV1)
39
+ class AuthorRegisteredMigration implements IEventTypeMigration<AuthorRegistered, AuthorRegisteredV1> {
40
+ upcast(builder: IEventMigrationBuilder<AuthorRegistered, AuthorRegisteredV1>): void {
41
+ builder.properties(_ => _
42
+ .split('firstName', 'name', ' ', 0)
43
+ .split('lastName', 'name', ' ', 1));
44
+ }
45
+
46
+ downcast(builder: IEventMigrationBuilder<AuthorRegisteredV1, AuthorRegistered>): void {
47
+ builder.properties(_ => _.combine('name', ' ', 'firstName', 'lastName'));
48
+ }
49
+ }
50
+
51
+ // Projected by the kernel from the second generation.
52
+ @fromEvent(AuthorRegistered)
53
+ class Author {
54
+ @field(String) firstName = '';
55
+ @field(String) lastName = '';
56
+ }
57
+
58
+ const observed: { event: AuthorRegistered; context: EventContext }[] = [];
59
+
60
+ @reactor('migration-replay-author-observer')
61
+ class AuthorObserver {
62
+ authorRegistered(event: AuthorRegistered, context: EventContext): void {
63
+ observed.push({ event, context });
64
+ }
65
+ }
66
+
67
+ function artifactsWith(overrides: Partial<IClientArtifactsProvider>): IClientArtifactsProvider {
68
+ return {
69
+ eventTypes: [],
70
+ readModels: [],
71
+ reactors: [],
72
+ reducers: [],
73
+ seeders: [],
74
+ constraints: [],
75
+ projections: [],
76
+ webhooks: [],
77
+ eventTypeMigrations: [],
78
+ globalForHandlers: [],
79
+ ...overrides
80
+ };
81
+ }
82
+
83
+ function clientWith(artifacts: IClientArtifactsProvider): ChronicleClient {
84
+ return new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
85
+ discoveryPatterns: [],
86
+ clientArtifactsProvider: artifacts
87
+ }));
88
+ }
89
+
90
+ async function eventually<T>(read: () => Promise<T>, accept: (value: T) => boolean, timeoutMs = 30_000): Promise<T> {
91
+ const deadline = Date.now() + timeoutMs;
92
+ let value = await read();
93
+ while (!accept(value)) {
94
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for the kernel; last value: ${JSON.stringify(value, (_, v) => typeof v === 'bigint' ? v.toString() : v)}`);
95
+ await new Promise(resolve => setTimeout(resolve, 250));
96
+ value = await read();
97
+ }
98
+ return value;
99
+ }
100
+
101
+ describe.skipIf(!connectionString && !process.env.CI)('when replaying an older generation against a kernel', () => {
102
+ const eventStoreName = `MigrationReplay${randomUUID().replaceAll('-', '')}`;
103
+ const eventSourceId = randomUUID();
104
+ let firstGenerationClient: ChronicleClient;
105
+ let secondGenerationClient: ChronicleClient;
106
+ let appendedSequenceNumber: bigint;
107
+ let event: AppendedEvent;
108
+ let author: Author | null;
109
+ let observation: { event: AuthorRegistered; context: EventContext };
110
+ let missingMigrationError: unknown;
111
+
112
+ beforeAll(async () => {
113
+ // An application that only knows the first generation appends the event.
114
+ firstGenerationClient = clientWith(artifactsWith({ eventTypes: [AuthorRegisteredV1] }));
115
+ const firstGenerationStore = await firstGenerationClient.getEventStore(eventStoreName);
116
+ const appended = await firstGenerationStore.eventLog.append(eventSourceId, Object.assign(new AuthorRegisteredV1(), { name: 'Jane Doe' }));
117
+ appendedSequenceNumber = appended.sequenceNumber.value;
118
+ firstGenerationClient.dispose();
119
+
120
+ // A later version registers the second generation with a migration, a projection and a reactor that replay the history.
121
+ secondGenerationClient = clientWith(artifactsWith({
122
+ eventTypes: [AuthorRegisteredV1, AuthorRegistered],
123
+ eventTypeMigrations: [AuthorRegisteredMigration],
124
+ readModels: [Author],
125
+ reactors: [AuthorObserver]
126
+ }));
127
+ const store: IEventStore = await secondGenerationClient.getEventStore(eventStoreName);
128
+
129
+ event = await eventually(
130
+ async () => (await store.eventLog.getForEventSourceIdAndEventTypes(eventSourceId, [AuthorRegistered]))[0],
131
+ _ => (_?.content as AuthorRegistered | undefined)?.firstName === 'Jane');
132
+ author = await eventually(() => store.readModels.findInstanceById(Author, eventSourceId), _ => _ !== null && _.firstName !== '');
133
+ observation = await eventually(async () => observed.find(_ => _.context.eventSourceId === eventSourceId)!, _ => _ !== undefined);
134
+
135
+ // Registering a second generation without a migration from the first is rejected.
136
+ const missingMigrationClient = clientWith(artifactsWith({ eventTypes: [AuthorRegisteredV1, AuthorRegistered] }));
137
+ missingMigrationError = await missingMigrationClient.getEventStore(`MigrationReplayMissing${randomUUID().replaceAll('-', '')}`).catch((error: unknown) => error);
138
+ missingMigrationClient.dispose();
139
+ });
140
+
141
+ afterAll(() => {
142
+ firstGenerationClient?.dispose();
143
+ secondGenerationClient?.dispose();
144
+ });
145
+
146
+ it('should read the first name split from the first generation', () => (event.content as AuthorRegistered).firstName.should.equal('Jane'));
147
+ it('should read the last name split from the first generation', () => (event.content as AuthorRegistered).lastName.should.equal('Doe'));
148
+ it('should keep the event source of the appended event', () => event.context.eventSourceId.should.equal(eventSourceId));
149
+ it('should keep the sequence number of the appended event', () => event.context.sequenceNumber.should.equal(appendedSequenceNumber));
150
+ it('should project the migrated first name', () => author!.firstName.should.equal('Jane'));
151
+ it('should project the migrated last name', () => author!.lastName.should.equal('Doe'));
152
+ it('should replay the migrated first name to the reactor', () => observation.event.firstName.should.equal('Jane'));
153
+ it('should replay the migrated last name to the reactor', () => observation.event.lastName.should.equal('Doe'));
154
+ it('should replay the event source to the reactor', () => observation.context.eventSourceId.should.equal(eventSourceId));
155
+ it('should reject a second generation that has no migration', () => missingMigrationError.should.be.instanceOf(Error));
156
+ });
@@ -0,0 +1,114 @@
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 { randomUUID } from 'node:crypto';
5
+ import { afterAll, beforeAll, chai, describe, it } from 'vitest';
6
+ import { JobStatus, JobStepStatus, type JobStepSummaryResponse, type JobSummaryResponse } from '@cratis/chronicle.contracts';
7
+ import { field, Guid } from '@cratis/fundamentals';
8
+ import { ChronicleClient } from '../../../ChronicleClient.js';
9
+ import { ChronicleOptions } from '../../../ChronicleOptions.js';
10
+ import { fromContractsGuid } from '../../../connection/Guid.js';
11
+ import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
12
+ import { eventType } from '../../../events/index.js';
13
+ import type { IEventStore } from '../../../IEventStore.js';
14
+ import { fromEvent } from '../../../projections/index.js';
15
+ import { JobId } from '../../JobId.js';
16
+
17
+ chai.should();
18
+
19
+ // Runs against a real Chronicle kernel; skipped locally unless the connection string is set (see vitest.integration.config.ts).
20
+ // In CI it never skips, so a missing connection string or unreachable kernel fails instead of passing vacuously.
21
+ const connectionString = process.env.CHRONICLE_INTEGRATION_CONNECTION_STRING;
22
+
23
+ @eventType()
24
+ class ItemAdded {
25
+ @field(String) name = '';
26
+ }
27
+
28
+ @fromEvent(ItemAdded)
29
+ class Item {
30
+ @field(String) name = '';
31
+ }
32
+
33
+ const artifacts: IClientArtifactsProvider = {
34
+ eventTypes: [ItemAdded],
35
+ readModels: [Item],
36
+ reactors: [],
37
+ reducers: [],
38
+ seeders: [],
39
+ constraints: [],
40
+ projections: [],
41
+ webhooks: [],
42
+ eventTypeMigrations: [],
43
+ globalForHandlers: []
44
+ };
45
+
46
+ async function eventually<T>(read: () => Promise<T>, accept: (value: T) => boolean, timeoutMs = 20_000): Promise<T> {
47
+ const deadline = Date.now() + timeoutMs;
48
+ let value = await read();
49
+ while (!accept(value)) {
50
+ if (Date.now() > deadline) throw new Error('Timed out waiting for the kernel');
51
+ await new Promise(resolve => setTimeout(resolve, 100));
52
+ value = await read();
53
+ }
54
+ return value;
55
+ }
56
+
57
+ describe.skipIf(!connectionString && !process.env.CI)('when managing a replay job against a kernel', () => {
58
+ let client: ChronicleClient;
59
+ let store: IEventStore;
60
+ let jobId: JobId;
61
+ let listed: JobSummaryResponse[];
62
+ let stopped: JobSummaryResponse | undefined;
63
+ let steps: JobStepSummaryResponse[];
64
+ let afterDelete: JobSummaryResponse | undefined;
65
+ let stopUnknownJob: unknown;
66
+ let deleteUnknownJob: unknown;
67
+
68
+ beforeAll(async () => {
69
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
70
+ discoveryPatterns: [],
71
+ clientArtifactsProvider: artifacts
72
+ }));
73
+ store = await client.getEventStore(`JobsEndToEnd${randomUUID().replaceAll('-', '')}`);
74
+
75
+ // Enough events that the replay is still running when it is stopped; a stopped job stays until deleted,
76
+ // where a completed one is removed and could not be listed reliably.
77
+ await store.eventLog.appendMany(Array.from({ length: 500 }, (_, index) => ({
78
+ eventSourceId: randomUUID(),
79
+ event: Object.assign(new ItemAdded(), { name: `Item ${index}` })
80
+ })));
81
+
82
+ jobId = await store.projections.replayForModel(Item);
83
+
84
+ // Stopping a job in the instant it starts leaves its step running forever, so wait until it is running.
85
+ await eventually(() => store.jobs.getJob(jobId), _ => _?.Status === JobStatus.JOB_STATUS_Running);
86
+ await store.jobs.stop(jobId);
87
+
88
+ listed = await store.jobs.getJobs();
89
+ stopped = await eventually(() => store.jobs.getJob(jobId), _ => _?.Status === JobStatus.JOB_STATUS_Stopped);
90
+ // The kernel updates step status asynchronously, after the job itself reports stopped.
91
+ steps = await eventually(
92
+ () => store.jobs.getJobSteps(jobId),
93
+ _ => _.length > 0 && _.every(step => step.Status === JobStepStatus.JOB_STEP_STATUS_Stopped),
94
+ 30_000);
95
+
96
+ await store.jobs.delete(jobId);
97
+ afterDelete = await eventually(() => store.jobs.getJob(jobId), _ => _ === undefined);
98
+
99
+ stopUnknownJob = await store.jobs.stop(randomUUID()).catch((error: unknown) => error);
100
+ deleteUnknownJob = await store.jobs.delete(randomUUID()).catch((error: unknown) => error);
101
+ });
102
+
103
+ afterAll(() => client?.dispose());
104
+
105
+ it('should start a replay job', () => jobId.toString().should.not.equal(Guid.empty.toString()));
106
+ it('should list the job', () => listed.some(_ => fromContractsGuid(_.Id).toString() === jobId.toString()).should.be.true);
107
+ it('should report the job as a replay', () => stopped!.Type.should.equal('ReplayObserver'));
108
+ it('should report the job as stopped', () => stopped!.Status.should.equal(JobStatus.JOB_STATUS_Stopped));
109
+ it('should list the steps of the job', () => steps.length.should.be.greaterThan(0));
110
+ it('should report the steps as stopped', () => steps.every(_ => _.Status === JobStepStatus.JOB_STEP_STATUS_Stopped).should.be.true);
111
+ it('should no longer list the deleted job', () => (afterDelete === undefined).should.be.true);
112
+ it('should report stopping a job that does not exist', () => stopUnknownJob.should.be.instanceOf(Error));
113
+ it('should report deleting a job that does not exist', () => deleteUnknownJob.should.be.instanceOf(Error));
114
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.31.0",
3
+ "version": "6.31.1",
4
4
  "description": "Event sourcing for TypeScript and Node.js — the idiomatic client for Cratis Chronicle, the open-source event-sourcing database",
5
5
  "author": "Cratis",
6
6
  "license": "MIT",
@@ -0,0 +1,111 @@
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 { randomUUID } from 'node:crypto';
5
+ import { afterAll, beforeAll, chai, describe, it } from 'vitest';
6
+ import { field } from '@cratis/fundamentals';
7
+ import { ChronicleClient } from '../../../ChronicleClient.js';
8
+ import { ChronicleOptions } from '../../../ChronicleOptions.js';
9
+ import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
10
+ import type { ChronicleConnection } from '../../../connection/index.js';
11
+ import { eventType } from '../../../events/index.js';
12
+ import type { IEventStore } from '../../../IEventStore.js';
13
+ import { onceOnly } from '../../onceOnly.js';
14
+ import { reactor } from '../../reactor.js';
15
+
16
+ chai.should();
17
+
18
+ // Runs against a real Chronicle kernel; skipped locally unless the connection string is set (see vitest.integration.config.ts).
19
+ // In CI it never skips, so a missing connection string or unreachable kernel fails instead of passing vacuously.
20
+ const connectionString = process.env.CHRONICLE_INTEGRATION_CONNECTION_STRING;
21
+
22
+ @eventType()
23
+ class ThingHappened {
24
+ @field(String) name = '';
25
+ }
26
+
27
+ // The client constructs reactor instances; share sinks for assertions across that boundary.
28
+ const onceOnlyInvocations: string[] = [];
29
+ const replayableInvocations: string[] = [];
30
+
31
+ @reactor()
32
+ @onceOnly()
33
+ class OnceOnlyReactor {
34
+ thingHappened(event: ThingHappened) { onceOnlyInvocations.push(event.name); }
35
+ }
36
+
37
+ @reactor()
38
+ class ReplayableReactor {
39
+ thingHappened(event: ThingHappened) { replayableInvocations.push(event.name); }
40
+ }
41
+
42
+ const artifacts: IClientArtifactsProvider = {
43
+ eventTypes: [ThingHappened],
44
+ readModels: [],
45
+ reactors: [OnceOnlyReactor, ReplayableReactor],
46
+ reducers: [],
47
+ seeders: [],
48
+ constraints: [],
49
+ projections: [],
50
+ webhooks: [],
51
+ eventTypeMigrations: [],
52
+ globalForHandlers: []
53
+ };
54
+
55
+ async function eventually(accept: () => boolean, timeoutMs = 30_000): Promise<void> {
56
+ const deadline = Date.now() + timeoutMs;
57
+ while (!accept()) {
58
+ if (Date.now() > deadline) throw new Error('Timed out waiting for the kernel');
59
+ await new Promise(resolve => setTimeout(resolve, 250));
60
+ }
61
+ }
62
+
63
+ const isEmptyJobId = (jobId: string | undefined) => /^[0-]*$/.test(jobId ?? '');
64
+
65
+ describe.skipIf(!connectionString && !process.env.CI)('when replaying reactors against a kernel', () => {
66
+ const storeName = `Replay${randomUUID().replaceAll('-', '').slice(0, 12)}`;
67
+ let client: ChronicleClient;
68
+ let store: IEventStore;
69
+ let connection: ChronicleConnection;
70
+ let onceOnlyJobId: string | undefined;
71
+ let replayableJobId: string | undefined;
72
+
73
+ const replay = (observerId: string) => connection.observers.replay({
74
+ EventStore: storeName,
75
+ Namespace: 'Default',
76
+ ObserverId: observerId,
77
+ EventSequenceId: 'event-log'
78
+ });
79
+
80
+ beforeAll(async () => {
81
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
82
+ discoveryPatterns: [],
83
+ clientArtifactsProvider: artifacts
84
+ }));
85
+ store = await client.getEventStore(storeName);
86
+ connection = (store as unknown as { _connection: ChronicleConnection })._connection;
87
+
88
+ (await store.eventLog.append(randomUUID(), Object.assign(new ThingHappened(), { name: 'first' }))).isSuccess.should.be.true;
89
+ await eventually(() => onceOnlyInvocations.length === 1 && replayableInvocations.length === 1);
90
+
91
+ onceOnlyJobId = (await replay('OnceOnlyReactor')).JobId;
92
+ replayableJobId = (await replay('ReplayableReactor')).JobId;
93
+ await eventually(() => replayableInvocations.length === 2);
94
+ await new Promise(resolve => setTimeout(resolve, 3_000));
95
+ });
96
+
97
+ afterAll(() => client?.dispose());
98
+
99
+ it('should replay a reactor that is not once-only', () => {
100
+ isEmptyJobId(replayableJobId).should.be.false;
101
+ replayableInvocations.should.deep.equal(['first', 'first']);
102
+ });
103
+
104
+ it('should not start a replay of a class-level once-only reactor', () => {
105
+ isEmptyJobId(onceOnlyJobId).should.be.true;
106
+ });
107
+
108
+ it('should not invoke a class-level once-only reactor again', () => {
109
+ onceOnlyInvocations.should.deep.equal(['first']);
110
+ });
111
+ });
@@ -0,0 +1,88 @@
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 { randomUUID } from 'node:crypto';
5
+ import { afterAll, beforeAll, chai, describe, it } from 'vitest';
6
+ import type { WebhookDefinition } from '@cratis/chronicle.contracts';
7
+ import { field } from '@cratis/fundamentals';
8
+ import { ChronicleClient } from '../../../ChronicleClient.js';
9
+ import { ChronicleOptions } from '../../../ChronicleOptions.js';
10
+ import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
11
+ import { eventType } from '../../../events/index.js';
12
+ import type { IEventStore } from '../../../IEventStore.js';
13
+
14
+ chai.should();
15
+
16
+ // Runs against a real Chronicle kernel; skipped locally unless the connection string is set (see vitest.integration.config.ts).
17
+ // In CI it never skips, so a missing connection string or unreachable kernel fails instead of passing vacuously.
18
+ const connectionString = process.env.CHRONICLE_INTEGRATION_CONNECTION_STRING;
19
+
20
+ @eventType()
21
+ class OrderShipped {
22
+ @field(String) orderId = '';
23
+ }
24
+
25
+ const artifacts: IClientArtifactsProvider = {
26
+ eventTypes: [OrderShipped],
27
+ readModels: [],
28
+ reactors: [],
29
+ reducers: [],
30
+ seeders: [],
31
+ constraints: [],
32
+ projections: [],
33
+ webhooks: [],
34
+ eventTypeMigrations: [],
35
+ globalForHandlers: []
36
+ };
37
+
38
+ async function eventually<T>(read: () => Promise<T>, accept: (value: T) => boolean, timeoutMs = 20_000): Promise<T> {
39
+ const deadline = Date.now() + timeoutMs;
40
+ let value = await read();
41
+ while (!accept(value)) {
42
+ if (Date.now() > deadline) throw new Error('Timed out waiting for the kernel');
43
+ await new Promise(resolve => setTimeout(resolve, 100));
44
+ value = await read();
45
+ }
46
+ return value;
47
+ }
48
+
49
+ describe.skipIf(!connectionString && !process.env.CI)('when registering and removing a webhook against a kernel', () => {
50
+ const webhookId = randomUUID();
51
+ const targetUrl = 'http://localhost:9/orders';
52
+ let client: ChronicleClient;
53
+ let store: IEventStore;
54
+ let registered: WebhookDefinition | undefined;
55
+ let afterRemove: WebhookDefinition[];
56
+ let registerWithoutIdentifier: unknown;
57
+
58
+ const findRegistered = async () => (await store.webhooks.getWebhooks()).find(_ => _.Identifier === webhookId);
59
+
60
+ beforeAll(async () => {
61
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
62
+ discoveryPatterns: [],
63
+ clientArtifactsProvider: artifacts
64
+ }));
65
+ store = await client.getEventStore(`WebhooksEndToEnd${randomUUID().replaceAll('-', '')}`);
66
+
67
+ await store.webhooks.register(webhookId, targetUrl, _ => _
68
+ .withEventType(OrderShipped)
69
+ .withHeader('X-Source', 'specs'));
70
+
71
+ // The kernel records the registration as events and builds its webhook list from them, so it shows up eventually.
72
+ registered = await eventually(findRegistered, _ => _ !== undefined);
73
+
74
+ await store.webhooks.remove(webhookId);
75
+ afterRemove = await eventually(() => store.webhooks.getWebhooks(), _ => !_.some(webhook => webhook.Identifier === webhookId));
76
+
77
+ registerWithoutIdentifier = await store.webhooks.register('', targetUrl, _ => _.withEventType(OrderShipped)).catch((error: unknown) => error);
78
+ });
79
+
80
+ afterAll(() => client?.dispose());
81
+
82
+ it('should list the webhook', () => registered!.Identifier.should.equal(webhookId));
83
+ it('should keep the target url', () => registered!.Target!.Url.should.equal(targetUrl));
84
+ it('should keep the header', () => registered!.Target!.Headers['X-Source'].should.equal('specs'));
85
+ it('should keep the event type', () => registered!.EventTypes.map(_ => _.Id).should.deep.equal(['OrderShipped']));
86
+ it('should no longer list the removed webhook', () => afterRemove.some(_ => _.Identifier === webhookId).should.be.false);
87
+ it('should report a registration the kernel rejects', () => registerWithoutIdentifier.should.be.instanceOf(Error));
88
+ });