@cratis/chronicle 6.71.1 → 6.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/reactors/AsyncQueue.d.ts +10 -0
  2. package/dist/reactors/AsyncQueue.d.ts.map +1 -0
  3. package/dist/reactors/AsyncQueue.js +42 -0
  4. package/dist/reactors/AsyncQueue.js.map +1 -0
  5. package/dist/reactors/IReactorBuilder.d.ts +12 -0
  6. package/dist/reactors/IReactorBuilder.d.ts.map +1 -0
  7. package/dist/reactors/IReactorBuilder.js +4 -0
  8. package/dist/reactors/IReactorBuilder.js.map +1 -0
  9. package/dist/reactors/IReactorDefinition.d.ts +14 -0
  10. package/dist/reactors/IReactorDefinition.d.ts.map +1 -0
  11. package/dist/reactors/IReactorDefinition.js +4 -0
  12. package/dist/reactors/IReactorDefinition.js.map +1 -0
  13. package/dist/reactors/IReactorDefinitionBuilder.d.ts +9 -0
  14. package/dist/reactors/IReactorDefinitionBuilder.d.ts.map +1 -0
  15. package/dist/reactors/IReactorDefinitionBuilder.js +4 -0
  16. package/dist/reactors/IReactorDefinitionBuilder.js.map +1 -0
  17. package/dist/reactors/IReactors.d.ts +21 -10
  18. package/dist/reactors/IReactors.d.ts.map +1 -1
  19. package/dist/reactors/ReactorBuilder.d.ts +32 -0
  20. package/dist/reactors/ReactorBuilder.d.ts.map +1 -0
  21. package/dist/reactors/ReactorBuilder.js +91 -0
  22. package/dist/reactors/ReactorBuilder.js.map +1 -0
  23. package/dist/reactors/ReactorCallback.d.ts +4 -0
  24. package/dist/reactors/ReactorCallback.d.ts.map +1 -0
  25. package/dist/reactors/ReactorCallback.js +4 -0
  26. package/dist/reactors/ReactorCallback.js.map +1 -0
  27. package/dist/reactors/ReactorEvent.d.ts +7 -0
  28. package/dist/reactors/ReactorEvent.d.ts.map +1 -0
  29. package/dist/reactors/ReactorEvent.js +4 -0
  30. package/dist/reactors/ReactorEvent.js.map +1 -0
  31. package/dist/reactors/ReactorObservation.d.ts +21 -0
  32. package/dist/reactors/ReactorObservation.d.ts.map +1 -0
  33. package/dist/reactors/ReactorObservation.js +43 -0
  34. package/dist/reactors/ReactorObservation.js.map +1 -0
  35. package/dist/reactors/ReactorObservationTarget.d.ts +4 -1
  36. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -1
  37. package/dist/reactors/ReactorPageDispatcher.d.ts +6 -0
  38. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -1
  39. package/dist/reactors/ReactorPageDispatcher.js +96 -51
  40. package/dist/reactors/ReactorPageDispatcher.js.map +1 -1
  41. package/dist/reactors/ReactorRegistration.d.ts +14 -0
  42. package/dist/reactors/ReactorRegistration.d.ts.map +1 -0
  43. package/dist/reactors/ReactorRegistration.js +4 -0
  44. package/dist/reactors/ReactorRegistration.js.map +1 -0
  45. package/dist/reactors/ReactorRegistrationKind.d.ts +7 -0
  46. package/dist/reactors/ReactorRegistrationKind.d.ts.map +1 -0
  47. package/dist/reactors/ReactorRegistrationKind.js +10 -0
  48. package/dist/reactors/ReactorRegistrationKind.js.map +1 -0
  49. package/dist/reactors/ReactorRegistrations.d.ts +17 -0
  50. package/dist/reactors/ReactorRegistrations.d.ts.map +1 -0
  51. package/dist/reactors/ReactorRegistrations.js +42 -0
  52. package/dist/reactors/ReactorRegistrations.js.map +1 -0
  53. package/dist/reactors/ReactorSubscription.d.ts +4 -0
  54. package/dist/reactors/ReactorSubscription.d.ts.map +1 -0
  55. package/dist/reactors/ReactorSubscription.js +4 -0
  56. package/dist/reactors/ReactorSubscription.js.map +1 -0
  57. package/dist/reactors/Reactors.d.ts +31 -38
  58. package/dist/reactors/Reactors.d.ts.map +1 -1
  59. package/dist/reactors/Reactors.js +143 -274
  60. package/dist/reactors/Reactors.js.map +1 -1
  61. package/dist/reactors/WaitTillSubscribedOptions.d.ts +7 -0
  62. package/dist/reactors/WaitTillSubscribedOptions.d.ts.map +1 -0
  63. package/dist/reactors/WaitTillSubscribedOptions.js +4 -0
  64. package/dist/reactors/WaitTillSubscribedOptions.js.map +1 -0
  65. package/dist/reactors/index.d.ts +5 -0
  66. package/dist/reactors/index.d.ts.map +1 -1
  67. package/dist/reactors/index.js.map +1 -1
  68. package/dist/reactors/prepareReactor.d.ts +34 -0
  69. package/dist/reactors/prepareReactor.d.ts.map +1 -0
  70. package/dist/reactors/prepareReactor.js +75 -0
  71. package/dist/reactors/prepareReactor.js.map +1 -0
  72. package/dist/reactors/waitTillSubscribed.d.ts +5 -0
  73. package/dist/reactors/waitTillSubscribed.d.ts.map +1 -0
  74. package/dist/reactors/waitTillSubscribed.js +29 -0
  75. package/dist/reactors/waitTillSubscribed.js.map +1 -0
  76. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.d.ts +142 -0
  77. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.d.ts.map +1 -0
  78. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.js +142 -0
  79. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.js.map +1 -0
  80. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.d.ts +24 -0
  81. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.d.ts.map +1 -0
  82. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.js +34 -0
  83. package/dist/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.js.map +1 -0
  84. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.d.ts +17 -0
  85. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.d.ts.map +1 -0
  86. package/dist/testing/projections/{ProjectionCountChildrenCapabilities.js → ProjectionArithmeticChildrenCapabilities.js} +24 -12
  87. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js.map +1 -0
  88. package/dist/testing/projections/ProjectionRootCapabilities.js +4 -4
  89. package/dist/testing/projections/ProjectionRootCapabilities.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +2 -2
  92. package/reactors/AsyncQueue.ts +41 -0
  93. package/reactors/IReactorBuilder.ts +15 -0
  94. package/reactors/IReactorDefinition.ts +17 -0
  95. package/reactors/IReactorDefinitionBuilder.ts +12 -0
  96. package/reactors/IReactors.ts +25 -10
  97. package/reactors/ReactorBuilder.ts +98 -0
  98. package/reactors/ReactorCallback.ts +7 -0
  99. package/reactors/ReactorEvent.ts +10 -0
  100. package/reactors/ReactorObservation.ts +45 -0
  101. package/reactors/ReactorObservationTarget.ts +4 -1
  102. package/reactors/ReactorPageDispatcher.ts +98 -54
  103. package/reactors/ReactorRegistration.ts +11 -0
  104. package/reactors/ReactorRegistrationKind.ts +9 -0
  105. package/reactors/ReactorRegistrations.ts +45 -0
  106. package/reactors/ReactorSubscription.ts +7 -0
  107. package/reactors/Reactors.ts +156 -310
  108. package/reactors/WaitTillSubscribedOptions.ts +9 -0
  109. package/reactors/for_Reactors/given/runtime_reactors.fixture.ts +50 -0
  110. package/reactors/for_Reactors/when_a_class_reactor_fails_to_restart.spec.ts +67 -0
  111. package/reactors/for_Reactors/when_a_class_reactor_fails_to_start.spec.ts +80 -0
  112. package/reactors/for_Reactors/when_class_delivery_is_unregistered.spec.ts +62 -0
  113. package/reactors/for_Reactors/when_defining_runtime_reactors.spec.ts +77 -0
  114. package/reactors/for_Reactors/when_dispatching_runtime_reactors.spec.ts +94 -0
  115. package/reactors/for_Reactors/when_registering_runtime_reactors.spec.ts +102 -0
  116. package/reactors/for_Reactors/when_stopping_runtime_reactors.spec.ts +160 -0
  117. package/reactors/for_Reactors/when_using_the_default_artifacts_provider.spec.ts +80 -0
  118. package/reactors/for_Reactors/when_waiting_till_subscribed.spec.ts +65 -0
  119. package/reactors/index.ts +5 -0
  120. package/reactors/prepareReactor.ts +79 -0
  121. package/reactors/waitTillSubscribed.ts +29 -0
  122. package/testing/for_ReadModelScenario/when_adding_with_children/given/compiled_projection.ts +71 -0
  123. package/testing/for_ReadModelScenario/when_adding_with_children/given/lifecycle.ts +38 -0
  124. package/testing/for_ReadModelScenario/when_adding_with_children/with_a_fluent_projection.spec.ts +64 -0
  125. package/testing/for_ReadModelScenario/when_adding_with_children/with_legacy_decorators.legacy.spec.ts +41 -0
  126. package/testing/for_ReadModelScenario/when_adding_with_children/with_standard_decorators.standard.spec.ts +42 -0
  127. package/testing/projections/{ProjectionCountChildrenCapabilities.ts → ProjectionArithmeticChildrenCapabilities.ts} +22 -11
  128. package/testing/projections/ProjectionRootCapabilities.ts +4 -4
  129. package/testing/projections/for_ProjectionCapabilities/when_validating_add_with_children.spec.ts +91 -0
  130. package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +12 -2
  131. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts +0 -15
  132. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts.map +0 -1
  133. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js.map +0 -1
