@cratis/chronicle 6.52.1 → 6.53.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 (41) hide show
  1. package/dist/projections/ProjectionDefinitionCompiler.d.ts.map +1 -1
  2. package/dist/projections/ProjectionDefinitionCompiler.js +22 -18
  3. package/dist/projections/ProjectionDefinitionCompiler.js.map +1 -1
  4. package/dist/projections/modelBound/childrenAndNestedBuilder.d.ts +6 -4
  5. package/dist/projections/modelBound/childrenAndNestedBuilder.d.ts.map +1 -1
  6. package/dist/projections/modelBound/childrenAndNestedBuilder.js +14 -12
  7. package/dist/projections/modelBound/childrenAndNestedBuilder.js.map +1 -1
  8. package/dist/reactors/Reactors.d.ts.map +1 -1
  9. package/dist/reactors/Reactors.js +2 -0
  10. package/dist/reactors/Reactors.js.map +1 -1
  11. package/dist/reactors/index.d.ts +1 -0
  12. package/dist/reactors/index.d.ts.map +1 -1
  13. package/dist/reactors/index.js +1 -0
  14. package/dist/reactors/index.js.map +1 -1
  15. package/dist/reactors/startAtTail.d.ts +18 -0
  16. package/dist/reactors/startAtTail.d.ts.map +1 -0
  17. package/dist/reactors/startAtTail.js +30 -0
  18. package/dist/reactors/startAtTail.js.map +1 -0
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/dist/webhooks/WebhookDefinitionBuilder.d.ts +1 -1
  21. package/dist/webhooks/WebhookDefinitionBuilder.d.ts.map +1 -1
  22. package/dist/webhooks/WebhookDefinitionBuilder.js +3 -1
  23. package/dist/webhooks/WebhookDefinitionBuilder.js.map +1 -1
  24. package/dist/webhooks/Webhooks.d.ts.map +1 -1
  25. package/dist/webhooks/Webhooks.js +2 -1
  26. package/dist/webhooks/Webhooks.js.map +1 -1
  27. package/jobs/for_Jobs/against_a_kernel/when_managing_a_replay_job.integration.spec.ts +25 -15
  28. package/package.json +2 -2
  29. package/projections/ProjectionDefinitionCompiler.ts +21 -18
  30. package/projections/for_ProjectionDefinitionCompiler/against_a_kernel/when_subscribing_with_from_all_events.integration.spec.ts +52 -48
  31. package/projections/for_ProjectionDefinitionCompiler/when_compiling_from_all_events.spec.ts +52 -25
  32. package/projections/for_ProjectionDefinitionCompiler/when_compiling_from_all_events.standard.spec.ts +49 -9
  33. package/projections/modelBound/childrenAndNestedBuilder.ts +17 -12
  34. package/reactors/Reactors.startAtTail.spec.ts +60 -0
  35. package/reactors/Reactors.ts +2 -0
  36. package/reactors/for_Reactors/against_a_kernel/when_starting_at_the_tail.integration.spec.ts +107 -0
  37. package/reactors/index.ts +1 -0
  38. package/reactors/startAtTail.spec.ts +31 -0
  39. package/reactors/startAtTail.ts +33 -0
  40. package/webhooks/WebhookDefinitionBuilder.ts +9 -7
  41. package/webhooks/Webhooks.ts +2 -1
@@ -65,8 +65,8 @@ class AllWithChildMappings {
65
65
  @field(Array, { genericArguments: [AllMappedChild] }) @childrenFrom(ChildAdded, 'childId') children: AllMappedChild[] = [];
66
66
  }
67
67
 
68
- // Without root all-event subscription, the shared All block needs a root From entry
69
- // for ChildAdded as well as the child's creating entry.
68
+ // The root fromEvery mapping handles ChildAdded only because the root explicitly
69
+ // subscribes to it; the child's All mapping belongs to the child independently.
70
70
  @fromEvent(Started)
71
71
  @fromEvent(ChildAdded)
