@cratis/chronicle 6.64.0 → 6.66.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 (106) hide show
  1. package/ChronicleClient.ts +2 -1
  2. package/ChronicleOptions.ts +65 -23
  3. package/README.md +1 -1
  4. package/connection/ChronicleConnection.auth.spec.ts +3 -3
  5. package/connection/ChronicleConnection.ts +24 -7
  6. package/connection/ChronicleConnectionString.spec.ts +85 -0
  7. package/connection/ChronicleConnectionString.ts +186 -12
  8. package/connection/ChronicleTlsMaterial.spec.ts +160 -0
  9. package/connection/ChronicleTlsMaterial.ts +121 -0
  10. package/connection/CompatibilityPreflight.ts +31 -5
  11. package/connection/LeastConnectionsLoadBalancerStrategy.ts +4 -2
  12. package/connection/LoadBalancerStrategyFactory.ts +7 -2
  13. package/connection/TokenProvider.ts +4 -1
  14. package/connection/fetchOAuthAccessToken.ts +4 -2
  15. package/connection/for_ChronicleConnection/when_checking_compatibility/before_append.spec.ts +12 -1
  16. package/connection/for_ChronicleConnection/when_creating_clients/with_correlated_multi_host_callers.spec.ts +1 -1
  17. package/connection/for_ChronicleConnection/when_deferring_client_creation/and_connecting.spec.ts +1 -1
  18. package/connection/for_CompatibilityPreflight/when_verifying/with_concurrent_calls.spec.ts +2 -2
  19. package/connection/for_CompatibilityPreflight/when_verifying/with_kernel_versions.spec.ts +38 -0
  20. package/connection/for_CompatibilityPreflight/when_verifying/with_the_check_skipped.spec.ts +23 -0
  21. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -1
  22. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -1
  23. package/dist/ChronicleClient.d.ts.map +1 -1
  24. package/dist/ChronicleClient.js +2 -1
  25. package/dist/ChronicleClient.js.map +1 -1
  26. package/dist/ChronicleOptions.d.ts +18 -0
  27. package/dist/ChronicleOptions.d.ts.map +1 -1
  28. package/dist/ChronicleOptions.js +55 -23
  29. package/dist/ChronicleOptions.js.map +1 -1
  30. package/dist/connection/ChronicleConnection.d.ts +3 -0
  31. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  32. package/dist/connection/ChronicleConnection.js +21 -7
  33. package/dist/connection/ChronicleConnection.js.map +1 -1
  34. package/dist/connection/ChronicleConnectionString.d.ts +50 -1
  35. package/dist/connection/ChronicleConnectionString.d.ts.map +1 -1
  36. package/dist/connection/ChronicleConnectionString.js +154 -12
  37. package/dist/connection/ChronicleConnectionString.js.map +1 -1
  38. package/dist/connection/ChronicleTlsMaterial.d.ts +54 -0
  39. package/dist/connection/ChronicleTlsMaterial.d.ts.map +1 -0
  40. package/dist/connection/ChronicleTlsMaterial.js +88 -0
  41. package/dist/connection/ChronicleTlsMaterial.js.map +1 -0
  42. package/dist/connection/CompatibilityPreflight.d.ts +7 -1
  43. package/dist/connection/CompatibilityPreflight.d.ts.map +1 -1
  44. package/dist/connection/CompatibilityPreflight.js +24 -4
  45. package/dist/connection/CompatibilityPreflight.js.map +1 -1
  46. package/dist/connection/LeastConnectionsLoadBalancerStrategy.d.ts +2 -1
  47. package/dist/connection/LeastConnectionsLoadBalancerStrategy.d.ts.map +1 -1
  48. package/dist/connection/LeastConnectionsLoadBalancerStrategy.js +3 -2
  49. package/dist/connection/LeastConnectionsLoadBalancerStrategy.js.map +1 -1
  50. package/dist/connection/LoadBalancerStrategyFactory.d.ts +2 -1
  51. package/dist/connection/LoadBalancerStrategyFactory.d.ts.map +1 -1
  52. package/dist/connection/LoadBalancerStrategyFactory.js +3 -2
  53. package/dist/connection/LoadBalancerStrategyFactory.js.map +1 -1
  54. package/dist/connection/TokenProvider.d.ts +4 -1
  55. package/dist/connection/TokenProvider.d.ts.map +1 -1
  56. package/dist/connection/TokenProvider.js +5 -1
  57. package/dist/connection/TokenProvider.js.map +1 -1
  58. package/dist/connection/fetchOAuthAccessToken.d.ts +2 -1
  59. package/dist/connection/fetchOAuthAccessToken.d.ts.map +1 -1
  60. package/dist/connection/fetchOAuthAccessToken.js +3 -2
  61. package/dist/connection/fetchOAuthAccessToken.js.map +1 -1
  62. package/dist/eventSequences/EventSequence.d.ts +3 -0
  63. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  64. package/dist/eventSequences/EventSequence.js +12 -3
  65. package/dist/eventSequences/EventSequence.js.map +1 -1
  66. package/dist/eventSequences/IEventSequence.d.ts +2 -0
  67. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  68. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts +1 -1
  69. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts.map +1 -1
  70. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js +3 -3
  71. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js.map +1 -1
  72. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts +2 -2
  73. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts.map +1 -1
  74. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js +10 -3
  75. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js.map +1 -1
  76. package/dist/index.d.ts +1 -0
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +1 -0
  79. package/dist/index.js.map +1 -1
  80. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  81. package/dist/testing/ReactorScenario.js +0 -2
  82. package/dist/testing/ReactorScenario.js.map +1 -1
  83. package/dist/transactions/UnitOfWork.d.ts +1 -0
  84. package/dist/transactions/UnitOfWork.d.ts.map +1 -1
  85. package/dist/transactions/UnitOfWork.js +17 -11
  86. package/dist/transactions/UnitOfWork.js.map +1 -1
  87. package/dist/tsconfig.tsbuildinfo +1 -1
  88. package/eventSequences/EventSequence.ts +14 -3
  89. package/eventSequences/IEventSequence.ts +3 -0
  90. package/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.ts +3 -3
  91. package/eventSequences/ensureNamedTagBatchIsSupported.ts +11 -3
  92. package/eventSequences/for_EventSequence/when_appending_named_tags/given.fixture.ts +3 -2
  93. package/eventSequences/for_EventSequence/when_appending_named_tags/with_kernel_versions.spec.ts +92 -0
  94. package/eventSequences/for_EventSequence/when_appending_named_tags/with_registered_sources.spec.ts +28 -22
  95. package/for_ChronicleClient/connectTimeout.spec.ts +29 -0
  96. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -1
  97. package/for_ChronicleOptions/when_configuring_keep_alive/with_skip_keep_alive.spec.ts +1 -1
  98. package/for_ChronicleOptions/when_configuring_the_connect_timeout/with_connect_timeout.spec.ts +23 -0
  99. package/for_index/when_importing_connection_helpers.spec.ts +13 -0
  100. package/index.ts +1 -0
  101. package/package.json +1 -1
  102. package/patterns/for_Patterns/when_querying_through_the_connection/after_resetting_the_channel.spec.ts +1 -1
  103. package/testing/ReactorScenario.ts +0 -3
  104. package/testing/for_ReactorScenario/when_recording_side_effects/with_named_tags.spec.ts +11 -13
  105. package/transactions/UnitOfWork.ts +18 -14
  106. package/transactions/for_UnitOfWork/when_committing_events_with_named_tags.spec.ts +87 -29