@@ -4,133 +4,54 @@
4
4
  import 'reflect-metadata';
5
5
  import { createLogger } from '../logging/createLogger.js';
6
6
  import { runInBackgroundContext } from '../telemetry/runInBackgroundContext.js';
7
- import { Constructor } from '@cratis/fundamentals';
8
- import { EventGenerationDelivery, ReactorMessage } from '@cratis/chronicle.contracts';
9
- import type { EventsToObserve } from '@cratis/chronicle.contracts';
10
- import { IClientArtifactsProvider } from '../artifacts/index.js';
11
- import { ChronicleConnection } from '../connection/index.js';
7
+ import type { IClientArtifactsProvider } from '../artifacts/index.js';
8
+ import type { ChronicleConnection } from '../connection/index.js';
12
9
  import { ConnectionLifecycle } from '../connection/ConnectionLifecycle.js';
13
- import { getTagsFor } from '../events/tagDecorator.js';
14
- import { getFilterTagsFor } from '../events/filterEventsByTagDecorator.js';
15
- import { getEventSourceTypeFor } from '../events/eventSourceTypeDecorator.js';
16
- import { getEventStreamTypeFor } from '../events/eventStreamTypeDecorator.js';
17
10
  import { EventSequenceId } from '../eventSequences/EventSequenceId.js';