72
72
  class ChildOnlyMappings {
@@ -81,20 +81,6 @@ const artifacts: IClientArtifactsProvider = {
81
81
  eventTypeMigrations: [], globalForHandlers: []
82
82
  };
83
83
 
84
- async function eventually<T>(read: () => Promise<T>, accept: (value: T) => boolean): Promise<T> {
85
- const deadline = Date.now() + 20_000;
86
- let value = await read();
87
- while (!accept(value)) {
88
- if (Date.now() > deadline) {
89
- const state = JSON.stringify(value, (_key, member: unknown) => typeof member === 'bigint' ? member.toString() : member);
90
- throw new Error(`Timed out waiting for the projected state: ${state}`);
91
- }
92
- await new Promise(resolve => setTimeout(resolve, 100));
93
- value = await read();
94
- }
95
- return value;
96
- }
97
-
98
84
  describe.skipIf(!connectionString && !process.env.CI)('when opting into fromAllEvents against a kernel', () => {
99
85
  const knownSource = randomUUID();
100
86
  const unrelatedSource = randomUUID();
@@ -111,25 +97,32 @@ describe.skipIf(!connectionString && !process.env.CI)('when opting into fromAllE
111
97
  let allAfterUnrelated: AllWithChildren | null;
112
98
  let restrictedAfterUnrelated: RestrictedWithChildren | null;
113
99
  let allChildMappingsAfterChild: AllWithChildMappings | null;
100
+ let allChildMappingsAfterUpdate: AllWithChildMappings | null;
114
101
  let childOnlyAfterChild: ChildOnlyMappings | null;
115
102
  let childOnlyAfterUnrelated: ChildOnlyMappings | null;
116
103
  let unrelatedChildOnly: ChildOnlyMappings | null;
117
104
 
118
- async function append(source: string, event: object): Promise<bigint> {
105
+ async function append(source: string, event: object, waitForObservers = true): Promise<bigint> {
119
106
  const result = await store.eventLog.append(source, event);
120
107
  result.isSuccess.should.be.true;
108
+ if (waitForObservers) {
109
+ const completion = await result.waitForCompletion(20_000);
110
+ completion.isSuccess.should.equal(true, `Observer completion failed: ${JSON.stringify(completion.failedPartitions)}`);
111
+ }
121
112
  return result.sequenceNumber.value;
122
113
  }
123
114
 
124
115
  async function waitForObserver(observerId: string, sequenceNumber: bigint): Promise<void> {
125
116
  const connection = (store as unknown as { _connection: ChronicleConnection })._connection;
126
- await eventually(() => connection.observers.getObserverInformation({
117
+ const observer = await connection.observers.getObserverInformation({
127
118
  EventStore: storeName,
128
119
  Namespace: 'Default',
129
120
  ObserverId: observerId,
130
121
  EventSequenceId: 'event-log'
131
- }), observer => observer.IsSubscribed && observer.RunningState === ObserverRunningState.Active &&
132
- observer.LastHandledEventSequenceNumber >= sequenceNumber);
122
+ }, { signal: AbortSignal.timeout(5_000) });
123
+ observer.IsSubscribed.should.equal(true, `${observerId} must be subscribed`);
124
+ observer.RunningState.should.equal(ObserverRunningState.Active);
125
+ (observer.LastHandledEventSequenceNumber >= sequenceNumber).should.equal(true, `${observerId} must have handled ${sequenceNumber}`);
133
126
  }
134
127
 
135
128
  beforeAll(async () => {
@@ -138,27 +131,33 @@ describe.skipIf(!connectionString && !process.env.CI)('when opting into fromAllE
138
131
  }));
139
132
  store = await client.getEventStore(storeName);
140
133
 
141
- await append(knownSource, Object.assign(new Started(), { value: 'started' }));
142
- allAfterStarted = await eventually(() => store.readModels.findInstanceById(AllWithChildren, knownSource), model => model?.lastValue === 'started');
143
- await eventually(() => store.readModels.findInstanceById(RestrictedWithChildren, knownSource), model => model?.lastValue === 'started');
144
- await append(knownSource, Object.assign(new ChildAdded(), { childId: 'child-one', value: 'child-value' }));
145
- allAfterChild = await eventually(() => store.readModels.findInstanceById(AllWithChildren, knownSource), model => model?.children?.length === 1);
146
- restrictedAfterChild = await eventually(() => store.readModels.findInstanceById(RestrictedWithChildren, knownSource), model => model?.children?.length === 1);
147
- childOnlyAfterChild = await eventually(() => store.readModels.findInstanceById(ChildOnlyMappings, knownSource), model => model?.children?.length === 1);
148
- allChildMappingsAfterChild = await eventually(() => store.readModels.findInstanceById(AllWithChildMappings, knownSource), model => model?.children?.length === 1);
149
-
150
- await append(knownSource, Object.assign(new Unrelated(), { marker: 'no-value' }));
151
- allAfterUnrelated = await eventually(() => store.readModels.findInstanceById(AllWithChildren, knownSource),
152
- model => model !== null && model.lastValue === '');
153
-
154
- await append(unrelatedSource, Object.assign(new Unrelated(), { marker: 'new-source' }));
155
- allOnly = await eventually(() => store.readModels.findInstanceById(AllOnly, unrelatedSource), model => model !== null);
156
- unrelatedAll = await eventually(() => store.readModels.findInstanceById(AllWithChildren, unrelatedSource), model => model !== null);
157
- // A subscribed sentinel advances each restricted observer past both unrelated events.
158
- // Progress on an all-event projection is not a barrier for another observer.
134
+ const startedSequenceNumber = await append(knownSource, Object.assign(new Started(), { value: 'started' }));
135
+ await waitForObserver('AllWithChildren', startedSequenceNumber);
136
+ allAfterStarted = await store.readModels.findInstanceById(AllWithChildren, knownSource);
137
+ const childSequenceNumber = await append(knownSource, Object.assign(new ChildAdded(), { childId: 'child-one', value: 'child-value' }));
138
+ for (const observerId of ['AllWithChildren', 'RestrictedWithChildren', 'ChildOnlyMappings', 'AllWithChildMappings']) {
139
+ await waitForObserver(observerId, childSequenceNumber);
140
+ }
141
+ allAfterChild = await store.readModels.findInstanceById(AllWithChildren, knownSource);
142
+ restrictedAfterChild = await store.readModels.findInstanceById(RestrictedWithChildren, knownSource);
143
+ childOnlyAfterChild = await store.readModels.findInstanceById(ChildOnlyMappings, knownSource);
144
+ allChildMappingsAfterChild = await store.readModels.findInstanceById(AllWithChildMappings, knownSource);
145
+
146
+ const updatedSequenceNumber = await append(knownSource, Object.assign(new ChildAdded(), { childId: 'child-one', value: 'updated-child-value' }));
147
+ await waitForObserver('AllWithChildMappings', updatedSequenceNumber);
148
+ allChildMappingsAfterUpdate = await store.readModels.findInstanceById(AllWithChildMappings, knownSource);
149
+
150
+ // This client's completion request carries only a global tail, so restricted
151
+ // observers cannot complete an unrelated append until a subscribed sentinel follows.
152
+ await append(knownSource, Object.assign(new Unrelated(), { marker: 'no-value' }), false);
153
+ await append(unrelatedSource, Object.assign(new Unrelated(), { marker: 'new-source' }), false);
159
154
  const sentinelSequenceNumber = await append(sentinelSource, Object.assign(new Started(), { value: 'sentinel' }));
160
- await waitForObserver('RestrictedWithChildren', sentinelSequenceNumber);
161
- await waitForObserver('ChildOnlyMappings', sentinelSequenceNumber);
155
+ for (const observerId of ['AllOnly', 'AllWithChildren', 'RestrictedWithChildren', 'ChildOnlyMappings']) {
156
+ await waitForObserver(observerId, sentinelSequenceNumber);
157
+ }
158
+ allAfterUnrelated = await store.readModels.findInstanceById(AllWithChildren, knownSource);
159
+ allOnly = await store.readModels.findInstanceById(AllOnly, unrelatedSource);
160
+ unrelatedAll = await store.readModels.findInstanceById(AllWithChildren, unrelatedSource);
162
161
  restrictedAfterUnrelated = await store.readModels.findInstanceById(RestrictedWithChildren, knownSource);
163
162
  unrelatedRestricted = await store.readModels.findInstanceById(RestrictedWithChildren, unrelatedSource);
164
163
  childOnlyAfterUnrelated = await store.readModels.findInstanceById(ChildOnlyMappings, knownSource);
@@ -173,10 +172,11 @@ describe.skipIf(!connectionString && !process.env.CI)('when opting into fromAllE
173
172
  (unrelatedRestricted === null).should.be.true;
174
173
  });
175
174
  it('should give the explicit all-event mapping precedence over fromEvery', () => allAfterStarted!.lastValue.should.equal('started'));
176
- it('should apply the root all-event mapping to a child', () => {
175
+ it('should update the root on a child event without copying its mapping into the child', () => {
176
+ allAfterChild!.lastValue.should.equal('child-value');
177
177
  allAfterChild!.children.should.have.lengthOf(1);
178
178
  allAfterChild!.children[0].id.should.equal('child-one');
179
- allAfterChild!.children[0].lastValue.should.equal('child-value');
179
+ allAfterChild!.children[0].lastValue.should.equal('');
180
180
  });
181
181
  it('should not propagate the deprecated restricted alias mapping to children', () => {
182
182
  restrictedAfterChild!.children.should.have.lengthOf(1);
@@ -186,17 +186,21 @@ describe.skipIf(!connectionString && !process.env.CI)('when opting into fromAllE
186
186
  allAfterUnrelated!.lastValue.should.equal('');
187
187
  });
188
188
  it('should leave the restricted alias unchanged on an unrelated event', () => restrictedAfterUnrelated!.lastValue.should.equal(restrictedAfterChild!.lastValue));
189
- it('should apply a child-declared all-event mapping through the shared root All block', () => {
189
+ it('should apply a child-declared mapping on creation without changing an unmapped same-named root property', () => {
190
190
  allChildMappingsAfterChild!.children[0].lastValue.should.equal('child-value');
191
- // The child event's key routes the all-event fallback to the child, not the root.
192
- allChildMappingsAfterChild!.lastValue.should.equal('started');
191
+ allChildMappingsAfterChild!.source.should.equal(knownSource);
192
+ allChildMappingsAfterChild!.lastValue.should.equal('');
193
+ });
194
+ it('should update the existing child through its own All mapping on subsequent child events', () => {
195
+ allChildMappingsAfterUpdate!.children.should.have.lengthOf(1);
196
+ allChildMappingsAfterUpdate!.children[0].lastValue.should.equal('updated-child-value');
197
+ allChildMappingsAfterUpdate!.lastValue.should.equal('');
193
198
  });
194
199
  it('should keep the root subscription restricted when only the child declares fromAllEvents', () => {
195
200
  childOnlyAfterChild!.rootValue.should.equal('child-value');
196
201
  childOnlyAfterChild!.children[0].id.should.equal('child-one');
197
- // The explicitly subscribed root From entry maps the root, not the child's shared values.
198
- childOnlyAfterChild!.children[0].lastValue.should.equal('');
199
- childOnlyAfterUnrelated!.rootValue.should.equal('child-value');
202
+ childOnlyAfterChild!.children[0].lastValue.should.equal('child-value');
203
+ childOnlyAfterUnrelated!.rootValue.should.equal('updated-child-value');
200
204
  (unrelatedChildOnly === null).should.be.true;
201
205
  });
202
206
  });
@@ -116,13 +116,13 @@ describe('when compiling fromAllEvents on a child model', () => {
116
116
  (definition.SubscribesToAllEvents === undefined).should.be.true;
117
117
  ('SubscribesToAllEvents' in definition.Children.items).should.be.false;
118
118
  });
119
- it('should collect the child mapping by bare name in the root All without subscribing to all events', () => {
119
+ it('should collect the mapping only in the owning child All with its full diagnostic path', () => {
120
120
  const { compiled, definition } = compileModelBound(Parent);
121
- definition.All!.should.deep.equal({ Properties: { title: 'name' }, IncludeChildren: true, AutoMap: 0 });
122
- definition.Children.items.All!.Properties.should.deep.equal({});
121
+ definition.All!.should.deep.equal({ Properties: {}, IncludeChildren: false, AutoMap: 0 });
122
+ definition.Children.items.All!.should.deep.equal({ Properties: { title: 'name' }, IncludeChildren: true, AutoMap: 0 });
123
123
  compiled.provenance.get(definition)!.should.include.deep.members([
124
- { contractPath: 'All', declaration: '@fromAllEvents' },
125
- { contractPath: 'All.Properties.title', declaration: '@fromAllEvents' }
124
+ { contractPath: 'Children.items.All', declaration: '@fromAllEvents' },
125
+ { contractPath: 'Children.items.All.Properties.title', declaration: '@fromAllEvents' }
126
126
  ]);
127
127
  });
128
128
  it('should emit the subscription only at the root when the parent opts in', () => {
@@ -131,17 +131,26 @@ describe('when compiling fromAllEvents on a child model', () => {
131
131
  const { definition } = compileModelBound(AllParent);
132
132
  definition.SubscribesToAllEvents.should.be.true;
133
133
  definition.All!.should.deep.equal({
134
- Properties: { source: '$eventContext(EventSourceId)', title: 'name' }, IncludeChildren: true, AutoMap: 0
134
+ Properties: { source: '$eventContext(EventSourceId)' }, IncludeChildren: true, AutoMap: 0
135
135
  });
136
136
  ('SubscribesToAllEvents' in definition.Children.items).should.be.false;
137
137
  });
138
- it('should share one bare-name mapping when a later child member shadows a root member', () => {
139
- class AllParent extends Model { items: Child[] = []; }
140
- fromAllEvents('rootName')(AllParent.prototype, 'title');
141
- field(Array, { genericArguments: [Child] })(AllParent.prototype, 'items');
142
- childrenFrom(Added, 'id')(AllParent.prototype, 'items');
143
- compileModelBound(AllParent).definition.All!.Properties.should.deep.equal({ title: 'name' });
144
- });
138
+ for (const childFirst of [true, false]) {
139
+ it(`should keep same-named root and child sources independent with child declared ${childFirst ? 'first' : 'last'}`, () => {
140
+ class AllParent { title = ''; items: Child[] = []; }
141
+ const declareChild = () => {
142
+ field(Array, { genericArguments: [Child] })(AllParent.prototype, 'items');
143
+ childrenFrom(Added, 'id')(AllParent.prototype, 'items');
144
+ };
145
+ if (childFirst) declareChild();
146
+ field(String)(AllParent.prototype, 'title');
147
+ fromAllEvents('rootName')(AllParent.prototype, 'title');
148
+ if (!childFirst) declareChild();
149
+ const { definition } = compileModelBound(AllParent);
150
+ definition.All!.Properties.should.deep.equal({ title: 'rootName' });
151
+ definition.Children.items.All!.Properties.should.deep.equal({ title: 'name' });
152
+ });
153
+ }
145
154
  });
146
155
 
147
156
  describe('when compiling fromAllEvents on nested and inherited child models', () => {
@@ -172,16 +181,35 @@ describe('when compiling fromAllEvents on nested and inherited child models', ()
172
181
  field(Detail)(Parent.prototype, 'detail');
173
182
  nested(Parent.prototype, 'detail');
174
183
 
175
- it('should collect grandchild and nested mappings into the root without path prefixes or legacy child mappings', () => {
176
- const { definition } = compileModelBound(Parent);
177
- definition.All!.should.deep.equal({
178
- Properties: { title: 'name', label: 'label', sequence: '$eventContext(SequenceNumber)' },
179
- IncludeChildren: true, AutoMap: 0
180
- });
184
+ it('should keep grandchild and nested mappings on their declaring levels including inherited fromEvery', () => {
185
+ const { compiled, definition } = compileModelBound(Parent);
186
+ definition.All!.should.deep.equal({ Properties: {}, IncludeChildren: false, AutoMap: 0 });
181
187
  (definition.SubscribesToAllEvents === undefined).should.be.true;
182
- definition.Children.groups.Children.children.All!.Properties.should.deep.equal({});
183
- definition.Children.groups.Children.children.Nested.detail.All!.Properties.should.deep.equal({});
184
- definition.Nested.detail.All!.Properties.should.deep.equal({});
188
+ definition.Children.groups.All!.Properties.should.deep.equal({});
189
+ definition.Children.groups.Children.children.All!.Properties.should.deep.equal({ title: 'name', ignored: 'ignoredEvery' });
190
+ const detailMappings = { label: 'label', sequence: '$eventContext(SequenceNumber)' };
191
+ definition.Children.groups.Children.children.Nested.detail.All!.Properties.should.deep.equal(detailMappings);
192
+ definition.Nested.detail.All!.Properties.should.deep.equal(detailMappings);
193
+ compiled.provenance.get(definition)!.should.include.deep.members([
194
+ { contractPath: 'Children.groups.Children.children.All.Properties.ignored', declaration: '@fromEvery' },
195
+ { contractPath: 'Children.groups.Children.children.Nested.detail.All.Properties.sequence', declaration: '@fromAllEvents' },
196
+ { contractPath: 'Nested.detail.All.Properties.label', declaration: '@fromAllEvents' }
197
+ ]);
198
+ });
199
+ it('should keep a sibling fromEvery context mapping local without enabling IncludeChildren or the deprecated child alias', () => {
200
+ class RestrictedChild { id = ''; source = ''; ignored = ''; }
201
+ for (const property of ['id', 'source', 'ignored']) field(String)(RestrictedChild.prototype, property);
202
+ fromEvery(undefined, 'eventSourceId')(RestrictedChild.prototype, 'source');
203
+ fromAll('ignoredAlias')(RestrictedChild.prototype, 'ignored');
204
+ class RestrictedParent { items: RestrictedChild[] = []; }
205
+ field(Array, { genericArguments: [RestrictedChild] })(RestrictedParent.prototype, 'items');
206
+ childrenFrom(Added, 'id')(RestrictedParent.prototype, 'items');
207
+ const { definition } = compileModelBound(RestrictedParent);
208
+ definition.All!.should.deep.equal({ Properties: {}, IncludeChildren: false, AutoMap: 0 });
209
+ definition.Children.items.All!.should.deep.equal({
210
+ Properties: { source: '$eventContext(EventSourceId)' }, IncludeChildren: false, AutoMap: 0
211
+ });
212
+ compileModelBound(Parent).definition.Children.groups.Children.children.All!.Properties.title.should.equal('name');
185
213
  });
186
214
  it('should collect a nested-only mapping without widening the root subscription', () => {
187
215
  class NestedOnly { detail = new Detail(); }
@@ -189,9 +217,8 @@ describe('when compiling fromAllEvents on nested and inherited child models', ()
189
217
  field(Detail)(NestedOnly.prototype, 'detail');
190
218
  nested(NestedOnly.prototype, 'detail');
191
219
  const { definition } = compileModelBound(NestedOnly);
192
- definition.All!.should.deep.equal({
193
- Properties: { label: 'label', sequence: '$eventContext(SequenceNumber)' }, IncludeChildren: true, AutoMap: 0
194
- });
220
+ definition.All!.should.deep.equal({ Properties: {}, IncludeChildren: false, AutoMap: 0 });
221
+ definition.Nested.detail.All!.Properties.should.deep.equal({ label: 'label', sequence: '$eventContext(SequenceNumber)' });
195
222
  (definition.SubscribesToAllEvents === undefined).should.be.true;
196
223
  ('SubscribesToAllEvents' in definition.Nested.detail).should.be.false;
197
224
  });
@@ -61,26 +61,66 @@ describe('when compiling standard fromAllEvents without explicit event subscript
61
61
  should(getFromAllEventsMetadata(Alias.prototype, 'title') === undefined).be.true;
62
62
  });
63
63
 
64
- it('should collect standard child and nested mappings in the root All without widening the subscription', () => {
64
+ it('should collect standard child and nested mappings on their owning levels without widening the subscription', () => {
65
65
  @eventType('standard-from-all-events-child-added')
66
66
  class Added { @field(String) id = ''; }
67
- class Detail { @field(String) @fromAllEvents(undefined, 'sequenceNumber') sequence = ''; }
67
+ class Detail {
68
+ @field(String) @fromAllEvents(undefined, 'sequenceNumber') sequence = '';
69
+ @field(String) @fromAllEvents() label = '';
70
+ }
68
71
  class Child {
69
72
  @field(String) id = '';
70
73
  @field(String) @fromAllEvents('name') title = '';
74
+ @field(String) @fromEvery('everyName') @fromAll('aliasName') restricted = '';
71
75
  @field(Detail) @nested detail = new Detail();
72
76
  }
73
77
  class Derived extends Child {}
74
- class Parent {
78
+ class Sibling extends Child { @field(String) @fromAllEvents('siblingName') override title = ''; }
79
+ class Group {
75
80
  @field(Array, { genericArguments: [Derived] }) @childrenFrom(Added, 'id') items: Derived[] = [];
76
81
  }
77
- const { definition } = compileModelBound(Parent);
78
- should(definition.All).deep.equal({
79
- Properties: { title: 'name', sequence: '$eventContext(SequenceNumber)' }, IncludeChildren: true, AutoMap: 0
80
- });
82
+ class Parent {
83
+ @field(Array, { genericArguments: [Group] }) @childrenFrom(Added, 'id') groups: Group[] = [];
84
+ @field(Array, { genericArguments: [Sibling] }) @childrenFrom(Added, 'id') siblings: Sibling[] = [];
85
+ @field(Detail) @nested detail = new Detail();
86
+ }
87
+ const { compiled, definition } = compileModelBound(Parent);
88
+ should(definition.All).deep.equal({ Properties: {}, IncludeChildren: false, AutoMap: 0 });
81
89
  should(definition.SubscribesToAllEvents === undefined).be.true;
82
- should(definition.Children.items.All!.Properties).deep.equal({});
83
- should(definition.Children.items.Nested.detail.All!.Properties).deep.equal({});
90
+ should(definition.Children.groups.All!.Properties).deep.equal({});
91
+ should(definition.Children.groups.Children.items.All!.Properties).deep.equal({ title: 'name', restricted: 'everyName' });
92
+ should(definition.Children.siblings.All!.Properties).deep.equal({ title: 'siblingName', restricted: 'everyName' });
93
+ const detailMappings = { sequence: '$eventContext(SequenceNumber)', label: 'label' };
94
+ should(definition.Children.groups.Children.items.Nested.detail.All!.Properties).deep.equal(detailMappings);
95
+ should(definition.Nested.detail.All!.Properties).deep.equal(detailMappings);
96
+ should(compiled.provenance.get(definition)).include.deep.members([
97
+ { contractPath: 'Children.groups.Children.items.All.Properties.restricted', declaration: '@fromEvery' },
98
+ { contractPath: 'Children.groups.Children.items.Nested.detail.All.Properties.sequence', declaration: '@fromAllEvents' }
99
+ ]);
100
+ });
101
+
102
+ it('should preserve independent same-named root and child mappings in either property order', () => {
103
+ @eventType('standard-all-same-name-added')
104
+ class Added { @field(String) id = ''; }
105
+ class Child {
106
+ @field(String) id = '';
107
+ @field(String) @fromEvery('ignored') @fromAllEvents('childName') title = '';
108
+ @field(String) @fromAllEvents('childOther') @fromEvery('ignored') other = '';
109
+ }
110
+ class RootFirst {
111
+ @field(String) @fromAllEvents('rootName') title = '';
112
+ @field(Array, { genericArguments: [Child] }) @childrenFrom(Added, 'id') items: Child[] = [];
113
+ }
114
+ class ChildFirst {
115
+ @field(Array, { genericArguments: [Child] }) @childrenFrom(Added, 'id') items: Child[] = [];
116
+ @field(String) @fromAllEvents('rootName') title = '';
117
+ }
118
+ for (const type of [RootFirst, ChildFirst]) {
119
+ const { definition } = compileModelBound(type);
120
+ should(definition.All!.Properties).deep.equal({ title: 'rootName' });
121
+ should(definition.Children.items.All!.Properties).deep.equal({ title: 'childName', other: 'childOther' });
122
+ should(definition.SubscribesToAllEvents).be.true;
123
+ }
84
124
  });
85
125
 
86
126
  it('should reject all-event scenarios before replay with the standard decorator declaration', () => {
@@ -234,12 +234,14 @@ function discoverIdentifiedBy(childType: Function | undefined, eventKey: string
234
234
  * `@childrenFrom`/`@nested` properties the child/nested type itself declares.
235
235
  * @param definition - The children definition being populated.
236
236
  * @param childType - The resolved child/nested type, when available.
237
- * @param collectSharedMapping - Collects member mappings into the root's shared All definition.
237
+ * @param path - The contract path of this child or nested definition.
238
+ * @param collectSharedMapping - Collects member mappings into their owning All definition.
238
239
  */
239
240
  function populateFromType(
240
241
  definition: ChildrenDefinitionLike,
241
242
  childType: Function | undefined,
242
- collectSharedMapping?: (prototype: object, property: string) => void
243
+ path: string,
244
+ collectSharedMapping?: (prototype: object, property: string, all: ChildrenDefinitionLike['All'], path: string) => void
243
245
  ): void {
244
246
  if (!childType) {
245
247
  return;
@@ -281,8 +283,7 @@ function populateFromType(
281
283
 
282
284
  const prototype = childType.prototype;
283
285
  const properties = TypeIntrospector.getTrackedProperties(childType);
284
- // Like .NET, collect this type's members before descending into its children.
285
- for (const property of properties) collectSharedMapping?.(prototype, property);
286
+ for (const property of properties) collectSharedMapping?.(prototype, property, definition.All, `${path}.All`);
286
287
  for (const property of properties) {
287
288
  applyPropertyMappings(prototype, property, fromByEventType);
288
289
 
@@ -307,11 +308,11 @@ function populateFromType(
307
308
 
308
309
  const childrenFromList = getChildrenFromMetadata(prototype, property);
309
310
  if (childrenFromList.length > 0) {
310
- definition.Children[property] = buildChildrenEntry(childType, property, childrenFromList, collectSharedMapping);
311
+ definition.Children[property] = buildChildrenEntry(childType, property, childrenFromList, collectSharedMapping, `${path}.Children.${property}`);
311
312
  }
312
313
 
313
314
  if (isNested(prototype, property)) {
314
- definition.Nested[property] = buildNestedEntry(childType, property, collectSharedMapping);
315
+ definition.Nested[property] = buildNestedEntry(childType, property, collectSharedMapping, `${path}.Nested.${property}`);
315
316
  }
316
317
  }
317
318
 
@@ -325,14 +326,16 @@ function populateFromType(
325
326
  * @param type - The class declaring the property.
326
327
  * @param property - The property name.
327
328
  * @param metadataList - The `@childrenFrom` metadata entries declared on the property (one per creating event type).
328
- * @param collectSharedMapping - Collects member mappings into the root's shared All definition.
329
+ * @param collectSharedMapping - Collects member mappings into their owning All definition.
330
+ * @param path - The contract path of this children definition.
329
331
  * @returns The wire-shaped children definition.
330
332
  */
331
333
  export function buildChildrenEntry(
332
334
  type: Function,
333
335
  property: string,
334
336
  metadataList: ChildrenFromMetadata[],
335
- collectSharedMapping?: (prototype: object, property: string) => void
337
+ collectSharedMapping?: (prototype: object, property: string, all: ChildrenDefinitionLike['All'], path: string) => void,
338
+ path = `Children.${property}`
336
339
  ): ChildrenDefinitionLike {
337
340
  const childType = resolveChildElementType(type, property);
338
341
  const definition = createEmptyChildrenDefinition(type, childType);
@@ -352,7 +355,7 @@ export function buildChildrenEntry(
352
355
  });
353
356
  }
354
357
 
355
- populateFromType(definition, childType, collectSharedMapping);
358
+ populateFromType(definition, childType, path, collectSharedMapping);
356
359
 
357
360
  // For non-aggregate-only creating events, populate an unmapped child identifier from
358
361
  // the creating event's key. IdentifiedBy selects the child property; it is not itself
@@ -395,13 +398,15 @@ export function buildChildrenEntry(
395
398
  * Builds the `ChildrenDefinition` for a `@nested` single-object property.
396
399
  * @param type - The class declaring the property.
397
400
  * @param property - The property name.
398
- * @param collectSharedMapping - Collects member mappings into the root's shared All definition.
401
+ * @param collectSharedMapping - Collects member mappings into their owning All definition.
402
+ * @param path - The contract path of this nested definition.
399
403
  * @returns The wire-shaped nested definition.
400
404
  */
401
405
  export function buildNestedEntry(
402
406
  type: Function,
403
407
  property: string,
404
- collectSharedMapping?: (prototype: object, property: string) => void
408
+ collectSharedMapping?: (prototype: object, property: string, all: ChildrenDefinitionLike['All'], path: string) => void,
409
+ path = `Nested.${property}`
405
410
  ): ChildrenDefinitionLike {
406
411
  const nestedType = resolveNestedType(type, property);
407
412
  const definition = createEmptyChildrenDefinition(type, nestedType);
@@ -414,6 +419,6 @@ export function buildNestedEntry(
414
419
  definition.RemovedWith.push({ Key: eventType, Value: { Key: '$eventSourceId', ParentKey: '' } });
415
420
  }
416
421
 
417
- populateFromType(definition, nestedType, collectSharedMapping);
422
+ populateFromType(definition, nestedType, path, collectSharedMapping);
418
423
  return definition;
419
424
  }
@@ -0,0 +1,60 @@
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 { ReactorMessage } from '@cratis/chronicle.contracts';
5
+ import { describe, expect, it } from 'vitest';
6
+ import type { IClientArtifactsProvider } from '../artifacts/index.js';
7
+ import type { ChronicleConnection } from '../connection/index.js';
8
+ import { ConnectionLifecycle } from '../connection/ConnectionLifecycle.js';
9
+ import type { IEventLog } from '../eventSequences/IEventLog.js';
10
+ import { eventType } from '../events/eventTypeDecorator.js';
11
+ import { reactor } from './reactor.js';
12
+ import { Reactors } from './Reactors.js';
13
+ import { startAtTail } from './startAtTail.js';
14
+
15
+ @eventType('start-at-tail-event')
16
+ class SomethingHappened {
17
+ constructor(readonly value: string = '') {}
18
+ }
19
+
20
+ @reactor('starts-at-tail')
21
+ @startAtTail()
22
+ class StartsAtTail {
23
+ somethingHappened() {}
24
+ }
25
+
26
+ @reactor('starts-at-the-beginning')
27
+ class StartsAtTheBeginning {
28
+ somethingHappened() {}
29
+ }
30
+
31
+ async function registrationOf(type: Function) {
32
+ const lifecycle = new ConnectionLifecycle();
33
+ let registration!: ReactorMessage;
34
+ let received!: () => void;
35
+ const registered = new Promise<void>(resolve => { received = resolve; });
36
+ async function* stream(queue: AsyncIterable<ReactorMessage>) {
37
+ registration = (await queue[Symbol.asyncIterator]().next()).value!;
38
+ received();
39
+ await new Promise(() => {});
40
+ }
41
+ const connection = { reactors: { observe: stream } } as unknown as ChronicleConnection;
42
+ const artifacts = { reactors: [type], eventTypes: [SomethingHappened] } as unknown as IClientArtifactsProvider;
43
+ const reactors = new Reactors(artifacts, connection, 'store', 'tenant', lifecycle, {} as IEventLog);
44
+ await reactors.register();
45
+ await registered;
46
+ reactors.dispose();
47
+ return registration.Content?.Value0?.Reactor;
48
+ }
49
+
50
+ describe('when registering a reactor marked to start at the tail', () => {
51
+ it('asks the kernel to begin at the tail', async () => {
52
+ expect((await registrationOf(StartsAtTail))?.StartAtTail).toBe(true);
53
+ });
54
+ });
55
+
56
+ describe('when registering a reactor that is not marked', () => {
57
+ it('does not ask the kernel to skip history', async () => {
58
+ expect((await registrationOf(StartsAtTheBeginning))?.StartAtTail).toBe(false);
59
+ });
60
+ });
@@ -22,6 +22,7 @@ import { IReactors } from './IReactors.js';
22
22
  import { dispatchReactorSideEffects } from './ReactorSideEffects.js';
23
23
  import { getReactorMetadata } from './reactor.js';
24
24
  import { isOnceOnly } from './onceOnly.js';
25
+ import { isStartAtTail } from './startAtTail.js';
25
26
  import { getReactorEventTypes, selectReactorHandler, invokeReactorHandler } from './ReactorDispatcher.js';
26
27
  import type { ReactorEventTypeEntry } from './ReactorDispatcher.js';
27
28
  import type { ReactorResultHandler } from './ReactorResultHandler.js';
@@ -277,6 +278,7 @@ export class Reactors implements IReactors {
277
278
  })),
278
279
  IsReplayable: !isOnceOnly(reactorType),
279
280
  IsNotReplayable: isOnceOnly(reactorType),
281
+ StartAtTail: isStartAtTail(reactorType),
280
282
  GenerationDelivery: EventGenerationDelivery.Compatibility,
281
283
  Tags: getTagsFor(reactorType).map(t => t.value),
282
284
  Filters: {
@@ -0,0 +1,107 @@
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 { eventType } from '../../../events/index.js';
11
+ import { reactor } from '../../reactor.js';
12
+ import { startAtTail } from '../../startAtTail.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 SomethingHappenedBeforeRegistration {
22
+ @field(String) name = '';
23
+ }
24
+
25
+ // The client constructs reactor instances; share sinks for assertions across that boundary.
26
+ const fromTheTail: string[] = [];
27
+ const fromTheBeginning: string[] = [];
28
+
29
+ @reactor()
30
+ @startAtTail()
31
+ class TailReactor {
32
+ somethingHappenedBeforeRegistration(event: SomethingHappenedBeforeRegistration) { fromTheTail.push(event.name); }
33
+ }
34
+
35
+ // The control: the same registration without the marker catches up on all history.
36
+ @reactor()
37
+ class HistoryReactor {
38
+ somethingHappenedBeforeRegistration(event: SomethingHappenedBeforeRegistration) { fromTheBeginning.push(event.name); }
39
+ }
40
+
41
+ const artifactsWith = (reactors: Function[]): IClientArtifactsProvider => ({
42
+ eventTypes: [SomethingHappenedBeforeRegistration],
43
+ readModels: [],
44
+ reactors,
45
+ reducers: [],
46
+ seeders: [],
47
+ constraints: [],
48
+ projections: [],
49
+ webhooks: [],
50
+ eventTypeMigrations: [],
51
+ globalForHandlers: []
52
+ });
53
+
54
+ async function eventually(accept: () => boolean, timeoutMs = 30_000): Promise<void> {
55
+ const deadline = Date.now() + timeoutMs;
56
+ while (!accept()) {
57
+ if (Date.now() > deadline) throw new Error('Timed out waiting for the kernel');
58
+ await new Promise(resolve => setTimeout(resolve, 100));
59
+ }
60
+ }
61
+
62
+ describe.skipIf(!connectionString && !process.env.CI)('when registering a reactor marked to start at the tail against a kernel', () => {
63
+ const storeName = `StartAtTail${randomUUID().replaceAll('-', '').slice(0, 12)}`;
64
+ const clients: ChronicleClient[] = [];
65
+
66
+ const newClient = (reactors: Function[]) => {
67
+ const client = new ChronicleClient(ChronicleOptions.fromConnectionString(connectionString!, {
68
+ discoveryPatterns: [],
69
+ clientArtifactsProvider: artifactsWith(reactors)
70
+ }));
71
+ clients.push(client);
72
+ return client;
73
+ };
74
+
75
+ beforeAll(async () => {
76
+ // History exists before either reactor has ever been registered.
77
+ const writer = await newClient([]).getEventStore(storeName);
78
+ for (const name of ['one', 'two', 'three']) {
79
+ const appended = await writer.eventLog.append(randomUUID(), Object.assign(new SomethingHappenedBeforeRegistration(), { name }));
80
+ appended.isSuccess.should.be.true;
81
+ }
82
+
83
+ const reader = await newClient([TailReactor, HistoryReactor]).getEventStore(storeName);
84
+
85
+ // The control proves the history was deliverable, so the tail reactor's silence is not vacuous.
86
+ await eventually(() => fromTheBeginning.length === 3);
87
+
88
+ const appended = await reader.eventLog.append(randomUUID(), Object.assign(new SomethingHappenedBeforeRegistration(), { name: 'after' }));
89
+ appended.isSuccess.should.be.true;
90
+ await eventually(() => fromTheTail.length === 1 && fromTheBeginning.length === 4);
91
+ });
92
+
93
+ afterAll(() => clients.forEach(client => client.dispose()));
94
+
95
+ it('should not deliver history that predates its registration', () => {
96
+ fromTheTail.should.not.include.members(['one', 'two', 'three']);
97
+ });
98
+
99
+ it('should deliver what is appended afterwards', () => {
100
+ fromTheTail.should.deep.equal(['after']);
101
+ });
102
+
103
+ it('should leave a reactor that is not marked to catch up on all history', () => {
104
+ // Each event has its own event source, so the kernel may deliver the partitions in any order.
105
+ [...fromTheBeginning].sort().should.deep.equal(['after', 'one', 'three', 'two']);
106
+ });
107
+ });