@cratis/chronicle 6.54.0 → 6.56.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 (170) hide show
  1. package/ChronicleClient.ts +16 -3
  2. package/ChronicleOptions.ts +11 -0
  3. package/EventStore.ts +8 -3
  4. package/WellKnownTelemetryNames.ts +2 -0
  5. package/artifacts/refuseClientHostedObservers.ts +16 -0
  6. package/connection/ChronicleConnection.auth.spec.ts +2 -0
  7. package/connection/ChronicleConnection.ts +21 -9
  8. package/connection/ChronicleConnectionString.ts +26 -1
  9. package/connection/ClientObserversRequireKeepAlive.ts +10 -0
  10. package/connection/for_ChronicleConnection/when_deferring_client_creation/and_connecting.spec.ts +83 -0
  11. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -0
  12. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -0
  13. package/dist/ChronicleClient.d.ts +1 -0
  14. package/dist/ChronicleClient.d.ts.map +1 -1
  15. package/dist/ChronicleClient.js +16 -3
  16. package/dist/ChronicleClient.js.map +1 -1
  17. package/dist/ChronicleOptions.d.ts +4 -0
  18. package/dist/ChronicleOptions.d.ts.map +1 -1
  19. package/dist/ChronicleOptions.js +7 -0
  20. package/dist/ChronicleOptions.js.map +1 -1
  21. package/dist/EventStore.d.ts +2 -1
  22. package/dist/EventStore.d.ts.map +1 -1
  23. package/dist/EventStore.js +10 -3
  24. package/dist/EventStore.js.map +1 -1
  25. package/dist/WellKnownTelemetryNames.d.ts +2 -0
  26. package/dist/WellKnownTelemetryNames.d.ts.map +1 -1
  27. package/dist/WellKnownTelemetryNames.js +2 -0
  28. package/dist/WellKnownTelemetryNames.js.map +1 -1
  29. package/dist/artifacts/refuseClientHostedObservers.d.ts +4 -0
  30. package/dist/artifacts/refuseClientHostedObservers.d.ts.map +1 -0
  31. package/dist/artifacts/refuseClientHostedObservers.js +15 -0
  32. package/dist/artifacts/refuseClientHostedObservers.js.map +1 -0
  33. package/dist/connection/ChronicleConnection.d.ts +7 -1
  34. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  35. package/dist/connection/ChronicleConnection.js +13 -8
  36. package/dist/connection/ChronicleConnection.js.map +1 -1
  37. package/dist/connection/ChronicleConnectionString.d.ts +8 -0
  38. package/dist/connection/ChronicleConnectionString.d.ts.map +1 -1
  39. package/dist/connection/ChronicleConnectionString.js +21 -1
  40. package/dist/connection/ChronicleConnectionString.js.map +1 -1
  41. package/dist/connection/ClientObserversRequireKeepAlive.d.ts +7 -0
  42. package/dist/connection/ClientObserversRequireKeepAlive.d.ts.map +1 -0
  43. package/dist/connection/ClientObserversRequireKeepAlive.js +14 -0
  44. package/dist/connection/ClientObserversRequireKeepAlive.js.map +1 -0
  45. package/dist/eventSequences/EventSequence.d.ts +3 -0
  46. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  47. package/dist/eventSequences/EventSequence.js +29 -1
  48. package/dist/eventSequences/EventSequence.js.map +1 -1
  49. package/dist/eventSequences/IEventSequence.d.ts +12 -0
  50. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  51. package/dist/eventSequences/ITransactionalEventSequence.d.ts +6 -0
  52. package/dist/eventSequences/ITransactionalEventSequence.d.ts.map +1 -1
  53. package/dist/eventSequences/TransactionalEventSequence.d.ts.map +1 -1
  54. package/dist/eventSequences/TransactionalEventSequence.js +3 -1
  55. package/dist/eventSequences/TransactionalEventSequence.js.map +1 -1
  56. package/dist/externalServices/ExternalServiceBuilder.js +1 -1
  57. package/dist/externalServices/ExternalServiceBuilder.js.map +1 -1
  58. package/dist/for_ChronicleClient/when_skipping_keep_alive/native-exit-probe.d.ts +2 -0
  59. package/dist/for_ChronicleClient/when_skipping_keep_alive/native-exit-probe.d.ts.map +1 -0
  60. package/dist/for_ChronicleClient/when_skipping_keep_alive/native-exit-probe.js +107 -0
  61. package/dist/for_ChronicleClient/when_skipping_keep_alive/native-exit-probe.js.map +1 -0
  62. package/dist/index.d.ts +1 -0
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/reactors/Reactors.d.ts +2 -1
  67. package/dist/reactors/Reactors.d.ts.map +1 -1
  68. package/dist/reactors/Reactors.js +12 -3
  69. package/dist/reactors/Reactors.js.map +1 -1
  70. package/dist/readModels/for_ReadModels/given/a_stored_read_model.d.ts.map +1 -1
  71. package/dist/readModels/for_ReadModels/given/a_stored_read_model.js +1 -1
  72. package/dist/readModels/for_ReadModels/given/a_stored_read_model.js.map +1 -1
  73. package/dist/readModels/indexDecorator.js +1 -1
  74. package/dist/readModels/indexDecorator.js.map +1 -1
  75. package/dist/reducers/Reducers.d.ts +2 -1
  76. package/dist/reducers/Reducers.d.ts.map +1 -1
  77. package/dist/reducers/Reducers.js +8 -2
  78. package/dist/reducers/Reducers.js.map +1 -1
  79. package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
  80. package/dist/reducers/ReductionOutcome.js +4 -1
  81. package/dist/reducers/ReductionOutcome.js.map +1 -1
  82. package/dist/testing/InProcessEventSequence.d.ts +2 -1
  83. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  84. package/dist/testing/InProcessEventSequence.js +1 -0
  85. package/dist/testing/InProcessEventSequence.js.map +1 -1
  86. package/dist/transactions/AppendOptionNotSupportedInUnitOfWork.d.ts +13 -0
  87. package/dist/transactions/AppendOptionNotSupportedInUnitOfWork.d.ts.map +1 -0
  88. package/dist/transactions/AppendOptionNotSupportedInUnitOfWork.js +19 -0
  89. package/dist/transactions/AppendOptionNotSupportedInUnitOfWork.js.map +1 -0
  90. package/dist/transactions/ConflictingAppendOptionNamesInUnitOfWork.d.ts +14 -0
  91. package/dist/transactions/ConflictingAppendOptionNamesInUnitOfWork.d.ts.map +1 -0
  92. package/dist/transactions/ConflictingAppendOptionNamesInUnitOfWork.js +21 -0
  93. package/dist/transactions/ConflictingAppendOptionNamesInUnitOfWork.js.map +1 -0
  94. package/dist/transactions/IUnitOfWork.d.ts +3 -0
  95. package/dist/transactions/IUnitOfWork.d.ts.map +1 -1
  96. package/dist/transactions/TransactionalAppendOptions.d.ts +8 -0
  97. package/dist/transactions/TransactionalAppendOptions.d.ts.map +1 -1
  98. package/dist/transactions/UnitOfWork.d.ts.map +1 -1
  99. package/dist/transactions/UnitOfWork.js +4 -2
  100. package/dist/transactions/UnitOfWork.js.map +1 -1
  101. package/dist/transactions/concurrencyScopesAreEqual.d.ts.map +1 -1
  102. package/dist/transactions/concurrencyScopesAreEqual.js +4 -3
  103. package/dist/transactions/concurrencyScopesAreEqual.js.map +1 -1
  104. package/dist/transactions/index.d.ts +2 -0
  105. package/dist/transactions/index.d.ts.map +1 -1
  106. package/dist/transactions/index.js +2 -0
  107. package/dist/transactions/index.js.map +1 -1
  108. package/dist/transactions/resolveTransactionalAppendOptions.d.ts +8 -0
  109. package/dist/transactions/resolveTransactionalAppendOptions.d.ts.map +1 -0
  110. package/dist/transactions/resolveTransactionalAppendOptions.js +58 -0
  111. package/dist/transactions/resolveTransactionalAppendOptions.js.map +1 -0
  112. package/dist/tsconfig.tsbuildinfo +1 -1
  113. package/dist/webhooks/WebhookDefinitionBuilder.d.ts.map +1 -1
  114. package/dist/webhooks/WebhookDefinitionBuilder.js +4 -2
  115. package/dist/webhooks/WebhookDefinitionBuilder.js.map +1 -1
  116. package/dist/webhooks/Webhooks.d.ts.map +1 -1
  117. package/dist/webhooks/Webhooks.js +2 -1
  118. package/dist/webhooks/Webhooks.js.map +1 -1
  119. package/eventSequences/EventSequence.spec.ts +55 -0
  120. package/eventSequences/EventSequence.ts +30 -1
  121. package/eventSequences/IEventSequence.ts +13 -0
  122. package/eventSequences/ITransactionalEventSequence.ts +6 -0
  123. package/eventSequences/TransactionalEventSequence.ts +3 -1
  124. package/eventSequences/for_TransactionalEventSequence/when_appending_many_with_append_option_names.spec.ts +26 -0
  125. package/eventSequences/for_TransactionalEventSequence/when_appending_many_with_unsupported_options.spec.ts +35 -0
  126. package/externalServices/ExternalServiceBuilder.ts +1 -1
  127. package/externalServices/ExternalServices.spec.ts +1 -1
  128. package/for_ChronicleClient/against_a_kernel/when_skipping_keep_alive.integration.spec.ts +80 -0
  129. package/for_ChronicleClient/when_skipping_keep_alive/and_connecting.spec.ts +158 -0
  130. package/for_ChronicleClient/when_skipping_keep_alive/native-exit-probe.ts +84 -0
  131. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -0
  132. package/for_ChronicleOptions/when_configuring_keep_alive/with_skip_keep_alive.spec.ts +35 -0
  133. package/for_EventStore/when_skipping_keep_alive/when_registering_artifacts.spec.ts +51 -0
  134. package/index.ts +1 -0
  135. package/package.json +2 -2
  136. package/reactors/Reactors.ts +10 -3
  137. package/reactors/for_Reactors/when_skipping_keep_alive/with_a_reactor.spec.ts +48 -0
  138. package/readModels/for_ReadModels/given/a_stored_read_model.ts +1 -1
  139. package/readModels/indexDecorator.legacy.spec.ts +7 -7
  140. package/readModels/indexDecorator.ts +1 -1
  141. package/readModels/indexRegistration.spec.ts +4 -4
  142. package/readModels/standardFallbacks.standard.spec.ts +2 -2
  143. package/reducers/Reducers.ts +6 -2
  144. package/reducers/ReductionOutcome.ts +4 -1
  145. package/reducers/for_Reducers/when_skipping_keep_alive/with_a_reducer.spec.ts +53 -0
  146. package/telemetry/for_ChronicleTelemetry/given/a_client.fixture.ts +1 -0
  147. package/telemetry/for_ChronicleTelemetry/given/a_span_name_registry.fixture.ts +2 -0
  148. package/telemetry/for_ChronicleTelemetry/given/an_event_sequence.fixture.ts +2 -1
  149. package/telemetry/for_ChronicleTelemetry/when_naming_spans/with_convention_names.spec.ts +1 -0
  150. package/telemetry/for_ChronicleTelemetry/when_recording_identifiers/with_per_client_privacy.spec.ts +2 -1
  151. package/testing/InProcessEventSequence.ts +1 -0
  152. package/transactions/AppendOptionNotSupportedInUnitOfWork.ts +17 -0
  153. package/transactions/ConflictingAppendOptionNamesInUnitOfWork.ts +17 -0
  154. package/transactions/IUnitOfWork.ts +3 -0
  155. package/transactions/TransactionalAppendOptions.ts +11 -0
  156. package/transactions/UnitOfWork.ts +4 -2
  157. package/transactions/concurrencyScopesAreEqual.ts +4 -3
  158. package/transactions/for_UnitOfWork/when_adding_events_with_append_option_names/and_both_names_have_different_values.spec.ts +65 -0
  159. package/transactions/for_UnitOfWork/when_adding_events_with_append_option_names/and_both_names_have_the_same_value.spec.ts +22 -0
  160. package/transactions/for_UnitOfWork/when_adding_events_with_append_option_names/and_the_append_option_names_are_used.spec.ts +25 -0
  161. package/transactions/for_UnitOfWork/when_adding_events_with_concurrency_scopes/and_a_routing_field_is_empty_versus_named.spec.ts +40 -0
  162. package/transactions/for_UnitOfWork/when_adding_events_with_concurrency_scopes/and_routing_fields_are_undefined_or_empty.spec.ts +39 -0
  163. package/transactions/for_UnitOfWork/when_adding_events_with_unsupported_append_options/and_a_correlation_id_is_given.spec.ts +38 -0
  164. package/transactions/for_UnitOfWork/when_adding_events_with_unsupported_append_options/and_an_event_source_id_is_given.spec.ts +38 -0
  165. package/transactions/for_UnitOfWork/when_adding_events_with_unsupported_append_options/and_concurrency_scopes_are_given.spec.ts +38 -0
  166. package/transactions/for_UnitOfWork/when_adding_events_with_unsupported_append_options/and_the_option_is_undefined.spec.ts +24 -0
  167. package/transactions/index.ts +2 -0
  168. package/transactions/resolveTransactionalAppendOptions.ts +68 -0
  169. package/webhooks/WebhookDefinitionBuilder.ts +4 -2
  170. package/webhooks/Webhooks.ts +2 -1