18
11
  import type { IEventLog } from '../eventSequences/IEventLog.js';
19
- import { createHandlerInstanceValidator } from '../observation/createHandlerInstanceValidator.js';
20
- import { IReactors } from './IReactors.js';
21
- import { getReactorMetadata } from './reactor.js';
22
- import { isOnceOnly } from './onceOnly.js';
23
- import { isStartAtTail } from './startAtTail.js';
24
- import { getReactorBatchMethods, getReactorEventTypes } from './ReactorDispatcher.js';
25
- import { ReactorPageDispatcher } from './ReactorPageDispatcher.js';
26
- import { toPageDelivery } from '../observation/batches/batchSize.js';
27
- import type { ReactorEventTypeEntry } from './ReactorDispatcher.js';
28
- import type { ReactorResultHandler } from './ReactorResultHandler.js';
29
- import type { ReactorServices } from './ReactorServices.js';
30
12
  import type { IEventStore } from '../IEventStore.js';
31
13
  import type { ClientArtifactsActivator } from '../artifacts/ClientArtifactsActivator.js';
32
14
  import { refuseClientHostedObservers } from '../artifacts/refuseClientHostedObservers.js';
33
15
  import { ObservationReconnectBackoff, type ObservationReconnectBackoffOptions } from '../observation/ObservationReconnectBackoff.js';
34
16
  import { classifyStreamError, StreamErrorKind } from '../observation/classifyStreamError.js';
35
17
  import type { ObservationStreamOutcome } from '../observation/ObservationStreamOutcome.js';
18
+ import type { IReactors } from './IReactors.js';
19
+ import type { IReactorBuilder } from './IReactorBuilder.js';
20
+ import type { IReactorDefinitionBuilder } from './IReactorDefinitionBuilder.js';
21
+ import type { IReactorDefinition } from './IReactorDefinition.js';
22
+ import type { ReactorId } from './ReactorId.js';
23
+ import type { ReactorResultHandler } from './ReactorResultHandler.js';
24
+ import type { ReactorServices } from './ReactorServices.js';
25
+ import type { ReactorRegistration } from './ReactorRegistration.js';
26
+ import { ReactorRegistrationKind } from './ReactorRegistrationKind.js';
27
+ import { ReactorRegistrations } from './ReactorRegistrations.js';
28
+ import { ReactorBuilder } from './ReactorBuilder.js';
29
+ import { ReactorObservation } from './ReactorObservation.js';
30
+ import { ReactorPageDispatcher } from './ReactorPageDispatcher.js';
31
+ import { prepareReactor, reactorSubscriptionMessage } from './prepareReactor.js';
32
+ import type { ReactorSubscription } from './ReactorSubscription.js';
33
+ import type { WaitTillSubscribedOptions } from './WaitTillSubscribedOptions.js';
34
+ import { waitTillSubscribed } from './waitTillSubscribed.js';
36
35
 