@@ -122,7 +122,8 @@ export class ChronicleClient implements IChronicleClient {
122
122
  deferClientCreation: options.skipKeepAlive,
123
123
  logger: options.logger,
124
124
  maxReceiveMessageSize: options.maxReceiveMessageSize ?? undefined,
125
- maxSendMessageSize: options.maxSendMessageSize ?? undefined
125
+ maxSendMessageSize: options.maxSendMessageSize ?? undefined,
126
+ connectTimeout: options.connectTimeout
126
127
  });
127
128
 
128
129
  this._logger.info('Created Chronicle client', {
@@ -28,6 +28,7 @@ type ChronicleOptionsConstructorParams = {
28
28
  readModelNamingPolicy?: ReadModelNamingPolicy;
29
29
  maxReceiveMessageSize?: number | null;
30
30
  maxSendMessageSize?: number | null;
31
+ connectTimeout?: number;
31
32
  };
32
33
 
33
34
  type ChronicleOptionsFactoryParams = {
@@ -43,6 +44,7 @@ type ChronicleOptionsFactoryParams = {
43
44
  readModelNamingPolicy?: ReadModelNamingPolicy;
44
45
  maxReceiveMessageSize?: number | null;
45
46
  maxSendMessageSize?: number | null;
47
+ connectTimeout?: number;
46
48
  };
47
49
 
48
50
  /**
@@ -133,6 +135,13 @@ export class ChronicleOptions {
133
135
  */
134
136
  readonly maxSendMessageSize: number | null;
135
137
 
138
+ /**
139
+ * How long, in milliseconds, the client waits for the kernel to answer the compatibility check on each new
140
+ * connection. Defaults to 10 seconds. A kernel that does not answer in time fails the connection attempt,
141
+ * which is retried; the check itself is never skipped by a timeout.
142
+ */
143
+ readonly connectTimeout: number;
144
+
136
145
  private constructor(options: ChronicleOptionsConstructorParams) {
137
146
  this.connectionString = options.connectionString;
138
147
  this.skipKeepAlive = options.skipKeepAlive === true;
@@ -148,26 +157,57 @@ export class ChronicleOptions {
148
157
  this.readModelNamingPolicy = options.readModelNamingPolicy;
149
158
  this.maxReceiveMessageSize = options.maxReceiveMessageSize === undefined ? ChronicleOptions.defaultMaxMessageSize : options.maxReceiveMessageSize;
150
159
  this.maxSendMessageSize = options.maxSendMessageSize === undefined ? ChronicleOptions.defaultMaxMessageSize : options.maxSendMessageSize;
151
- const spanNames = options.telemetry?.spanNames;
152
- if (spanNames !== undefined && spanNames !== 'legacy' && spanNames !== 'convention') {
160
+ this.connectTimeout = ChronicleOptions.validConnectTimeout(options.connectTimeout ?? ChronicleOptions.defaultConnectTimeout);
161
+ ChronicleOptions.validateTelemetry(options.telemetry);
162
+ this.telemetry = options.telemetry;
163
+ this.logger = options.logger;
164
+ }
165
+
166
+ private static validConnectTimeout(connectTimeout: number): number {
167
+ // AbortSignal.timeout accepts only whole milliseconds that fit an unsigned 32-bit integer.
168
+ if (!Number.isInteger(connectTimeout) || connectTimeout <= 0 || connectTimeout > ChronicleOptions.maxConnectTimeout) {
169
+ throw new TypeError(`connectTimeout must be a whole number of milliseconds between 1 and ${ChronicleOptions.maxConnectTimeout}.`);
170
+ }
171
+ return connectTimeout;
172
+ }
173
+
174
+ private static validateTelemetry(telemetry?: ChronicleTelemetryOptions): void {
175
+ ChronicleOptions.validateSpanNames(telemetry?.spanNames);
176
+ ChronicleOptions.validateEventSourceIdPolicy(telemetry?.eventSourceId);
177
+ }
178
+
179
+ private static validateSpanNames(spanNames?: string): void {
180
+ if (spanNames !== undefined && !ChronicleOptions._spanNames.has(spanNames)) {
153
181
  throw new TypeError('telemetry.spanNames must be legacy or convention.');
154
182
  }
155
- const policy = options.telemetry?.eventSourceId;
156
- if (policy !== undefined) {
157
- if (policy?.mode !== 'raw' && policy?.mode !== 'hmac') {
158
- throw new TypeError('telemetry.eventSourceId.mode must be raw or hmac.');
159
- }
160
- if (policy.mode === 'hmac' && (!types.isUint8Array(policy.key) || policy.key.byteLength === 0)) {
161
- throw new TypeError('telemetry.eventSourceId.key must be a non-empty Uint8Array for hmac mode.');
162
- }
183
+ }
184
+
185
+ private static validateEventSourceIdPolicy(policy: ChronicleTelemetryOptions['eventSourceId']): void {
186
+ if (policy === undefined) return;
187
+ if (!ChronicleOptions._eventSourceIdModes.has(policy?.mode)) {
188
+ throw new TypeError('telemetry.eventSourceId.mode must be raw or hmac.');
189
+ }
190
+ if (policy.mode === 'hmac' && !ChronicleOptions.isNonEmptyKey(policy.key)) {
191
+ throw new TypeError('telemetry.eventSourceId.key must be a non-empty Uint8Array for hmac mode.');
163
192
  }
164
- this.telemetry = options.telemetry;
165
- this.logger = options.logger;
193
+ }
194
+
195
+ private static readonly _spanNames: ReadonlySet<unknown> = new Set(['legacy', 'convention']);
196
+ private static readonly _eventSourceIdModes: ReadonlySet<unknown> = new Set(['raw', 'hmac']);
197
+
198
+ private static isNonEmptyKey(key: unknown): boolean {
199
+ return types.isUint8Array(key) && key.byteLength > 0;
166
200
  }
167
201
 
168
202
  /** The default maximum gRPC message size in bytes: 100 MB. */
169
203
  static readonly defaultMaxMessageSize = 100 * 1024 * 1024;
170
204
 
205
+ /** The default time, in milliseconds, the client waits for the kernel's compatibility check: 10 seconds. */
206
+ static readonly defaultConnectTimeout = 10_000;
207
+
208
+ /** The longest connect timeout, in milliseconds, the client accepts: the largest unsigned 32-bit integer. */
209
+ static readonly maxConnectTimeout = 4_294_967_295;
210
+
171
211
  private static defaultDiscoveryPatterns(): string[] {
172
212
  const typescriptEntry = /\.(?:ts|tsx|mts|cts)$/i.test(process.argv[1] ?? '');
173
213
  const typescriptLoader = process.execArgv.some(arg => /(?:tsx|ts-node|--experimental-strip-types|--experimental-transform-types)/i.test(arg));
@@ -206,20 +246,22 @@ export class ChronicleOptions {
206
246
  const parsed = typeof connectionString === 'string'
207
247
  ? new ChronicleConnectionString(connectionString)
208
248
  : connectionString;
249
+ const factoryOptions: ChronicleOptionsFactoryParams = options ?? {};
209
250
  return new ChronicleOptions({
210
251
  connectionString: parsed,
211
252
  skipKeepAlive: ChronicleOptions.shouldSkipKeepAlive(parsed, options),
212
- clientArtifactsProvider: options?.clientArtifactsProvider,
213
- discoveryPatterns: options?.discoveryPatterns,
214
- defaultSinkTypeId: options?.defaultSinkTypeId,
215
- defaultGraphSinkTypeId: options?.defaultGraphSinkTypeId,
216
- reactorResultHandler: options?.reactorResultHandler,
217
- artifactActivator: options?.artifactActivator,
218
- readModelNamingPolicy: options?.readModelNamingPolicy,
219
- maxReceiveMessageSize: options?.maxReceiveMessageSize,
220
- maxSendMessageSize: options?.maxSendMessageSize,
221
- telemetry: options?.telemetry,
222
- logger: options?.logger
253
+ clientArtifactsProvider: factoryOptions.clientArtifactsProvider,
254
+ discoveryPatterns: factoryOptions.discoveryPatterns,
255
+ defaultSinkTypeId: factoryOptions.defaultSinkTypeId,
256
+ defaultGraphSinkTypeId: factoryOptions.defaultGraphSinkTypeId,
257
+ reactorResultHandler: factoryOptions.reactorResultHandler,
258
+ artifactActivator: factoryOptions.artifactActivator,
259
+ readModelNamingPolicy: factoryOptions.readModelNamingPolicy,
260
+ maxReceiveMessageSize: factoryOptions.maxReceiveMessageSize,
261
+ maxSendMessageSize: factoryOptions.maxSendMessageSize,
262
+ connectTimeout: factoryOptions.connectTimeout,
263
+ telemetry: factoryOptions.telemetry,
264
+ logger: factoryOptions.logger
223
265
  });
224
266
  }
225
267
 
package/README.md CHANGED
@@ -72,7 +72,7 @@ Chronicle decorators work with both TC39 standard decorators (TypeScript 5.2+; d
72
72
 
73
73
  Read models are inferred from `@projection('id', Model)`, `@reducer('id', sequenceId, Model)`, or an exported model with `@fromEvent(Event)` or other model-bound property mappings. Their schema comes from the model type; the default identifier is its class name. See [read models](https://github.com/Cratis/Chronicle.TypeScript/blob/main/Documentation/read-models.md) for preserving existing custom identifiers.
74
74
 
75
- Decorated artifacts register when their modules are imported. When the entry file is TypeScript (run through a loader such as `tsx`), the client also scans `**/*.ts` files by default; compiled JavaScript scans nothing unless you set `discoveryPatterns`. See [artifact discovery](https://github.com/Cratis/Chronicle.TypeScript/blob/main/Documentation/getting-started.md#artifact-discovery).
75
+ Decorated artifacts register when their modules are imported. When the process runs TypeScript (a `.ts`, `.tsx`, `.mts` or `.cts` entry file, a loader such as `tsx` or `ts-node`, Node's `--experimental-strip-types` or `--experimental-transform-types`, or Vitest), the client also scans `**/*.ts` and `**/*.tsx` files by default, excluding declaration files, specs, tests, `node_modules`, `dist` and `build`. Otherwise, as for compiled JavaScript, it scans nothing unless you set `discoveryPatterns`. See [artifact discovery](https://github.com/Cratis/Chronicle.TypeScript/blob/main/Documentation/getting-started.md#artifact-discovery).
76
76
 
77
77
  The client skips TLS certificate validation unless the connection string sets `skipTlsValidation=false` (the default stays `true` in this release; an explicit `false` requires validation). Set it for every server other than a local development kernel; the client logs a warning when it skips validation for a non-loopback host; see [Connect to Chronicle](https://github.com/Cratis/Chronicle.TypeScript/blob/main/Documentation/connecting.md).
78
78
 
@@ -27,7 +27,7 @@ async function listen(rejectAnonymous = false): Promise<number> {
27
27
  server.add(ConnectionServiceDefinition, {
28
28
  ...methods, checkCompatibility: async () => {
29
29
  if (rejectAnonymous) throw new ServerError(status.UNAUTHENTICATED, 'Unauthenticated');
30
- return { IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' };
30
+ return { IsCompatible: true, Incompatibilities: [], ServerVersion: '19.37.4' };
31
31
  }
32
32
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
33
33
  servers.push(server);
@@ -46,7 +46,7 @@ async function listenAuthenticated(onCheck?: () => void): Promise<number> {
46
46
  checkCompatibility: async (request, context) => {
47
47
  onCheck?.();
48
48
  await authenticate(request, context);
49
- return { IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' };
49
+ return { IsCompatible: true, Incompatibilities: [], ServerVersion: '19.37.4' };
50
50
  }
51
51
  } as ServiceImplementation<typeof ConnectionServiceDefinition>);
52
52
  server.add(ServerDefinition, {
@@ -195,7 +195,7 @@ describe('ChronicleConnection authentication', () => {
195
195
  const unsupported = async () => { throw new Error('Unexpected RPC'); };
196
196
  server.add(ConnectionServiceDefinition, {
197
197
  ...Object.fromEntries(Object.keys(ConnectionServiceDefinition.methods).map(name => [name, unsupported])),
198
- checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: 'test' }),
198
+ checkCompatibility: async () => ({ IsCompatible: true, Incompatibilities: [], ServerVersion: '19.37.4' }),
199
199
  observeConnectedClients: async function* () {
200
200
  attempts();
201
201
  throw new ServerError(status.UNAUTHENTICATED, 'Token expired');
@@ -42,6 +42,7 @@ import { ChronicleConnectionString, type ChronicleServerAddress } from './Chroni
42
42
  import { ChronicleServerAddressResolver } from './ChronicleServerAddressResolver.js';
43
43
  import { ChronicleServices } from './ChronicleServices.js';
44
44
  import './encodeExplicitFalse.js';
45
+ import { ChronicleTlsMaterial } from './ChronicleTlsMaterial.js';
45
46
  import { CompatibilityPreflight } from './CompatibilityPreflight.js';
46
47
  import { formatServerAddress } from './formatServerAddress.js';
47
48
  import type { ILoadBalancerStrategy } from './ILoadBalancerStrategy.js';
@@ -114,6 +115,7 @@ export class ChronicleConnection implements ChronicleServices {
114
115
  private readonly _tokenProviders = new Map<string, ITokenProvider>();
115
116
  private readonly _addressResolver: ChronicleServerAddressResolver;
116
117
  private readonly _loadBalancerStrategy: ILoadBalancerStrategy;
118
+ private readonly _tlsMaterial: ChronicleTlsMaterial;
117
119
  private _isConnected = false;
118
120
  private _warnedAboutSkippedTlsValidation = false;
119
121
  private _clientsReady?: Promise<void>;
@@ -129,12 +131,15 @@ export class ChronicleConnection implements ChronicleServices {
129
131
  this._connectionString = ChronicleConnectionString.Default;
130
132
  }
131
133
 
132
- if (!this._connectionString.apiKey && (!!this._connectionString.username !== !!this._connectionString.password)) {
134
+ if (!this._connectionString.noAuthentication && !this._connectionString.apiKey && (!!this._connectionString.username !== !!this._connectionString.password)) {
133
135
  throw new Error('Connection string must contain both username and password, or neither');
134
136
  }
135
137
 
136
138
  this._addressResolver = new ChronicleServerAddressResolver();
137
- this._loadBalancerStrategy = createLoadBalancerStrategy(this._connectionString.loadBalancer, this._connectionString.skipTlsValidation);
139
+ // Loaded once, up front: a missing or unreadable certificate file fails the connection setup here rather
140
+ // than on every reconnect - or not at all until validation is switched on.
141
+ this._tlsMaterial = this._connectionString.loadTlsMaterial();
142
+ this._loadBalancerStrategy = createLoadBalancerStrategy(this._connectionString.loadBalancer, this._connectionString.skipTlsValidation, this._tlsMaterial);
138
143
 
139
144
  if (!_options.deferClientCreation) {
140
145
  this._clientsReady = this.startClientCreation();
@@ -263,6 +268,13 @@ export class ChronicleConnection implements ChronicleServices {
263
268
  return this._connections;
264
269
  }
265
270
 
271
+ /** Gets the server version after verifying this channel's contract, or undefined when skipped. */
272
+ async getKernelVersion(): Promise<string | undefined> {
273
+ await (this._clientsReady ??= this.startClientCreation());
274
+ await this._compatibility.verify();
275
+ return this._compatibility.kernelVersion;
276
+ }
277
+
266
278
  private startClientCreation(): Promise<void> {
267
279
  return runInBackgroundContext(() => this.createClients());
268
280
  }
@@ -319,14 +331,14 @@ export class ChronicleConnection implements ChronicleServices {
319
331
  const selected = await this._loadBalancerStrategy.select(candidates);
320
332
  const serverAddress = formatServerAddress(selected);
321
333
  const tokenProvider = this.createTokenProvider(selected);
322
- const credentials = this._options.credentials ?? this._connectionString.createCredentials();
334
+ const credentials = this._options.credentials ?? this._connectionString.createCredentials(this._tlsMaterial);
323
335
 
324
336
  this._channel = createChannel(serverAddress, credentials, channelOptions);
325
337
 
326
338
  // nice-grpc invokes the last middleware first: auth retries re-enter propagation.
327
339
  const factory = createClientFactory().use(traceContextMiddleware).use(this.createAuthMiddleware(tokenProvider));
328
340
  this._connections = factory.create(ConnectionServiceDefinition, this._channel);
329
- this._compatibility = new CompatibilityPreflight(this._connections, this._options.connectTimeout ?? 10_000);
341
+ this._compatibility = new CompatibilityPreflight(this._connections, this._options.connectTimeout ?? 10_000, this._connectionString.skipCompatibilityCheck);
330
342
  const eventSequenceFactory = factory.use(this._compatibility.middleware());
331
343
  this._services = {
332
344
  eventStores: factory.create(EventStoresDefinition, this._channel),
@@ -368,7 +380,7 @@ export class ChronicleConnection implements ChronicleServices {
368
380
  const channelHosts = this._options.credentials ? [] : remoteOnly(candidateHosts);
369
381
  // OAuth token requests (every mode except an API key) always skip validation, against
370
382
  // the explicit authority when set, otherwise the selected server.
371
- const tokenHosts = this._connectionString.apiKey
383
+ const tokenHosts = this._connectionString.apiKey || this._connectionString.noAuthentication
372
384
  ? []
373
385
  : remoteOnly(this._options.authority ? [new URL(this._options.authority).hostname] : candidateHosts);
374
386
  if (channelHosts.length === 0 && tokenHosts.length === 0) return;
@@ -391,6 +403,11 @@ export class ChronicleConnection implements ChronicleServices {
391
403
  const hasUsername = !!this._connectionString.username;
392
404
  const hasApiKey = !!this._connectionString.apiKey;
393
405
 
406
+ // Asking for no authentication is deliberate and beats anything else the connection string carries.
407
+ if (this._connectionString.noAuthentication) {
408
+ return new NoOpTokenProvider();
409
+ }
410
+
394
411
  if (hasApiKey) {
395
412
  return new NoOpTokenProvider();
396
413
  }
@@ -426,7 +443,7 @@ export class ChronicleConnection implements ChronicleServices {
426
443
  const endpoint = `${scheme}://${authorityHost.includes(':') && !authorityHost.startsWith('[') ? `[${authorityHost}]` : authorityHost}:${authorityPort}/connect/token`;
427
444
  let provider = this._tokenProviders.get(endpoint);
428
445
  if (!provider) {
429
- provider = new OAuthTokenProvider(endpoint, username, password, this._connectionString.skipTlsValidation);
446
+ provider = new OAuthTokenProvider(endpoint, username, password, this._connectionString.skipTlsValidation, undefined, this._tlsMaterial);
430
447
  this._tokenProviders.set(endpoint, provider);
431
448
  }
432
449
  return provider;
@@ -456,7 +473,7 @@ export class ChronicleConnection implements ChronicleServices {
456
473
  const metadata = options.metadata ? Metadata(options.metadata) : Metadata();
457
474
  metadata.set('authorization', `Bearer ${token}`);
458
475
  options.metadata = metadata;
459
- } else if (connectionString.apiKey) {
476
+ } else if (connectionString.apiKey && !connectionString.noAuthentication) {
460
477
  const metadata = options.metadata ? Metadata(options.metadata) : Metadata();
461
478
  metadata.set('api-key', connectionString.apiKey);
462
479
  options.metadata = metadata;
@@ -177,6 +177,91 @@ describe('ChronicleConnectionStringBuilder', () => {
177
177
  });
178
178
  });
179
179
 
180
+ describe('ChronicleConnectionStringBuilder options', () => {
181
+ describe('when parsing caCertificatePath', () => {
182
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?caCertificatePath=%2Fetc%2Fca.pem');
183
+ it('should have the decoded path', () => expect(builder.caCertificatePath).toBe('/etc/ca.pem'));
184
+ });
185
+
186
+ describe('when caCertificatePath holds an at sign', () => {
187
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?caCertificatePath=%2Fhome%2Fme@corp%2Fca.pem');
188
+ it('should keep it', () => expect(builder.caCertificatePath).toBe('/home/me@corp/ca.pem'));
189
+ });
190
+
191
+ describe('when parsing auth=none together with credentials', () => {
192
+ const builder = new ChronicleConnectionStringBuilder('chronicle://user:pass@host:35000?auth=none');
193
+ it('should be flagged as no authentication', () => expect(builder.noAuthentication).toBe(true));
194
+ it('should beat the credentials', () => expect(builder.authenticationMode).toBe(AuthenticationMode.None));
195
+ });
196
+
197
+ describe('when auth=none is spelled in another case', () => {
198
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?AUTH=None');
199
+ it('should still be no authentication', () => expect(builder.noAuthentication).toBe(true));
200
+ });
201
+
202
+ describe('when there are no credentials', () => {
203
+ it('should use the development client credentials', () =>
204
+ expect(new ChronicleConnectionStringBuilder('chronicle://host:35000').authenticationMode).toBe(AuthenticationMode.ClientCredentials));
205
+ });
206
+
207
+ describe('when only a username is given', () => {
208
+ it('should throw', () =>
209
+ expect(() => new ChronicleConnectionStringBuilder('chronicle://user@host:35000').authenticationMode).toThrow());
210
+ });
211
+
212
+ describe('when parsing skipCompatibilityCheck and skipKeepAlive', () => {
213
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?skipCompatibilityCheck=true&skipKeepAlive=true');
214
+ it('should skip the compatibility check', () => expect(builder.skipCompatibilityCheck).toBe(true));
215
+ it('should skip the keep-alive', () => expect(builder.skipKeepAlive).toBe(true));
216
+ });
217
+
218
+ describe('when the new flags are absent', () => {
219
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000');
220
+ it('should not skip the compatibility check', () => expect(builder.skipCompatibilityCheck).toBe(false));
221
+ it('should not be no authentication', () => expect(builder.noAuthentication).toBe(false));
222
+ it('should have no CA certificate path', () => expect(builder.caCertificatePath).toBeUndefined());
223
+ });
224
+
225
+ describe('when a boolean option is neither true nor false', () => {
226
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?skipTlsValidation=maybe');
227
+ it('should throw naming the option', () => expect(() => builder.skipTlsValidation).toThrow(/skipTlsValidation/));
228
+ });
229
+
230
+ describe('when option names are spelled in another case', () => {
231
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?APIKEY=abc&SkipTlsValidation=false&DISABLETLS=TRUE');
232
+ it('should read the api key', () => expect(builder.apiKey).toBe('abc'));
233
+ it('should read skipTlsValidation', () => expect(builder.skipTlsValidation).toBe(false));
234
+ it('should read disableTls', () => expect(builder.disableTls).toBe(true));
235
+ });
236
+
237
+ describe('when percent-decoding option values', () => {
238
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000?apiKey=a%2Bb+c%3D');
239
+ it('should decode once and keep a literal plus', () => expect(builder.apiKey).toBe('a+b+c='));
240
+ });
241
+
242
+ describe('when user information spilled an unencoded separator into the query', () => {
243
+ it('should throw', () =>
244
+ expect(() => new ChronicleConnectionStringBuilder('chronicle://user:pa?ss@host:35000')).toThrow(/percent-encoded/));
245
+ it('should throw for an at sign in an option that cannot hold one', () =>
246
+ expect(() => new ChronicleConnectionStringBuilder('chronicle://host:35000?disableTls=x@y')).toThrow(/percent-encoded/));
247
+ });
248
+
249
+ describe('when building credentials containing reserved characters', () => {
250
+ const builder = new ChronicleConnectionStringBuilder('chronicle://host:35000');
251
+ builder.username = 'al@ice';
252
+ builder.password = 'p:ss/w?rd';
253
+ const roundTripped = new ChronicleConnectionStringBuilder(builder.build());
254
+ it('should round trip the username', () => expect(roundTripped.username).toBe('al@ice'));
255
+ it('should round trip the password', () => expect(roundTripped.password).toBe('p:ss/w?rd'));
256
+ });
257
+
258
+ describe('when round tripping every option', () => {
259
+ const original = 'chronicle://host:35000?auth=none&disableTls=true&skipCompatibilityCheck=true&skipKeepAlive=true' +
260
+ '&certificatePath=%2Fc.p12&certificatePassword=pw&caCertificatePath=%2Fca.pem&custom=value';
261
+ it('should reproduce it', () => expect(new ChronicleConnectionStringBuilder(original).build()).toBe(original));
262
+ });
263
+ });
264
+
180
265
  describe('ChronicleConnectionString', () => {
181
266
  describe('when parsing a connection string with multiple hosts', () => {
182
267
  const connectionString = new ChronicleConnectionString('chronicle://host1:35001,host2:35002');