@@ -6,6 +6,8 @@ import { createLogger } from './logging/createLogger.js';
6
6
  import { setTelemetryAttribute, recordSafeException } from './telemetry/spanAttributes.js';
7
7
  import { SpanStatusCode } from '@opentelemetry/api';
8
8
  import { ChronicleOptions } from './ChronicleOptions.js';
9
+ import { refuseClientHostedObservers } from './artifacts/refuseClientHostedObservers.js';
10
+ import { ClientObserversRequireKeepAlive } from './connection/ClientObserversRequireKeepAlive.js';
9
11
  import { ChronicleConnection } from './connection/index.js';
10
12
  import { IncompatibleChronicleServer } from './connection/IncompatibleChronicleServer.js';
11
13
  import { OAuthTokenHttpError } from './connection/fetchOAuthAccessToken.js';
@@ -95,6 +97,7 @@ export class ChronicleClient implements IChronicleClient {
95
97
  : { connectionString: options.connectionString };
96
98
  this._connection = new ChronicleConnection({
97
99
  ...connectionOptions,
100
+ deferClientCreation: options.skipKeepAlive,
98
101
  logger: options.logger,
99
102
  maxReceiveMessageSize: options.maxReceiveMessageSize ?? undefined,
100
103
  maxSendMessageSize: options.maxSendMessageSize ?? undefined
@@ -136,7 +139,7 @@ export class ChronicleClient implements IChronicleClient {
136
139
  });
137
140
  });