37
- /** Expression used to partition reactor observations by event source ID. */
38
- const EVENT_SOURCE_ID_KEY = '$eventSourceId';
39
-
40
- /**
41
- * A push-based async queue that implements {@link AsyncIterable} for use with nice-grpc
42
- * bidirectional streaming. Values pushed via {@link send} are yielded in order to
43
- * any consumer that iterates the queue.
44
- */
45
- class AsyncQueue<T> {
46
- private readonly _queue: T[] = [];
47
- private _resolve: ((result: IteratorResult<T, undefined>) => void) | undefined = undefined;
48
- private _done = false;
49
-
50
- /** Pushes a value into the queue. No-op if the queue has been completed. */
51
- send(value: T): void {
52
- if (this._done) return;
53
- if (this._resolve) {
54
- const resolve = this._resolve;
55
- this._resolve = undefined;
56
- resolve({ value, done: false });
57
- } else {
58
- this._queue.push(value);
59
- }
60
- }
61
-
62
- /** Signals that no more values will be pushed, causing consumers to finish iteration. */
63
- complete(): void {
64
- this._done = true;
65
- if (this._resolve) {
66
- this._resolve({ value: undefined, done: true });
67
- this._resolve = undefined;
68
- }
69
- }
70
-
71
- [Symbol.asyncIterator](): AsyncIterator<T, undefined> {
72
- // eslint-disable-next-line @typescript-eslint/no-this-alias
73
- const self = this;
74
- return {
75
- next(): Promise<IteratorResult<T, undefined>> {
76
- if (self._queue.length > 0) {
77
- return Promise.resolve({ value: self._queue.shift()!, done: false });
78
- }
79
- if (self._done) {
80
- return Promise.resolve({ value: undefined, done: true });
81
- }
82
- return new Promise(resolve => {
83
- self._resolve = resolve as (result: IteratorResult<T, undefined>) => void;
84
- });
85
- },
86
- return(): Promise<IteratorResult<T, undefined>> {
87
- self._done = true;
88
- if (self._resolve) {
89
- self._resolve({ value: undefined, done: true });
90
- self._resolve = undefined;
91
- }
92
- return Promise.resolve({ value: undefined, done: true });
93
- }
94
- };
95
- }
96
- }
97
-
98
- /**
99
- * Implements {@link IReactors}, managing discovery and registration of reactors
100
- * with the Chronicle Kernel via bidirectional gRPC streaming.
101
- */
36
+ /** Manages discovered and runtime reactors using local-start/local-stop completion semantics. */
102
37
  export class Reactors implements IReactors {
103
38
  private readonly _logger: ReturnType<typeof createLogger>;
104
- private readonly _lifecycle: ConnectionLifecycle;
105
39
  private readonly _unsubscribeDisconnected: () => void;
106
- private readonly _reactors = new Map<string, Constructor>();
107
- private readonly _queues = new Map<string, AsyncQueue<ReactorMessage>>();
108
- private readonly _observations = new Map<string, AbortController>();
40
+ private readonly _registrations = new ReactorRegistrations();
41
+ private readonly _observations = new Map<string, ReactorObservation>();
109
42
  private readonly _reconnectBackoffs = new Map<string, ObservationReconnectBackoff>();
110
43
  private readonly _reobserveTimers = new Map<string, ReturnType<typeof setTimeout>>();
44
+ private readonly _lifetime = new AbortController();
111
45
  private _registered = false;
112
46
  private _disposed = false;
113
47
 
114
- /**
115
- * Creates a new {@link Reactors} instance.
116
- * @param _clientArtifacts - Provider for discovered client artifact types.
117
- * @param _connection - The Chronicle gRPC connection.
118
- * @param _eventStoreName - The name of the event store.
119
- * @param _namespace - The namespace within the event store.
120
- * @param lifecycle - The connection lifecycle used to react to disconnect events.
121
- * @param _eventLog - The event log used to append side-effect events a reactor handler returns.
122
- * @param _resultHandler - Optional handler for values a reactor handler returns.
123
- * @param _eventStore - Optional event store handed to reactor handlers.
124
- * @param _artifactActivator - Optional activator creating reactor instances.
125
- * @param _skipKeepAlive - Whether the client runs without a keep-alive, which refuses client-hosted reactors.
126
- * @param _reconnectBackoff - How a reactor waits before opening its observation stream again after it ended.
127
- */
48
+ /** Creates the reactor collection for one event store and namespace. */
128
49
  constructor(
129
50
  private readonly _clientArtifacts: IClientArtifactsProvider,
130
51
  private readonly _connection: ChronicleConnection,
131
52
  private readonly _eventStoreName: string,
132
53
  private readonly _namespace: string,
133
- lifecycle: ConnectionLifecycle,
54
+ private readonly _lifecycle: ConnectionLifecycle,
134
55
  private readonly _eventLog: IEventLog,
135
56
  private readonly _resultHandler?: ReactorResultHandler,
136
57
  private readonly _eventStore?: IEventStore,
@@ -139,95 +60,157 @@ export class Reactors implements IReactors {
139
60
  private readonly _reconnectBackoff: ObservationReconnectBackoffOptions = {}
140
61
  ) {
141
62
  this._logger = createLogger('@cratis/chronicle/reactors', _connection.logger);
142
- this._lifecycle = lifecycle;
143
- this._unsubscribeDisconnected = lifecycle.onDisconnected(async () => {
63
+ this._unsubscribeDisconnected = _lifecycle.onDisconnected(async () => {
144
64
  this._logger.info('Disconnected — stopping all reactor observations');
145
65
  this._registered = false;
146
66
  this.disconnectAll();
147
67
  });
148
68
  }
149
69
 
150
- /** Stops observations permanently when the owning client is disposed. */
70
+ /** Stops local observations permanently, without waiting for running user callbacks. */
151
71
  dispose(): void {
152
72
  this._unsubscribeDisconnected();
153
73
  this._disposed = true;
154
74
  this._registered = false;
75
+ this._lifetime.abort(new Error('Reactors have been disposed.'));
155
76
  this.disconnectAll();
156
77
  this._reconnectBackoffs.clear();
157
78
  }
158
79
 
159
80
  /** @inheritdoc */
160
81
  async discover(): Promise<void> {
161
- this._reactors.clear();
162
- for (const type of this._clientArtifacts.reactors) {
163
- const metadata = getReactorMetadata(type);
164
- if (metadata) {
165
- this._reactors.set(metadata.id.value, type);
166
- this._logger.debug('Discovered reactor', { reactorId: metadata.id.value, type: (type as Function).name });
167
- }
168
- }
82
+ this._registrations.discover(this._clientArtifacts.reactors);
169
83
  }
170
84
 
171
85
  /** @inheritdoc */
172
- async register(): Promise<void> {
173
- if (this._skipKeepAlive) refuseClientHostedObservers({ reactors: this._clientArtifacts.reactors, reducers: [] });
174
- if (this._registered || this._disposed) {
86
+ define(id: ReactorId | string, define: (builder: IReactorBuilder) => void): IReactorDefinition {
87
+ const builder = new ReactorBuilder(id, this._clientArtifacts.eventTypes);
88
+ define(builder);
89
+ return builder.build();
90
+ }
91
+
92
+ /** @inheritdoc */
93
+ register(): Promise<void>;
94
+ register(definition: IReactorDefinition): Promise<void>;
95
+ register(id: ReactorId | string, define: (builder: IReactorBuilder) => void): Promise<void>;
96
+ register(id: ReactorId | string, configure: (builder: IReactorDefinitionBuilder) => void, handle: IReactorDefinition['handle']): Promise<void>;
97
+ async register(idOrDefinition?: ReactorId | string | IReactorDefinition,
98
+ configure?: (builder: ReactorBuilder) => void, handle?: IReactorDefinition['handle']): Promise<void> {
99
+ if (idOrDefinition !== undefined) {
100
+ this.registerRuntime(idOrDefinition, configure, handle);
175
101
  return;
176
102
  }
177
-
178
- if (this._reactors.size === 0) {
179
- await this.discover();
103
+ if (this._skipKeepAlive) refuseClientHostedObservers({ reactors: this._clientArtifacts.reactors, reducers: [] });
104
+ if (this._disposed) return;
105
+ this._registrations.discover(this._clientArtifacts.reactors);
106
+ const registrations = this._registrations.all.map(registration => ({
107
+ registration, subscription: prepareReactor(registration, this._clientArtifacts)
108
+ }));
109
+ this._registered = true;
110
+ for (const { registration, subscription } of registrations) {
111
+ if (!this.hasObservation(registration.id)) this.startObservation(registration, subscription);
180
112
  }
113
+ }
181
114
 
182
- if (this._disposed) return;
183
- const registrations = [...this._reactors].map(([id, type]) => ({
184
- id, type, eventTypes: getReactorEventTypes(type, this._clientArtifacts.eventTypes),
185
- batchMethods: getReactorBatchMethods(type, this._clientArtifacts.eventTypes)
186
- })).map(registration => ({ ...registration, validateInstance: createHandlerInstanceValidator(registration.type, [
187
- ...registration.eventTypes.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)),
188
- ...registration.batchMethods.map(method => method.methodName)
189
- ]) }));
190
- this._logger.info('Registering reactors', { count: this._reactors.size });
191
- for (const { id, type, eventTypes, validateInstance } of registrations) {
192
- this.startObservation(id, type, eventTypes, validateInstance);
115
+ /** @inheritdoc */
116
+ async unregister(id: ReactorId | string): Promise<void> {
117
+ const value = typeof id === 'string' ? id : id.value;
118
+ this._registrations.remove(value);
119
+ clearTimeout(this._reobserveTimers.get(value));
120
+ this._reobserveTimers.delete(value);
121
+ const attempt = this._observations.get(value);
122
+ this._observations.delete(value);
123
+ attempt?.stop();
124
+ this._reconnectBackoffs.delete(value);
125
+ }
126
+
127
+ /** @inheritdoc */
128
+ async waitTillSubscribed(id: ReactorId | string, options: WaitTillSubscribedOptions = {}): Promise<void> {
129
+ const value = typeof id === 'string' ? id : id.value;
130
+ const registration = this._registrations.all.find(entry => entry.id === value);
131
+ const eventSequenceId = registration ? prepareReactor(registration, this._clientArtifacts).eventSequenceId : EventSequenceId.eventLog.value;
132
+ await waitTillSubscribed(signal => this._connection.observers.getObserverInformation({
133
+ EventStore: this._eventStoreName, Namespace: this._namespace, ObserverId: value, EventSequenceId: eventSequenceId
134
+ }, { signal }), options, this._lifetime.signal);
135
+ }
136
+
137
+ private registerRuntime(idOrDefinition: ReactorId | string | IReactorDefinition,
138
+ configure: ((builder: ReactorBuilder) => void) | undefined, handle: IReactorDefinition['handle'] | undefined): void {
139
+ if (this._disposed) throw new Error('Reactors have been disposed.');
140
+ if (this._skipKeepAlive) throw new Error('Client-hosted reactors require keep-alive.');
141
+ const definition = this.runtimeDefinition(idOrDefinition, configure, handle);
142
+ this._registrations.discover(this._clientArtifacts.reactors);
143
+ const registration: ReactorRegistration = { id: definition.id.value, kind: handle ? ReactorRegistrationKind.Delegate : ReactorRegistrationKind.Fluent, definition };
144
+ const subscription = prepareReactor(registration, this._clientArtifacts);
145
+ this._registrations.add(registration);
146
+ try {
147
+ this._registered = true;
148
+ this.startObservation(registration, subscription);
149
+ } catch (error) {
150
+ this._registrations.remove(registration.id);
151
+ throw error;
193
152
  }
153
+ }
194
154
 
195
- this._registered = true;
155
+ private runtimeDefinition(idOrDefinition: ReactorId | string | IReactorDefinition,
156
+ configure: ((builder: ReactorBuilder) => void) | undefined, handle: IReactorDefinition['handle'] | undefined): IReactorDefinition {
157
+ if (typeof idOrDefinition === 'object' && 'handle' in idOrDefinition) return idOrDefinition;
158
+ const builder = new ReactorBuilder(idOrDefinition, this._clientArtifacts.eventTypes);
159
+ configure?.(builder);
160
+ return builder.build(handle);
196
161
  }
197
162
 
198
- private startObservation(id: string, reactorType: Constructor,
199
- eventTypes: ReactorEventTypeEntry[], validateInstance: (instance: object) => void): void {
200
- runInBackgroundContext(() => {
201
- if (this._disposed) return;
202
- const metadata = getReactorMetadata(reactorType)!;
203
- const eventSequenceId = metadata.eventSequenceId ?? EventSequenceId.eventLog.value;
163
+ private hasObservation(id: string): boolean {
164
+ return this._observations.has(id) || this._reobserveTimers.has(id);
165
+ }
204
166
 
205
- this._logger.info('Starting reactor observation', {
206
- reactorId: id,
207
- eventSequenceId,
208
- handlerCount: eventTypes.length,
209
- handlers: eventTypes.map(e => e.methodName)
210
- });
167
+ private startObservation(registration: ReactorRegistration, subscription: ReactorSubscription): void {
168
+ const attempt = new ReactorObservation(registration, this._lifecycle.connectionId);
169
+ this._observations.set(registration.id, attempt);
170
+ runInBackgroundContext(() => { void this.runObservation(attempt, subscription); });
171
+ }
211
172
 
212
- void this.runObservation(id, reactorType, eventSequenceId, eventTypes, validateInstance);
173
+ private createDispatcher(subscription: ReactorSubscription, signal: AbortSignal): ReactorPageDispatcher {
174
+ const { reactorType: type } = subscription;
175
+ const reactorInstance = type && !this._artifactActivator ? new (type as new () => Record<string, Function>)() : undefined;
176
+ if (reactorInstance) subscription.validateInstance(reactorInstance);
177
+ const services: ReactorServices | undefined = this._eventStore && {
178
+ eventStore: this._eventStore, readModels: this._eventStore.readModels, signal
179
+ };
180
+ return new ReactorPageDispatcher({
181
+ ...subscription, reactorInstance, services, signal,
182
+ eventStoreName: this._eventStoreName, namespace: this._namespace,
183
+ eventLog: this._eventLog, resultHandler: this._resultHandler,
184
+ artifactActivator: type ? this._artifactActivator : undefined,
185
+ logger: this._logger, connectionLogger: this._connection.logger
213
186
  });
214
187
  }
215
188
 
216
- private async runObservation(
217
- id: string,
218
- reactorType: Constructor,
219
- eventSequenceId: string,
220
- eventTypes: ReactorEventTypeEntry[],
221
- validateInstance: (instance: object) => void
222
- ): Promise<void> {
189
+ private async runObservation(attempt: ReactorObservation, subscription: ReactorSubscription): Promise<void> {
190
+ const id = attempt.registration.id;
223
191
  let outcome: ObservationStreamOutcome = 'ended';
224
192
  try {
225
- outcome = await this.observeReactor(id, reactorType, eventSequenceId, eventTypes, validateInstance);
193
+ this.reconnectBackoffFor(id).streamOpened();
194
+ const dispatcher = this.createDispatcher(subscription, attempt.controller.signal);
195
+ attempt.queue.send(reactorSubscriptionMessage(subscription, {
196
+ connectionId: attempt.connectionId, eventStore: this._eventStoreName, namespace: this._namespace
197
+ }));
198
+ outcome = await attempt.observe(this._connection.reactors.observe(attempt.queue, { signal: attempt.controller.signal }), dispatcher, {
199
+ delivered: () => this.reconnectBackoffFor(id).streamDelivered(),
200
+ failed: error => this.streamFailed(attempt, error)
201
+ });
226
202
  } catch (error) {
227
- this._logger.error('Reactor observation loop exited with error', { reactorId: id, error });
203
+ if (this.isCurrent(attempt)) this._logger.error('Reactor observation failed while handling a delivery', { reactorId: id, error });
204
+ } finally {
205
+ attempt.stop();
228
206
  }
207
+ if (!this.isCurrent(attempt)) return;
208
+ this._observations.delete(id);
209
+ if (outcome === 'ended') this.scheduleReobserve(attempt.registration, subscription);
210
+ }
229
211
 
230
- if (outcome === 'ended') this.scheduleReobserve(id, reactorType, eventTypes, validateInstance);
212
+ private isCurrent(attempt: ReactorObservation): boolean {
213
+ return this._observations.get(attempt.registration.id) === attempt;
231
214
  }
232
215
 
233
216
  private reconnectBackoffFor(id: string): ObservationReconnectBackoff {
@@ -239,180 +222,43 @@ export class Reactors implements IReactors {
239
222
  return backoff;
240
223
  }
241
224
 
242
- /**
243
- * Re-establishes an observation whose stream ended.
244
- *
245
- * The stream ending without an error is not proof that all is well — the kernel
246
- * closes a cross-store (inbox) reactor's stream rather than tailing it forever,
247
- * so a reactor that does not re-subscribe there silently stops observing until
248
- * the whole client reconnects. Both endings are therefore retried. The delay keeps
249
- * a stream that keeps ending from becoming a hot loop, and grows with jitter while
250
- * it does (see {@link ObservationReconnectBackoff}).
251
- */
252
- private scheduleReobserve(id: string, reactorType: Constructor, eventTypes: ReactorEventTypeEntry[], validateInstance: (instance: object) => void): void {
253
- // A disconnect clears the registration; the reconnect re-registers every
254
- // reactor from scratch, so retrying here as well would double up.
255
- if (!this._registered || this._disposed) {
256
- return;
257
- }
225
+ private canObserve(registration: ReactorRegistration): boolean {
226
+ return this._registered && !this._disposed && this._registrations.isCurrent(registration);
227
+ }
258
228
 
259
- clearTimeout(this._reobserveTimers.get(id));
229
+ private scheduleReobserve(registration: ReactorRegistration, subscription: ReactorSubscription): void {
230
+ if (!this.canObserve(registration)) return;
231
+ const id = registration.id;
260
232
  const delayMs = this.reconnectBackoffFor(id).nextDelayMs();
261
233
  this._logger.debug('Waiting before re-establishing reactor observation', { reactorId: id, delayMs });
262
234
  const handle = runInBackgroundContext(() => setTimeout(() => {
263
235
  this._reobserveTimers.delete(id);
264
- // A reconnect in the meantime has already opened a new stream; opening another would leave one untracked.
265
- if (!this._registered || this._disposed || this._observations.has(id)) {
266
- return;
267
- }
268
-
269
- this._logger.info('Re-establishing reactor observation', { reactorId: id });
270
- this.startObservation(id, reactorType, eventTypes, validateInstance);
236
+ if (!this.canObserve(registration) || this._observations.has(id)) return;
237
+ this.startObservation(registration, subscription);
271
238
  }, delayMs));
272
-
273
239
  handle.unref?.();
274
240
  this._reobserveTimers.set(id, handle);
275
241
  }
276
242
 
277
- private async observeReactor(
278
- id: string,
279
- reactorType: Constructor,
280
- eventSequenceId: string,
281
- eventTypes: ReactorEventTypeEntry[],
282
- validateInstance: (instance: object) => void
283
- ): Promise<ObservationStreamOutcome> {
284
- const batchMethods = getReactorBatchMethods(reactorType, this._clientArtifacts.eventTypes);
285
- const queue = new AsyncQueue<ReactorMessage>();
286
- const controller = new AbortController();
287
- this._queues.set(id, queue);
288
- this._observations.set(id, controller);
289
- const connectionId = this._lifecycle.connectionId;
290
- const backoff = this.reconnectBackoffFor(id);
291
- backoff.streamOpened();
292
-
293
- queue.send({
294
- Content: {
295
- Value0: {
296
- ConnectionId: connectionId,
297
- EventStore: this._eventStoreName,
298
- Namespace: this._namespace,
299
- Reactor: {
300
- ReactorId: id,
301
- EventSequenceId: eventSequenceId,
302
- EventTypes: [...eventTypes, ...batchMethods.flatMap(method => [...method.eventTypes.values()])].map(et => ({
303
- EventType: { Id: et.id, Generation: et.generation, Tombstone: false },
304
- Key: EVENT_SOURCE_ID_KEY
305
- })),
306
- IsReplayable: !isOnceOnly(reactorType),
307
- IsNotReplayable: isOnceOnly(reactorType),
308
- StartAtTail: isStartAtTail(reactorType),
309
- GenerationDelivery: EventGenerationDelivery.Compatibility,
310
- Tags: getTagsFor(reactorType).map(t => t.value),
311
- Filters: {
312
- FilterTags: getFilterTagsFor(reactorType).map(t => t.value),
313
- EventSourceType: getEventSourceTypeFor(reactorType),
314
- EventStreamType: getEventStreamTypeFor(reactorType)
315
- }
316
- },
317
- PageDelivery: toPageDelivery(reactorType)
318
- },
319
- Value1: undefined
320
- }
321
- });
322
-
323
- let iterator: AsyncIterator<EventsToObserve> | undefined;
324
- let streamFinished = false;
325
- try {
326
- const reactorInstance = this._artifactActivator ? undefined : new (reactorType as new () => Record<string, Function>)();
327
- if (reactorInstance) validateInstance(reactorInstance);
328
- const services: ReactorServices | undefined = this._eventStore && {
329
- eventStore: this._eventStore, readModels: this._eventStore.readModels, signal: controller.signal
330
- };
331
-
332
- const dispatcher = new ReactorPageDispatcher({
333
- id, reactorType, eventSequenceId, eventStoreName: this._eventStoreName, namespace: this._namespace,
334
- entries: eventTypes, batchMethods, validateInstance, reactorInstance, services, signal: controller.signal,
335
- eventLog: this._eventLog, resultHandler: this._resultHandler, artifactActivator: this._artifactActivator,
336
- logger: this._logger, connectionLogger: this._connection.logger
337
- });
338
-
339
- // Pull each message by hand so only a failure of the stream itself is classified: an error from a
340
- // handler is the handler's failure, and must never make the whole client reconnect.
341
- iterator = this._connection.reactors.observe(queue, { signal: controller.signal })[Symbol.asyncIterator]();
342
- for (;;) {
343
- let next: IteratorResult<EventsToObserve>;
344
- try {
345
- next = await iterator.next();
346
- } catch (streamError) {
347
- streamFinished = true;
348
- return this.streamFailed(id, queue, controller.signal, connectionId, streamError);
349
- }
350
-
351
- if (next.done) {
352
- streamFinished = true;
353
- break;
354
- }
355
-
356
- backoff.streamDelivered();
357
- const result = await dispatcher.dispatch(next.value);
358
- queue.send({ Content: { Value0: undefined, Value1: result } });
359
- }
360
-
361
- if (this._queues.get(id) !== queue) {
362
- this._logger.debug('Reactor observation stream closed cleanly', { reactorId: id });
363
- return 'superseded';
364
- }
365
-
366
- return 'ended';
367
- } catch (handlerError) {
368
- if (this._queues.get(id) !== queue) return 'superseded';
369
- this._logger.error('Reactor observation failed while handling a delivery', { reactorId: id, error: handlerError });
370
- return 'ended';
371
- } finally {
372
- if (!streamFinished) {
373
- controller.abort();
374
- void iterator?.return?.()?.catch(() => undefined);
375
- }
376
-
377
- // Only retire our own queue: a reconnect can already have replaced it,
378
- // and deleting the new one would leave that observation untracked and
379
- // leak a duplicate stream on every reconnect.
380
- if (this._queues.get(id) === queue) {
381
- this._queues.delete(id);
382
- this._observations.delete(id);
383
- }
384
- queue.complete();
385
- }
386
- }
387
-
388
- private streamFailed(id: string, queue: AsyncQueue<ReactorMessage>, signal: AbortSignal, connectionId: string, error: unknown): ObservationStreamOutcome {
389
- // A late error from a stream that a disconnect, a dispose or a newer stream replaced says nothing about now.
390
- if (this._queues.get(id) !== queue) {
391
- this._logger.debug('Reactor observation stream closed cleanly', { reactorId: id });
392
- return 'superseded';
393
- }
394
-
243
+ private streamFailed(attempt: ReactorObservation, error: unknown): ObservationStreamOutcome {
244
+ if (!this.isCurrent(attempt)) return 'superseded';
395
245
  const kind = classifyStreamError(error);
396
- if (kind === StreamErrorKind.Cancelled && signal.aborted) return 'stopped';
246
+ if (kind === StreamErrorKind.Cancelled && attempt.controller.signal.aborted) return 'stopped';
397
247
  if (kind === StreamErrorKind.SessionLost) {
398
- // The kernel lost this client's registration. Opening the same stream with the same connection id
399
- // can never work, so reconnect the whole client, which re-registers every reactor.
400
- this._logger.warn('Reactor observation stream lost its session; reconnecting the client', { reactorId: id, error });
401
- this._lifecycle.requestReconnect(connectionId, 'reactor-session-lost', error,
402
- handlerError => this._logger.error('Reconnect request handler failed', { reactorId: id, error: handlerError }));
248
+ this._logger.warn('Reactor observation stream lost its session; reconnecting the client', { reactorId: attempt.registration.id, error });
249
+ this._lifecycle.requestReconnect(attempt.connectionId, 'reactor-session-lost', error,
250
+ handlerError => this._logger.error('Reconnect request handler failed', { reactorId: attempt.registration.id, error: handlerError }));
403
251
  return 'sessionLost';
404
252
  }
405
-
406
- this._logger.error('Reactor observation stream ended unexpectedly', { reactorId: id, error });
253
+ this._logger.error('Reactor observation stream ended unexpectedly', { reactorId: attempt.registration.id, error });
407
254
  return 'ended';
408
255
  }
409
256
 
410
257
  private disconnectAll(): void {
411
258
  for (const timer of this._reobserveTimers.values()) clearTimeout(timer);
412
259
  this._reobserveTimers.clear();
413
- for (const controller of this._observations.values()) controller.abort();
414
- for (const queue of this._queues.values()) queue.complete();
260
+ const attempts = [...this._observations.values()];
415
261
  this._observations.clear();
416
- this._queues.clear();
262
+ for (const attempt of attempts) attempt.stop();
417
263
  }
418
264
  }
@@ -0,0 +1,9 @@
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
+ /** Options for a per-observer readiness check, not a registration acknowledgment. */
5
+ export interface WaitTillSubscribedOptions {
6
+ /** Timeout in milliseconds, including RPCs. Defaults to 5000. */
7
+ readonly timeout?: number;
8
+ readonly signal?: AbortSignal;
9
+ }
@@ -0,0 +1,50 @@
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 { Constructor } from '@cratis/fundamentals';
6
+ import { EventsToObserve, ObserverInformation, type ReactorMessage } from '@cratis/chronicle.contracts';
7
+ import type { IClientArtifactsProvider } from '../../../artifacts/IClientArtifactsProvider.js';
8
+ import type { ChronicleConnection } from '../../../connection/ChronicleConnection.js';
9
+ import { ConnectionLifecycle } from '../../../connection/ConnectionLifecycle.js';
10
+ import type { IEventLog } from '../../../eventSequences/IEventLog.js';
11
+ import { eventType } from '../../../events/eventTypeDecorator.js';
12
+ import { AsyncQueue } from '../../AsyncQueue.js';
13
+ import { Reactors } from '../../Reactors.js';
14
+
15
+ @eventType('runtime-registered')
16
+ export class Registered { value = ''; }
17
+ @eventType('runtime-other')
18
+ export class Other {}
19
+
20
+ /** A controllable duplex stream, recording only messages actually sent by production code. */
21
+ export class runtime_reactors {
22
+ readonly lifecycle = new ConnectionLifecycle();
23
+ readonly types: Constructor[] = [Registered, Other];
24
+ readonly artifacts: Constructor[] = [];
25
+ readonly attempts: { incoming: AsyncQueue<EventsToObserve>; sent: ReactorMessage[]; signal: AbortSignal }[] = [];
26
+ readonly information = vi.fn(async () => ObserverInformation.fromPartial({ IsSubscribed: false }));
27
+ readonly observe = vi.fn((outgoing: AsyncIterable<ReactorMessage>, options: { signal: AbortSignal }) => {
28
+ const attempt = { incoming: new AsyncQueue<EventsToObserve>(), sent: [] as ReactorMessage[], signal: options.signal };
29
+ this.attempts.push(attempt);
30
+ options.signal.addEventListener('abort', () => attempt.incoming.complete(), { once: true });
31
+ return (async function* () {
32
+ const messages = outgoing[Symbol.asyncIterator]();
33
+ const registration = await messages.next();
34
+ if (!registration.done) attempt.sent.push(registration.value);
35
+ for await (const message of attempt.incoming) {
36
+ yield message;
37
+ const result = await messages.next();
38
+ if (!result.done) attempt.sent.push(result.value);
39
+ }
40
+ })();
41
+ });
42
+ readonly reactors: Reactors;
43
+
44
+ constructor(skipKeepAlive = false) {
45
+ this.reactors = new Reactors({ reactors: this.artifacts, eventTypes: this.types } as unknown as IClientArtifactsProvider,
46
+ { reactors: { observe: this.observe }, observers: { getObserverInformation: this.information } } as unknown as ChronicleConnection,
47
+ 'store', 'tenant', this.lifecycle, {} as IEventLog, undefined, undefined, undefined, skipKeepAlive,
48
+ { baseDelayMs: 10, nextJitter: () => 0 });
49
+ }
50
+ }