138
141
 
139
- this.startConnectionWatchdog();
142
+ if (!options.skipKeepAlive) this.startConnectionWatchdog();
140
143
  }
141
144
 
142
145
  /** @inheritdoc */
@@ -193,7 +196,7 @@ export class ChronicleClient implements IChronicleClient {
193
196
  });
194
197
  ensureCommandSuccess('ensure event store', await this._connection.eventStores.ensureEventStore({ Name: storeName.value }));
195
198
 
196
- const created = new EventStore(storeName, namespaceName, this._connection, this._lifecycle, this.options.defaultSinkTypeId, this.options.clientArtifactsProvider, this.options.reactorResultHandler, this.options.artifactActivator, this.options.readModelNamingPolicy, this.options.telemetry);
199
+ const created = new EventStore(storeName, namespaceName, this._connection, this._lifecycle, this.options.defaultSinkTypeId, this.options.clientArtifactsProvider, this.options.reactorResultHandler, this.options.artifactActivator, this.options.readModelNamingPolicy, this.options.telemetry, this.options.skipKeepAlive);
197
200
  this._stores.set(key, created);
198
201
 
199
202
  try {
@@ -300,6 +303,12 @@ export class ChronicleClient implements IChronicleClient {
300
303
  throw new Error('ChronicleClient was disposed during connection attempt.');
301
304
  }
302
305
 
306
+ private async validateClientObservers(): Promise<void> {
307
+ if (!this.options.skipKeepAlive) return;
308
+ await this._discoveryOperation;
309
+ refuseClientHostedObservers(this.options.clientArtifactsProvider);
310
+ }
311
+
303
312
  private async ensureConnected(): Promise<void> {
304
313
  if (this._isDisposed) {
305
314
  throw new Error('ChronicleClient is disposed. Create a new client instance before making calls.');
@@ -307,6 +316,8 @@ export class ChronicleClient implements IChronicleClient {
307
316
 
308
317
  if (this._connectionFailure) throw this._connectionFailure;
309
318
 
319
+ await this.validateClientObservers();
320
+
310
321
  // Callers arriving during recovery must share its verdict, not create a competing channel.
311
322
  if (this._reconnectOperation) await this._reconnectOperation;
312
323
 
@@ -443,7 +454,7 @@ export class ChronicleClient implements IChronicleClient {
443
454
  }
444
455
 
445
456
  private shouldReconnect(error: unknown): boolean {
446
- if (isTerminalServerError(error)) return false;
457
+ if (error instanceof ClientObserversRequireKeepAlive || isTerminalServerError(error)) return false;
447
458
  return this.isRejectedAuthentication(error) ||
448
459
  hasReconnectableStatusCode(error) ||
449
460
  this.mentionsConnectionProblem(error);
@@ -499,6 +510,8 @@ export class ChronicleClient implements IChronicleClient {
499
510
  }
500
511
 
501
512
  private async startKernelKeepAlive(): Promise<void> {
513
+ if (this.options.skipKeepAlive) return;
514
+
502
515
  this._keepAliveAbortController?.abort();
503
516
  this._keepAliveAbortController = new AbortController();
504
517
  const { signal } = this._keepAliveAbortController;
@@ -15,6 +15,7 @@ type ChronicleOptionsConstructorParams = {
15
15
  telemetry?: ChronicleTelemetryOptions;
16
16
  logger?: IChronicleLogger;
17
17
  connectionString: ChronicleConnectionString;
18
+ skipKeepAlive?: boolean;
18
19
  programIdentifier?: string;
19
20
  softwareVersion?: string;
20
21
  softwareCommit?: string;
@@ -29,6 +30,7 @@ type ChronicleOptionsConstructorParams = {
29
30
  };
30
31
 
31
32
  type ChronicleOptionsFactoryParams = {
33
+ skipKeepAlive?: boolean;
32
34
  telemetry?: ChronicleTelemetryOptions;
33
35
  logger?: IChronicleLogger;
34
36
  clientArtifactsProvider?: IClientArtifactsProvider;
@@ -45,6 +47,9 @@ type ChronicleOptionsFactoryParams = {
45
47
  * Represents configuration options for the Chronicle client.
46
48
  */
47
49
  export class ChronicleOptions {
50
+ /** Skip the keep-alive stream and health watchdog for short-lived processes. Either input can enable this. */
51
+ readonly skipKeepAlive: boolean;
52
+
48
53
  /** Per-client telemetry privacy settings. Event source identifiers are omitted by default. */
49
54
  readonly telemetry?: ChronicleTelemetryOptions;
50
55
 
@@ -121,6 +126,7 @@ export class ChronicleOptions {
121
126
 
122
127
  private constructor(options: ChronicleOptionsConstructorParams) {
123
128
  this.connectionString = options.connectionString;
129
+ this.skipKeepAlive = options.skipKeepAlive === true;
124
130
  this.programIdentifier = options.programIdentifier ?? 'Unknown';
125
131
  this.softwareVersion = options.softwareVersion ?? '0.0.0';
126
132
  this.softwareCommit = options.softwareCommit ?? 'Unknown';
@@ -174,6 +180,10 @@ export class ChronicleOptions {
174
180
  ];
175
181
  }
176
182
 
183
+ private static shouldSkipKeepAlive(connectionString: ChronicleConnectionString, options?: ChronicleOptionsFactoryParams): boolean {
184
+ return options?.skipKeepAlive === true || connectionString.skipKeepAlive;
185
+ }
186
+
177
187
  /**
178
188
  * Creates a {@link ChronicleOptions} instance from a connection string.
179
189
  * @param connectionString - The connection string to parse and use.
@@ -188,6 +198,7 @@ export class ChronicleOptions {
188
198
  : connectionString;
189
199
  return new ChronicleOptions({
190
200
  connectionString: parsed,
201
+ skipKeepAlive: ChronicleOptions.shouldSkipKeepAlive(parsed, options),
191
202
  clientArtifactsProvider: options?.clientArtifactsProvider,
192
203
  discoveryPatterns: options?.discoveryPatterns,
193
204
  defaultSinkTypeId: options?.defaultSinkTypeId,
package/EventStore.ts CHANGED
@@ -41,6 +41,7 @@ import { observeOperation } from './telemetry/observeOperation.js';
41
41
  import { DefaultClientArtifactsProvider } from './artifacts/DefaultClientArtifactsProvider.js';
42
42
  import type { IClientArtifactsProvider } from './artifacts/IClientArtifactsProvider.js';
43
43
  import { validateArtifactSchemas } from './artifacts/validateArtifactSchemas.js';
44
+ import { refuseClientHostedObservers } from './artifacts/refuseClientHostedObservers.js';
44
45
  import { IUnitOfWorkManager } from './transactions/IUnitOfWorkManager.js';
45
46
  import { UnitOfWorkManager } from './transactions/UnitOfWorkManager.js';
46
47
  import { IJobs } from './jobs/IJobs.js';
@@ -101,7 +102,8 @@ export class EventStore implements IEventStore {
101
102
  reactorResultHandler?: ReactorResultHandler,
102
103
  artifactActivator?: ClientArtifactsActivator,
103
104
  readModelNamingPolicy?: ReadModelNamingPolicy,
104
- private readonly _telemetry?: ChronicleTelemetryOptions
105
+ private readonly _telemetry?: ChronicleTelemetryOptions,
106
+ private readonly _skipKeepAlive: boolean = false
105
107
  ) {
106
108
  this._logger = createLogger('@cratis/chronicle/EventStore', _connection.logger);
107
109
  this.unitOfWorkManager = new UnitOfWorkManager(this);
@@ -116,8 +118,8 @@ export class EventStore implements IEventStore {
116
118
 
117
119
  this.eventTypes = new EventTypes(name.value, _connection, artifacts);
118
120
  this.projections = new Projections(name.value, namespace.value, _connection, artifacts, defaultSinkTypeId, readModelNamingPolicy);
119
- this.reactors = new Reactors(artifacts, _connection, name.value, namespace.value, lifecycle, this.eventLog, reactorResultHandler, this, artifactActivator);
120
- this.reducers = new Reducers(artifacts, _connection, name.value, namespace.value, lifecycle, defaultSinkTypeId, this, artifactActivator, readModelNamingPolicy);
121
+ this.reactors = new Reactors(artifacts, _connection, name.value, namespace.value, lifecycle, this.eventLog, reactorResultHandler, this, artifactActivator, _skipKeepAlive);
122
+ this.reducers = new Reducers(artifacts, _connection, name.value, namespace.value, lifecycle, defaultSinkTypeId, this, artifactActivator, readModelNamingPolicy, _skipKeepAlive);
121
123
  this.readModels = new ReadModels(name.value, namespace.value, _connection, artifacts, defaultSinkTypeId, readModelType => this.projections.hasForModel(readModelType), readModelNamingPolicy, lifecycle);
122
124
  this.jobs = new Jobs(name.value, namespace.value, _connection);
123
125
  this.patterns = new Patterns(name.value, namespace.value, _connection);
@@ -137,6 +139,8 @@ export class EventStore implements IEventStore {
137
139
  * @returns A promise that resolves when all registrations are complete.
138
140
  */
139
141
  async registerArtifacts(): Promise<void> {
142
+ if (this._skipKeepAlive) refuseClientHostedObservers(this._artifacts);
143
+
140
144
  this._logger.debug('Discovering artifacts for registration', {
141
145
  eventStore: this.name.value,
142
146
  namespace: this.namespace.value
@@ -153,6 +157,7 @@ export class EventStore implements IEventStore {
153
157
  this.seeding.discover()
154
158
  ]);
155
159
 
160
+ if (this._skipKeepAlive) refuseClientHostedObservers(this._artifacts);
156
161
  validateArtifactSchemas(this._artifacts);
157
162
  for (const type of this._artifacts.reactors) {
158
163
  getReactorEventTypes(type, this._artifacts.eventTypes);
@@ -60,6 +60,7 @@ export const WellKnownTelemetryNames = {
60
60
  getFromSequenceNumber: 'chronicle.event_sequences.get_from_sequence_number',
61
61
  redact: 'chronicle.event_sequences.redact',
62
62
  redactForEventSource: 'chronicle.event_sequences.redact_for_event_source',
63
+ copyForEventSource: 'chronicle.event_sequences.copy_for_event_source',
63
64
  completeStream: 'chronicle.event_sequences.complete_stream',
64
65
  getEventStore: 'chronicle.client.get_event_store',
65
66
  getEventStores: 'chronicle.client.get_event_stores',
@@ -75,6 +76,7 @@ export const WellKnownTelemetryNames = {
75
76
  getFromSequenceNumber: 'cratis.chronicle.client.event_sequence.get_from_sequence_number',
76
77
  redact: 'cratis.chronicle.client.event_sequence.redact',
77
78
  redactForEventSource: 'cratis.chronicle.client.event_sequence.redact_for_event_source',
79
+ copyForEventSource: 'cratis.chronicle.client.event_sequence.copy_for_event_source',
78
80
  completeStream: 'cratis.chronicle.client.event_sequence.complete_stream',
79
81
  getEventStore: 'cratis.chronicle.client.event_store.get',
80
82
  getEventStores: 'cratis.chronicle.client.event_store.list',
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { IClientArtifactsProvider } from './IClientArtifactsProvider.js';
5
+ import { getReactorMetadata } from '../reactors/reactor.js';
6
+ import { getReducerMetadata } from '../reducers/reducer.js';
7
+ import { ClientObserversRequireKeepAlive } from '../connection/ClientObserversRequireKeepAlive.js';
8
+
9
+ /** Refuse client-hosted observers before any network or registration side effects. */
10
+ export function refuseClientHostedObservers(artifacts: Pick<IClientArtifactsProvider, 'reactors' | 'reducers'>): void {
11
+ const reactor = artifacts.reactors.map(getReactorMetadata).find(metadata => metadata !== undefined);
12
+ if (reactor) throw new ClientObserversRequireKeepAlive('Reactor', reactor.id.value);
13
+
14
+ const reducer = artifacts.reducers.map(getReducerMetadata).find(metadata => metadata !== undefined);
15
+ if (reducer) throw new ClientObserversRequireKeepAlive('Reducer', reducer.id.value);
16
+ }
@@ -50,9 +50,11 @@ async function listenAuthenticated(onCheck?: () => void): Promise<number> {
50
50
  }
51
51
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
52
52
  server.add(ServerDefinition, {
53
+ ...Object.fromEntries(Object.keys(ServerDefinition.methods).map(name => [name, unsupported])),
53
54
  getVersionInfo: async () => ({}), resetKernelState: unsupported
54
55
  } as ServiceImplementation<typeof ServerDefinition>);
55
56
  server.add(EventStoresDefinition, {
57
+ ...Object.fromEntries(Object.keys(EventStoresDefinition.methods).map(name => [name, unsupported])),
56
58
  allEventStores: async () => ({ IsAuthorized: true, Data: [] }),
57
59
  ensureEventStore: unsupported, observeEventStores: unsupported
58
60
  } as ServiceImplementation<typeof EventStoresDefinition>);
@@ -51,6 +51,12 @@ import { ITokenProvider, NoOpTokenProvider, OAuthTokenProvider } from './TokenPr
51
51
  * Configuration options for Chronicle connection.
52
52
  */
53
53
  export interface ChronicleConnectionOptions {
54
+ /**
55
+ * Do not resolve or select a server, or build the channel, until the first connect()/resetChannel().
56
+ * Used by short-lived clients so nothing touches the network before the caller's first operation.
57
+ */
58
+ deferClientCreation?: boolean;
59
+
54
60
  /** Optional client-owned diagnostic sink; absent preserves the diag adapter. */
55
61
  logger?: IChronicleLogger;
56
62
 
@@ -109,7 +115,7 @@ export class ChronicleConnection implements ChronicleServices {
109
115
  private readonly _loadBalancerStrategy: ILoadBalancerStrategy;
110
116
  private _isConnected = false;
111
117
  private _warnedAboutSkippedTlsValidation = false;
112
- private _clientsReady: Promise<void>;
118
+ private _clientsReady?: Promise<void>;
113
119
 
114
120
  constructor(private readonly _options: ChronicleConnectionOptions) {
115
121
  if (_options.connectionString) {
@@ -129,12 +135,14 @@ export class ChronicleConnection implements ChronicleServices {
129
135
  this._addressResolver = new ChronicleServerAddressResolver();
130
136
  this._loadBalancerStrategy = createLoadBalancerStrategy(this._connectionString.loadBalancer, this._connectionString.skipTlsValidation);
131
137
 
132
- this._clientsReady = runInBackgroundContext(() => this.createClients());
133
- // Building the initial channel is async (address resolution + load balancer
134
- // selection), so the constructor cannot await it. Real failures still surface to
135
- // callers that await connect()/resetChannel(); this only prevents an unhandled
136
- // rejection warning from the fire-and-forget initial build.
137
- this._clientsReady.catch(() => {});
138
+ if (!_options.deferClientCreation) {
139
+ this._clientsReady = this.startClientCreation();
140
+ // Building the initial channel is async (address resolution + load balancer
141
+ // selection), so the constructor cannot await it. Real failures still surface to
142
+ // callers that await connect()/resetChannel(); this only prevents an unhandled
143
+ // rejection warning from the fire-and-forget initial build.
144
+ this._clientsReady.catch(() => {});
145
+ }
138
146
  }
139
147
 
140
148
  /** The diagnostic sink shared by services owned by this connection. */
@@ -250,8 +258,12 @@ export class ChronicleConnection implements ChronicleServices {
250
258
  return this._connections;
251
259
  }
252
260
 
261
+ private startClientCreation(): Promise<void> {
262
+ return runInBackgroundContext(() => this.createClients());
263
+ }
264
+
253
265
  async connect(): Promise<void> {
254
- await this._clientsReady;
266
+ await (this._clientsReady ??= this.startClientCreation());
255
267
  // The bounded compatibility RPC establishes transport readiness and contract support together.
256
268
  await this._compatibility.verify();
257
269
  this._isConnected = true;
@@ -265,7 +277,7 @@ export class ChronicleConnection implements ChronicleServices {
265
277
  }
266
278
 
267
279
  this._isConnected = false;
268
- this._clientsReady = runInBackgroundContext(() => this.createClients());
280
+ this._clientsReady = this.startClientCreation();
269
281
  await this._clientsReady;
270
282
  }
271
283
 
@@ -104,6 +104,7 @@ export class ChronicleConnectionStringBuilder {
104
104
  private static readonly _schemeKey = 'Scheme';
105
105
  private static readonly _apiKeyKey = 'apiKey';
106
106
  private static readonly _disableTlsKey = 'disableTls';
107
+ private static readonly _skipKeepAliveKey = 'skipKeepAlive';
107
108
  private static readonly _skipTlsValidationKey = 'skipTlsValidation';
108
109
  private static readonly _certificatePathKey = 'certificatePath';
109
110
  private static readonly _certificatePasswordKey = 'certificatePassword';
@@ -251,6 +252,15 @@ export class ChronicleConnectionStringBuilder {
251
252
  this._properties.set(ChronicleConnectionStringBuilder._skipTlsValidationKey, value.toString());
252
253
  }
253
254
 
255
+ /** Skip the client keep-alive connection for short-lived processes. Defaults to false. */
256
+ get skipKeepAlive(): boolean {
257
+ return this._properties.get(ChronicleConnectionStringBuilder._skipKeepAliveKey) === 'true';
258
+ }
259
+
260
+ set skipKeepAlive(value: boolean) {
261
+ this._properties.set(ChronicleConnectionStringBuilder._skipKeepAliveKey, value.toString());
262
+ }
263
+
254
264
  get certificatePath(): string | undefined {
255
265
  return this._properties.get(ChronicleConnectionStringBuilder._certificatePathKey);
256
266
  }
@@ -345,6 +355,8 @@ export class ChronicleConnectionStringBuilder {
345
355
  queryParameters.push('disableTls=true');
346
356
  }
347
357
 
358
+ this.appendSkipKeepAlive(queryParameters);
359
+
348
360
  if (!this.skipTlsValidation) {
349
361
  queryParameters.push('skipTlsValidation=false');
350
362
  }
@@ -365,7 +377,7 @@ export class ChronicleConnectionStringBuilder {
365
377
  queryParameters.push(`srvNameServer=${encodeURIComponent(this.srvNameServer)}`);
366
378
  }
367
379
 
368
- for (const [key, value] of this._properties) {
380
+ for (const [key, value] of this.propertiesWithoutSkipKeepAlive()) {
369
381
  if (
370
382
  key !== ChronicleConnectionStringBuilder._usernameKey &&
371
383
  key !== ChronicleConnectionStringBuilder._passwordKey &&
@@ -389,6 +401,14 @@ export class ChronicleConnectionStringBuilder {
389
401
  return result;
390
402
  }
391
403
 
404
+ private appendSkipKeepAlive(queryParameters: string[]): void {
405
+ if (this.skipKeepAlive) queryParameters.push('skipKeepAlive=true');
406
+ }
407
+
408
+ private propertiesWithoutSkipKeepAlive(): [string, string][] {
409
+ return [...this._properties].filter(([key]) => key !== ChronicleConnectionStringBuilder._skipKeepAliveKey);
410
+ }
411
+
392
412
  private parseConnectionString(connectionString: string): void {
393
413
  const lowerCased = connectionString.toLowerCase();
394
414
  if (lowerCased.startsWith('chronicle://') || lowerCased.startsWith(`${SRV_SCHEME}://`)) {
@@ -518,6 +538,11 @@ export class ChronicleConnectionString {
518
538
  return this._builder.disableTls;
519
539
  }
520
540
 
541
+ /** Whether the client skips the keep-alive connection for short-lived processes. */
542
+ get skipKeepAlive(): boolean {
543
+ return this._builder.skipKeepAlive;
544
+ }
545
+
521
546
  /**
522
547
  * Whether TLS certificate validation is skipped. See
523
548
  * {@link ChronicleConnectionStringBuilder.skipTlsValidation}.
@@ -0,0 +1,10 @@
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
+ /** A client-hosted observer requires a long-running keep-alive connection. */
5
+ export class ClientObserversRequireKeepAlive extends Error {
6
+ constructor(readonly observerKind: 'Reactor' | 'Reducer', readonly observerId: string) {
7
+ super(`${observerKind} '${observerId}' cannot be registered because this client skips the keep-alive connection (short-lived process). Client-hosted observers need a long-running process: host them in a client that does not set skipKeepAlive.`);
8
+ this.name = 'ClientObserversRequireKeepAlive';
9
+ }
10
+ }
@@ -0,0 +1,83 @@
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 { afterEach, beforeEach, chai, describe, it, vi } from 'vitest';
5
+ import { createServer, type ServiceImplementation } from 'nice-grpc';
6
+ import { ConnectionServiceDefinition } from '@cratis/chronicle.contracts';
7
+ import { ChronicleConnection } from '../../ChronicleConnection.js';
8
+ import { ChronicleServerAddressResolver } from '../../ChronicleServerAddressResolver.js';
9
+ import { LeastConnectionsLoadBalancerStrategy } from '../../LeastConnectionsLoadBalancerStrategy.js';
10
+ import { ChronicleClient } from '../../../ChronicleClient.js';
11
+ import { ChronicleOptions } from '../../../ChronicleOptions.js';
12
+ import { reactor } from '../../../reactors/reactor.js';
13
+ import { ClientObserversRequireKeepAlive } from '../../ClientObserversRequireKeepAlive.js';
14
+
15
+ chai.should();
16
+ @reactor('preflight')
17
+ class Observer {}
18
+ let server: ReturnType<typeof createServer>;
19
+ let connection: ChronicleConnection;
20
+ let client: ChronicleClient;
21
+ let address: string;
22
+ let fetch: ReturnType<typeof vi.spyOn>;
23
+ let select: ReturnType<typeof vi.spyOn>;
24
+ let resolve: ReturnType<typeof vi.spyOn>;
25
+ beforeEach(async () => {
26
+ server = createServer();
27
+ const unused = async () => { throw new Error('Unexpected RPC'); };
28
+ server.add(ConnectionServiceDefinition, {
29
+ ...Object.fromEntries(Object.keys(ConnectionServiceDefinition.methods).map(name => [name, unused])),
30
+ checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' })
31
+ } as ServiceImplementation<typeof ConnectionServiceDefinition>);
32
+ const port = await server.listen('127.0.0.1:0');
33
+ address = `chronicle://127.0.0.1:${port},127.0.0.1:1?disableTls=true`;
34
+ fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => new Response(String(input).includes(`:${port}/`) ? '0' : '1'));
35
+ select = vi.spyOn(LeastConnectionsLoadBalancerStrategy.prototype, 'select');
36
+ resolve = vi.spyOn(ChronicleServerAddressResolver.prototype, 'resolve');
37
+ });
38
+ afterEach(async () => {
39
+ client?.dispose();
40
+ connection?.dispose();
41
+ await server.shutdown();
42
+ vi.restoreAllMocks();
43
+ });
44
+ describe('when deferring client creation', () => {
45
+ it('should not resolve select probe or reserve before connecting', async () => {
46
+ connection = new ChronicleConnection({ connectionString: address, deferClientCreation: true });
47
+ await new Promise(resolve => setTimeout(resolve, 400));
48
+ resolve.mock.calls.should.have.lengthOf(0);
49
+ select.mock.calls.should.have.lengthOf(0);
50
+ fetch.mock.calls.should.have.lengthOf(0);
51
+ });
52
+ it('should create one channel on connect and replace it unconditionally on reset', async () => {
53
+ connection = new ChronicleConnection({ connectionString: address, deferClientCreation: true });
54
+ await connection.connect();
55
+ select.mock.calls.should.have.lengthOf(1);
56
+ fetch.mock.calls.should.have.lengthOf(3);
57
+ await connection.resetChannel();
58
+ await connection.connect();
59
+ select.mock.calls.should.have.lengthOf(2);
60
+ fetch.mock.calls.should.have.lengthOf(6);
61
+ });
62
+ it('should eagerly create clients by default', async () => {
63
+ connection = new ChronicleConnection({ connectionString: address });
64
+ await new Promise(resolve => setTimeout(resolve, 400));
65
+ select.mock.calls.should.have.lengthOf(1);
66
+ fetch.mock.calls.should.have.lengthOf(3);
67
+ });
68
+ it('should refuse observers before even multi-host probes', async () => {
69
+ client = new ChronicleClient(ChronicleOptions.fromConnectionString(address, {
70
+ skipKeepAlive: true, discoveryPatterns: [], clientArtifactsProvider: {
71
+ eventTypes: [], reactors: [Observer], reducers: [], readModels: [], seeders: [], constraints: [],
72
+ projections: [], webhooks: [], eventTypeMigrations: [], globalForHandlers: []
73
+ }
74
+ }));
75
+ const [result] = await Promise.allSettled([client.getEventStore('store')]);
76
+ result.status.should.equal('rejected');
77
+ if (result.status === 'rejected') result.reason.should.be.instanceOf(ClientObserversRequireKeepAlive);
78
+ await new Promise(resolve => setTimeout(resolve, 400));
79
+ resolve.mock.calls.should.have.lengthOf(0);
80
+ select.mock.calls.should.have.lengthOf(0);
81
+ fetch.mock.calls.should.have.lengthOf(0);
82
+ });
83
+ });
@@ -36,6 +36,7 @@ beforeEach(async () => {
36
36
  connectionKeepAlive: async () => ({})
37
37
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
38
38
  server.add(EventStoresDefinition, {
39
+ ...Object.fromEntries(Object.keys(EventStoresDefinition.methods).map(name => [name, unused])),
39
40
  allEventStores: async () => {
40
41
  if (rejectNext) {
41
42
  rejectNext = false;
@@ -35,6 +35,7 @@ beforeAll(async () => {
35
35
  checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' })
36
36
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
37
37
  server.add(EventStoresDefinition, {
38
+ ...Object.fromEntries(Object.keys(EventStoresDefinition.methods).map(name => [name, unused])),
38
39
  allEventStores: async () => ({ IsAuthorized: true, Data: [] }),
39
40
  ensureEventStore: unused,
40
41
  observeEventStores: async function* () {
@@ -47,6 +47,7 @@ export declare class ChronicleClient implements IChronicleClient {
47
47
  /** @inheritdoc */
48
48
  dispose(): void;
49
49
  private connectWithRetry;
50
+ private validateClientObservers;
50
51
  private ensureConnected;
51
52
  private reconnect;
52
53
  private recoverConnection;
@@ -1 +1 @@
1
- {"version":3,"file":"ChronicleClient.d.ts","sourceRoot":"","sources":["../ChronicleClient.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAUzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AA4B/C;;;;;;;;;;;;GAYG;AACH,qBAAa,eAAgB,YAAW,gBAAgB;IAwBxC,QAAQ,CAAC,OAAO,EAAE,gBAAgB;IAvB9C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,CAAQ;IACtD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAU;IAE/C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAsB;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsC;IAC9D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA6B;IAExD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkC;IAE1D,OAAO,CAAC,eAAe,CAAC,CAAiC;IACzD,OAAO,CAAC,iBAAiB,CAAC,CAAgB;IAC1C,OAAO,CAAC,mBAAmB,CAAC,CAAgB;IAC5C,OAAO,CAAC,mBAAmB,CAAC,CAAgB;IAC5C,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,yBAAyB,CAAC,CAAkB;IACpD,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,kBAAkB,CAAC,CAAQ;IACnC,OAAO,CAAC,gCAAgC,CAAK;IAE7C;;;OAGG;IACH,YAAqB,OAAO,EAAE,gBAAgB,EAsD7C;IAED,kBAAkB;IACZ,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,uBAAuB,GAAG,OAAO,CAAC,WAAW,CAAC,CA4BrH;IAED,OAAO,CAAC,eAAe;YAKT,qBAAqB;IA+BnC,kBAAkB;IACZ,cAAc,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC,CAuBhD;IAED,kBAAkB;IAClB,OAAO,IAAI,IAAI,CAqBd;YAEa,gBAAgB;YA4ChB,eAAe;YAuBf,SAAS;YAYT,iBAAiB;YAiBjB,kBAAkB;IA4BhC;;;;OAIG;YACW,OAAO;YAcP,aAAa;IAyB3B,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,2BAA2B;IAOnC,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,wBAAwB;IAKhC,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,uBAAuB;IAQ/B,OAAO,KAAK,oBAAoB,GAE/B;YAEa,cAAc;YAkBd,oBAAoB;IAmClC,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,0BAA0B;YAQpB,yBAAyB;CA4B1C"}
1
+ {"version":3,"file":"ChronicleClient.d.ts","sourceRoot":"","sources":["../ChronicleClient.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAYzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AA4B/C;;;;;;;;;;;;GAYG;AACH,qBAAa,eAAgB,YAAW,gBAAgB;IAwBxC,QAAQ,CAAC,OAAO,EAAE,gBAAgB;IAvB9C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,CAAQ;IACtD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAU;IAE/C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAsB;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsC;IAC9D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA6B;IAExD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkC;IAE1D,OAAO,CAAC,eAAe,CAAC,CAAiC;IACzD,OAAO,CAAC,iBAAiB,CAAC,CAAgB;IAC1C,OAAO,CAAC,mBAAmB,CAAC,CAAgB;IAC5C,OAAO,CAAC,mBAAmB,CAAC,CAAgB;IAC5C,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,yBAAyB,CAAC,CAAkB;IACpD,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,kBAAkB,CAAC,CAAQ;IACnC,OAAO,CAAC,gCAAgC,CAAK;IAE7C;;;OAGG;IACH,YAAqB,OAAO,EAAE,gBAAgB,EAuD7C;IAED,kBAAkB;IACZ,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,uBAAuB,GAAG,OAAO,CAAC,WAAW,CAAC,CA4BrH;IAED,OAAO,CAAC,eAAe;YAKT,qBAAqB;IA+BnC,kBAAkB;IACZ,cAAc,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC,CAuBhD;IAED,kBAAkB;IAClB,OAAO,IAAI,IAAI,CAqBd;YAEa,gBAAgB;YA4ChB,uBAAuB;YAMvB,eAAe;YAyBf,SAAS;YAYT,iBAAiB;YAiBjB,kBAAkB;IA4BhC;;;;OAIG;YACW,OAAO;YAcP,aAAa;IAyB3B,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,2BAA2B;IAOnC,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,wBAAwB;IAKhC,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,uBAAuB;IAQ/B,OAAO,KAAK,oBAAoB,GAE/B;YAEa,cAAc;YAkBd,oBAAoB;IAqClC,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,0BAA0B;YAQpB,yBAAyB;CA4B1C"}
@@ -4,6 +4,8 @@ import * as os from 'os';
4
4
  import { createLogger } from './logging/createLogger.js';
5
5
  import { setTelemetryAttribute, recordSafeException } from './telemetry/spanAttributes.js';
6
6
  import { SpanStatusCode } from '@opentelemetry/api';
7
+ import { refuseClientHostedObservers } from './artifacts/refuseClientHostedObservers.js';
8
+ import { ClientObserversRequireKeepAlive } from './connection/ClientObserversRequireKeepAlive.js';
7
9
  import { ChronicleConnection } from './connection/index.js';
8
10
  import { IncompatibleChronicleServer } from './connection/IncompatibleChronicleServer.js';
9
11
  import { OAuthTokenHttpError } from './connection/fetchOAuthAccessToken.js';
@@ -83,6 +85,7 @@ export class ChronicleClient {
83
85
  : { connectionString: options.connectionString };
84
86
  this._connection = new ChronicleConnection({
85
87
  ...connectionOptions,
88
+ deferClientCreation: options.skipKeepAlive,
86
89
  logger: options.logger,
87
90
  maxReceiveMessageSize: options.maxReceiveMessageSize ?? undefined,
88
91
  maxSendMessageSize: options.maxSendMessageSize ?? undefined
@@ -117,7 +120,8 @@ export class ChronicleClient {
117
120
  connectionId: this._lifecycle.connectionId
118
121
  });
119
122
  });
120
- this.startConnectionWatchdog();
123
+ if (!options.skipKeepAlive)
124
+ this.startConnectionWatchdog();
121
125
  }
122
126
  /** @inheritdoc */
123
127
  async getEventStore(name, namespace) {
@@ -169,7 +173,7 @@ export class ChronicleClient {
169
173
  eventStore: storeName.value
170
174
  });
171
175
  ensureCommandSuccess('ensure event store', await this._connection.eventStores.ensureEventStore({ Name: storeName.value }));
172
- const created = new EventStore(storeName, namespaceName, this._connection, this._lifecycle, this.options.defaultSinkTypeId, this.options.clientArtifactsProvider, this.options.reactorResultHandler, this.options.artifactActivator, this.options.readModelNamingPolicy, this.options.telemetry);
176
+ const created = new EventStore(storeName, namespaceName, this._connection, this._lifecycle, this.options.defaultSinkTypeId, this.options.clientArtifactsProvider, this.options.reactorResultHandler, this.options.artifactActivator, this.options.readModelNamingPolicy, this.options.telemetry, this.options.skipKeepAlive);
173
177
  this._stores.set(key, created);
174
178
  try {
175
179
  await this.registerArtifactsForStore(created, 'new-store');
@@ -267,12 +271,19 @@ export class ChronicleClient {
267
271
  }
268
272
  throw new Error('ChronicleClient was disposed during connection attempt.');
269
273
  }
274
+ async validateClientObservers() {
275
+ if (!this.options.skipKeepAlive)
276
+ return;
277
+ await this._discoveryOperation;
278
+ refuseClientHostedObservers(this.options.clientArtifactsProvider);
279
+ }
270
280
  async ensureConnected() {
271
281
  if (this._isDisposed) {
272
282
  throw new Error('ChronicleClient is disposed. Create a new client instance before making calls.');
273
283
  }
274
284
  if (this._connectionFailure)
275
285
  throw this._connectionFailure;
286
+ await this.validateClientObservers();
276
287
  // Callers arriving during recovery must share its verdict, not create a competing channel.
277
288
  if (this._reconnectOperation)
278
289
  await this._reconnectOperation;
@@ -398,7 +409,7 @@ export class ChronicleClient {
398
409
  ['invalid_client', 'unauthorized_client', 'invalid_grant'].includes(httpError.errorCode ?? '');
399
410
  }
400
411
  shouldReconnect(error) {
401
- if (isTerminalServerError(error))
412
+ if (error instanceof ClientObserversRequireKeepAlive || isTerminalServerError(error))
402
413
  return false;
403
414
  return this.isRejectedAuthentication(error) ||
404
415
  hasReconnectableStatusCode(error) ||
@@ -448,6 +459,8 @@ export class ChronicleClient {
448
459
  }
449
460
  }
450
461
  async startKernelKeepAlive() {
462
+ if (this.options.skipKeepAlive)
463
+ return;
451
464
  this._keepAliveAbortController?.abort();
452
465
  this._keepAliveAbortController = new AbortController();
453
466
  const { signal } = this._keepAliveAbortController;