@milaboratories/pl-client 2.16.13 → 2.16.15

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 (63) hide show
  1. package/dist/__external/.pnpm/{@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3 → @rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3}/__external/tslib/tslib.es6.cjs.map +1 -1
  2. package/dist/__external/.pnpm/{@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3 → @rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3}/__external/tslib/tslib.es6.js.map +1 -1
  3. package/dist/core/client.cjs +31 -16
  4. package/dist/core/client.cjs.map +1 -1
  5. package/dist/core/client.d.ts +3 -2
  6. package/dist/core/client.d.ts.map +1 -1
  7. package/dist/core/client.js +31 -16
  8. package/dist/core/client.js.map +1 -1
  9. package/dist/core/default_client.cjs +1 -1
  10. package/dist/core/default_client.cjs.map +1 -1
  11. package/dist/core/default_client.js +1 -1
  12. package/dist/core/default_client.js.map +1 -1
  13. package/dist/core/errors.cjs +71 -26
  14. package/dist/core/errors.cjs.map +1 -1
  15. package/dist/core/errors.d.ts +10 -3
  16. package/dist/core/errors.d.ts.map +1 -1
  17. package/dist/core/errors.js +68 -27
  18. package/dist/core/errors.js.map +1 -1
  19. package/dist/core/ll_client.cjs +48 -18
  20. package/dist/core/ll_client.cjs.map +1 -1
  21. package/dist/core/ll_client.d.ts +12 -3
  22. package/dist/core/ll_client.d.ts.map +1 -1
  23. package/dist/core/ll_client.js +49 -19
  24. package/dist/core/ll_client.js.map +1 -1
  25. package/dist/core/transaction.cjs +1 -1
  26. package/dist/core/transaction.js +1 -1
  27. package/dist/core/unauth_client.cjs +6 -2
  28. package/dist/core/unauth_client.cjs.map +1 -1
  29. package/dist/core/unauth_client.d.ts +2 -1
  30. package/dist/core/unauth_client.d.ts.map +1 -1
  31. package/dist/core/unauth_client.js +6 -2
  32. package/dist/core/unauth_client.js.map +1 -1
  33. package/dist/core/websocket_stream.cjs +23 -2
  34. package/dist/core/websocket_stream.cjs.map +1 -1
  35. package/dist/core/websocket_stream.d.ts.map +1 -1
  36. package/dist/core/websocket_stream.js +23 -2
  37. package/dist/core/websocket_stream.js.map +1 -1
  38. package/dist/index.cjs +4 -0
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/proto-rest/index.cjs +1 -1
  42. package/dist/proto-rest/index.cjs.map +1 -1
  43. package/dist/proto-rest/index.js +2 -2
  44. package/dist/proto-rest/index.js.map +1 -1
  45. package/dist/test/test_config.cjs +13 -3
  46. package/dist/test/test_config.cjs.map +1 -1
  47. package/dist/test/test_config.d.ts +4 -0
  48. package/dist/test/test_config.d.ts.map +1 -1
  49. package/dist/test/test_config.js +12 -4
  50. package/dist/test/test_config.js.map +1 -1
  51. package/package.json +10 -8
  52. package/src/core/client.ts +40 -21
  53. package/src/core/default_client.ts +1 -1
  54. package/src/core/errors.ts +61 -34
  55. package/src/core/ll_client.test.ts +18 -3
  56. package/src/core/ll_client.ts +63 -22
  57. package/src/core/unauth_client.test.ts +4 -4
  58. package/src/core/unauth_client.ts +7 -2
  59. package/src/core/websocket_stream.ts +22 -1
  60. package/src/proto-rest/index.ts +2 -2
  61. package/src/test/test_config.ts +13 -4
  62. /package/dist/__external/.pnpm/{@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3 → @rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3}/__external/tslib/tslib.es6.cjs +0 -0
  63. /package/dist/__external/.pnpm/{@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3 → @rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3}/__external/tslib/tslib.es6.js +0 -0
@@ -9,7 +9,7 @@ import { inferAuthRefreshTime } from './auth.js';
9
9
  import { defaultHttpDispatcher } from '@milaboratories/pl-http';
10
10
  import { parseHttpAuth } from '@milaboratories/pl-model-common';
11
11
  import { createClient, parseResponseError } from '../proto-rest/index.js';
12
- import { notEmpty } from '@milaboratories/ts-helpers';
12
+ import { notEmpty, retry, withTimeout } from '@milaboratories/ts-helpers';
13
13
  import { Code } from '../proto-grpc/google/rpc/code.js';
14
14
  import { WebSocketBiDiStream } from './websocket_stream.js';
15
15
  import { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js';
@@ -33,8 +33,8 @@ class WireClientProviderImpl {
33
33
  }
34
34
  /** Abstract out low level networking and authorization details */
35
35
  class LLPlClient {
36
- ops;
37
36
  conf;
37
+ ops;
38
38
  /** Initial authorization information */
39
39
  authInformation;
40
40
  /** Will be executed by the client when it is required */
@@ -47,7 +47,7 @@ class LLPlClient {
47
47
  refreshTimestamp;
48
48
  _status = 'OK';
49
49
  statusListener;
50
- _wireProto = undefined;
50
+ _wireProto = 'grpc';
51
51
  _wireConn;
52
52
  _restInterceptors;
53
53
  _restMiddlewares;
@@ -55,11 +55,15 @@ class LLPlClient {
55
55
  providers = [];
56
56
  clientProvider;
57
57
  httpDispatcher;
58
- constructor(configOrAddress, ops = {}) {
58
+ static async build(configOrAddress, ops = {}) {
59
+ const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;
60
+ const pl = new LLPlClient(conf, ops);
61
+ await pl.detectOptimalWireProtocol();
62
+ return pl;
63
+ }
64
+ constructor(conf, ops = {}) {
65
+ this.conf = conf;
59
66
  this.ops = ops;
60
- this.conf = typeof configOrAddress === 'string'
61
- ? plAddressToConfig(configOrAddress)
62
- : configOrAddress;
63
67
  const { auth, statusListener } = ops;
64
68
  if (auth !== undefined) {
65
69
  this.refreshTimestamp = inferAuthRefreshTime(auth.authInformation, this.conf.authMaxRefreshSeconds);
@@ -79,7 +83,10 @@ class LLPlClient {
79
83
  this._restMiddlewares.push(this.createRestErrorMiddleware());
80
84
  this._grpcInterceptors.push(this.createGrpcErrorInterceptor());
81
85
  this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);
82
- this.initWireConnection();
86
+ if (this.conf.wireProtocol) {
87
+ this._wireProto = this.conf.wireProtocol;
88
+ }
89
+ this.initWireConnection(this._wireProto);
83
90
  if (statusListener !== undefined) {
84
91
  this.statusListener = statusListener;
85
92
  statusListener(this._status);
@@ -98,12 +105,8 @@ class LLPlClient {
98
105
  }
99
106
  });
100
107
  }
101
- initWireConnection() {
102
- if (this._wireProto === undefined) {
103
- // TODO: implement automatic server mode detection
104
- this._wireProto = this.conf.wireProtocol ?? 'grpc';
105
- }
106
- switch (this._wireProto) {
108
+ initWireConnection(protocol) {
109
+ switch (protocol) {
107
110
  case 'rest':
108
111
  this.initRestConnection();
109
112
  return;
@@ -113,7 +116,7 @@ class LLPlClient {
113
116
  default:
114
117
  ((v) => {
115
118
  throw new Error(`Unsupported wire protocol '${v}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);
116
- })(this._wireProto);
119
+ })(protocol);
117
120
  }
118
121
  }
119
122
  initRestConnection() {
@@ -170,6 +173,7 @@ class LLPlClient {
170
173
  _replaceWireConnection(newConn) {
171
174
  const oldConn = this._wireConn;
172
175
  this._wireConn = newConn;
176
+ this._wireProto = newConn.type;
173
177
  // Reset all providers to let them reinitialize their clients
174
178
  for (let i = 0; i < this.providers.length; i++) {
175
179
  const provider = this.providers[i].deref();
@@ -213,6 +217,9 @@ class LLPlClient {
213
217
  get wireConnection() {
214
218
  return this._wireConn;
215
219
  }
220
+ get wireProtocol() {
221
+ return this._wireProto;
222
+ }
216
223
  /** Returns true if client is authenticated. Even with anonymous auth information
217
224
  * connection is considered authenticated. Unauthenticated clients are used for
218
225
  * login and similar tasks, see {@link UnauthenticatedPlClient}. */
@@ -364,7 +371,7 @@ class LLPlClient {
364
371
  body: { expiration: `${ttlSeconds}s` },
365
372
  headers,
366
373
  });
367
- return notEmpty((await resp).data).token;
374
+ return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;
368
375
  }
369
376
  }
370
377
  async ping() {
@@ -373,16 +380,39 @@ class LLPlClient {
373
380
  return (await cl.ping({})).response;
374
381
  }
375
382
  else {
376
- return notEmpty((await cl.GET('/v1/ping')).data);
383
+ return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');
377
384
  }
378
385
  }
386
+ /**
387
+ * Detects the best available wire protocol.
388
+ * If wireProtocol is explicitly configured, does nothing.
389
+ * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.
390
+ */
391
+ async detectOptimalWireProtocol() {
392
+ if (this.conf.wireProtocol) {
393
+ return;
394
+ }
395
+ const retryOptions = {
396
+ type: 'exponentialBackoff',
397
+ maxAttempts: 80,
398
+ initialDelay: 30,
399
+ backoffMultiplier: 1.3,
400
+ jitter: 0.2,
401
+ maxDelay: 500,
402
+ };
403
+ await retry(() => withTimeout(this.ping(), 500), retryOptions, () => {
404
+ const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';
405
+ this.initWireConnection(protocol);
406
+ return true;
407
+ });
408
+ }
379
409
  async license() {
380
410
  const cl = this.clientProvider.get();
381
411
  if (cl instanceof PlatformClient) {
382
412
  return (await cl.license({})).response;
383
413
  }
384
414
  else {
385
- const resp = notEmpty((await cl.GET('/v1/license')).data);
415
+ const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');
386
416
  return {
387
417
  status: resp.status,
388
418
  isOk: resp.isOk,
@@ -396,7 +426,7 @@ class LLPlClient {
396
426
  return (await cl.authMethods({})).response;
397
427
  }
398
428
  else {
399
- return notEmpty((await cl.GET('/v1/auth/methods')).data);
429
+ return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');
400
430
  }
401
431
  }
402
432
  async txSync(txId) {
@@ -1 +1 @@
1
- {"version":3,"file":"ll_client.js","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n public readonly conf: PlClientConfig;\n\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol | undefined = undefined;\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n constructor(\n configOrAddress: PlClientConfig | string,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n this.conf = typeof configOrAddress === 'string'\n ? plAddressToConfig(configOrAddress)\n : configOrAddress;\n\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n\n this.initWireConnection();\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection() {\n if (this._wireProto === undefined) {\n // TODO: implement automatic server mode detection\n this._wireProto = this.conf.wireProtocol ?? 'grpc';\n }\n\n switch (this._wireProto) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(this._wireProto);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data).token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data);\n }\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data);\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data);\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["GrpcPlApiClient","status","GrpcStatus"],"mappings":";;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAA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I,CAAC,IAAI,CAAC,WAAW,WAAW;AAE5C,gBAAA,OAAO,IAAI,mBAAmB,CAAC,KAAK,EAClC,CAAC,GAAG,KAAK,mBAAmB,CAAC,QAAQ,CAAC,GAAG,CAAC,EAC1C,CAAC,IAAI,KAAK,mBAAmB,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,EAC9D;AACE,oBAAA,WAAW,EAAE,gBAAgB;AAC7B,oBAAA,QAAQ,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ;oBACxC,UAAU,EAAE,QAAQ,CAAC,UAAU;AAE/B,oBAAA,UAAU,EAAE,OAAO,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;;AAEjD,wBAAA,SAAS,EAAE,CAAC;wBACZ,OAAO,EAAE,EAAE,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,EAAE,EAAE;qBACvD,CAAC;AACH,iBAAA,CACF;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,iDAAA,EAAoD,IAAI,CAAC,UAAU,CAAA,CAAE,CAAC;AACxF,QAAA,CAAC,CAAC;IACJ;;AAGO,IAAA,MAAM,KAAK,GAAA;QAChB,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,KAAK,MAAM,EAAE;AACvC,YAAA,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,EAAE;QACvC;AAGA,QAAA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IACrC;AACD;;;;"}
1
+ {"version":3,"file":"ll_client.js","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty, retry, withTimeout, type RetryOptions } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = 'grpc';\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n await pl.detectOptimalWireProtocol();\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');\n }\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n const retryOptions: RetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: 80,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n await retry(\n () => withTimeout(this.ping(), 500),\n retryOptions,\n () => {\n const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';\n this.initWireConnection(protocol);\n return true;\n });\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["GrpcPlApiClient","status","GrpcStatus"],"mappings":";;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAAA,iBAAiB,GAAjB,iBAAiB;IAAyC;IAEjI,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;IACzB;IAEO,GAAG,GAAA;AACR,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;AAC3B,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,MAAM;IACpB;AACD;AAED;MACa,UAAU,CAAA;AA2CH,IAAA,IAAA;AACC,IAAA,GAAA;;AA1CX,IAAA,eAAe;;AAEN,IAAA,YAAY;;AAEZ,IAAA,WAAW;;AAEX,IAAA,oBAAoB;;AAE7B,IAAA,gBAAgB;IAEhB,OAAO,GAAuB,IAAI;AACzB,IAAA,cAAc;IAEvB,UAAU,GAAiB,MAAM;AACjC,IAAA,SAAS;AAEA,IAAA,iBAAiB;AACjB,IAAA,gBAAgB;AAChB,IAAA,iBAAiB;IACjB,SAAS,GAA2C,EAAE;AAEvD,IAAA,cAAc;AAEd,IAAA,cAAc;IAEvB,aAAa,KAAK,CACvB,eAAwC,EACxC,MAII,EAAE,EAAA;AAEN,QAAA,MAAM,IAAI,GAAG,OAAO,eAAe,KAAK,QAAQ,GAAG,iBAAiB,CAAC,eAAe,CAAC,GAAG,eAAe;QAEvG,MAAM,EAAE,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_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.cjs');
3
+ var tslib_es6 = require('../__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.cjs');
4
4
  var types = require('./types.cjs');
5
5
  var api = require('../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs');
6
6
  var util = require('../util/util.cjs');
@@ -1,4 +1,4 @@
1
- import { __esDecorate, __runInitializers } from '../__external/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.js';
1
+ import { __esDecorate, __runInitializers } from '../__external/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.52.4_tslib@2.8.1_typescript@5.6.3/__external/tslib/tslib.es6.js';
2
2
  import { ensureResourceIdNotNull, isLocalResourceId, extractBasicResourceData, createLocalResourceId, MaxTxId, isNullResourceId } from './types.js';
3
3
  import { TxAPI_Open_Request_WritableTx } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js';
4
4
  import { toBytes } from '../util/util.js';
@@ -7,8 +7,12 @@ var errors = require('./errors.cjs');
7
7
  /** Primarily used for initial authentication (login) */
8
8
  class UnauthenticatedPlClient {
9
9
  ll;
10
- constructor(configOrAddress) {
11
- this.ll = new ll_client.LLPlClient(configOrAddress);
10
+ constructor(ll) {
11
+ this.ll = ll;
12
+ }
13
+ static async build(configOrAddress) {
14
+ const ll = await ll_client.LLPlClient.build(configOrAddress);
15
+ return new UnauthenticatedPlClient(ll);
12
16
  }
13
17
  async ping() {
14
18
  return await this.ll.ping();
@@ -1 +1 @@
1
- {"version":3,"file":"unauth_client.cjs","sources":["../../src/core/unauth_client.ts"],"sourcesContent":["import type { AuthInformation, PlClientConfig } from './config';\nimport type {\n AuthAPI_ListMethods_Response,\n MaintenanceAPI_Ping_Response,\n} from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { LLPlClient } from './ll_client';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedError } from './errors';\n\n/** Primarily used for initial authentication (login) */\nexport class UnauthenticatedPlClient {\n public readonly ll: LLPlClient;\n\n constructor(configOrAddress: PlClientConfig | string) {\n this.ll = new LLPlClient(configOrAddress);\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async authMethods(): Promise<AuthAPI_ListMethods_Response> {\n return await this.ll.authMethods();\n }\n\n public async requireAuth(): Promise<boolean> {\n return (await this.authMethods()).methods.length > 0;\n }\n\n public async login(user: string, password: string): Promise<AuthInformation> {\n try {\n const token = await this.ll.getJwtToken(\n BigInt(this.ll.conf.authTTLSeconds),\n { authorization: 'Basic ' + Buffer.from(user + ':' + password).toString('base64') },\n );\n const jwtToken = notEmpty(token);\n if (jwtToken === '') throw new Error('empty token');\n return { jwtToken };\n } catch (e: any) {\n if (e.code === 'UNAUTHENTICATED') throw new UnauthenticatedError(e.message);\n throw new Error(e);\n }\n }\n}\n"],"names":["LLPlClient","notEmpty","UnauthenticatedError"],"mappings":";;;;;;AASA;MACa,uBAAuB,CAAA;AAClB,IAAA,EAAE;AAElB,IAAA,WAAA,CAAY,eAAwC,EAAA;QAClD,IAAI,CAAC,EAAE,GAAG,IAAIA,oBAAU,CAAC,eAAe,CAAC;IAC3C;AAEO,IAAA,MAAM,IAAI,GAAA;AACf,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE;IAC7B;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,EAAE;IACpC;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC;IACtD;AAEO,IAAA,MAAM,KAAK,CAAC,IAAY,EAAE,QAAgB,EAAA;AAC/C,QAAA,IAAI;AACF,YAAA,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,CACrC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,EACnC,EAAE,aAAa,EAAE,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CACpF;AACD,YAAA,MAAM,QAAQ,GAAGC,kBAAQ,CAAC,KAAK,CAAC;YAChC,IAAI,QAAQ,KAAK,EAAE;AAAE,gBAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC;YACnD,OAAO,EAAE,QAAQ,EAAE;QACrB;QAAE,OAAO,CAAM,EAAE;AACf,YAAA,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB;AAAE,gBAAA,MAAM,IAAIC,2BAAoB,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3E,YAAA,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC;QACpB;IACF;AACD;;;;"}
1
+ {"version":3,"file":"unauth_client.cjs","sources":["../../src/core/unauth_client.ts"],"sourcesContent":["import type { AuthInformation, PlClientConfig } from './config';\nimport type {\n AuthAPI_ListMethods_Response,\n MaintenanceAPI_Ping_Response,\n} from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { LLPlClient } from './ll_client';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedError } from './errors';\n\n/** Primarily used for initial authentication (login) */\nexport class UnauthenticatedPlClient {\n public readonly ll: LLPlClient;\n\n private constructor(ll: LLPlClient) {\n this.ll = ll;\n }\n\n public static async build(configOrAddress: PlClientConfig | string): Promise<UnauthenticatedPlClient> {\n const ll = await LLPlClient.build(configOrAddress);\n return new UnauthenticatedPlClient(ll);\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async authMethods(): Promise<AuthAPI_ListMethods_Response> {\n return await this.ll.authMethods();\n }\n\n public async requireAuth(): Promise<boolean> {\n return (await this.authMethods()).methods.length > 0;\n }\n\n public async login(user: string, password: string): Promise<AuthInformation> {\n try {\n const token = await this.ll.getJwtToken(\n BigInt(this.ll.conf.authTTLSeconds),\n { authorization: 'Basic ' + Buffer.from(user + ':' + password).toString('base64') },\n );\n const jwtToken = notEmpty(token);\n if (jwtToken === '') throw new Error('empty token');\n return { jwtToken };\n } catch (e: any) {\n if (e.code === 'UNAUTHENTICATED') throw new UnauthenticatedError(e.message);\n throw new Error(e);\n }\n }\n}\n"],"names":["LLPlClient","notEmpty","UnauthenticatedError"],"mappings":";;;;;;AASA;MACa,uBAAuB,CAAA;AAClB,IAAA,EAAE;AAElB,IAAA,WAAA,CAAoB,EAAc,EAAA;AAChC,QAAA,IAAI,CAAC,EAAE,GAAG,EAAE;IACd;AAEO,IAAA,aAAa,KAAK,CAAC,eAAwC,EAAA;QAChE,MAAM,EAAE,GAAG,MAAMA,oBAAU,CAAC,KAAK,CAAC,eAAe,CAAC;AAClD,QAAA,OAAO,IAAI,uBAAuB,CAAC,EAAE,CAAC;IACxC;AAEO,IAAA,MAAM,IAAI,GAAA;AACf,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE;IAC7B;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,EAAE;IACpC;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC;IACtD;AAEO,IAAA,MAAM,KAAK,CAAC,IAAY,EAAE,QAAgB,EAAA;AAC/C,QAAA,IAAI;AACF,YAAA,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,CACrC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,EACnC,EAAE,aAAa,EAAE,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CACpF;AACD,YAAA,MAAM,QAAQ,GAAGC,kBAAQ,CAAC,KAAK,CAAC;YAChC,IAAI,QAAQ,KAAK,EAAE;AAAE,gBAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC;YACnD,OAAO,EAAE,QAAQ,EAAE;QACrB;QAAE,OAAO,CAAM,EAAE;AACf,YAAA,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB;AAAE,gBAAA,MAAM,IAAIC,2BAAoB,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3E,YAAA,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC;QACpB;IACF;AACD;;;;"}
@@ -4,7 +4,8 @@ import { LLPlClient } from './ll_client';
4
4
  /** Primarily used for initial authentication (login) */
5
5
  export declare class UnauthenticatedPlClient {
6
6
  readonly ll: LLPlClient;
7
- constructor(configOrAddress: PlClientConfig | string);
7
+ private constructor();
8
+ static build(configOrAddress: PlClientConfig | string): Promise<UnauthenticatedPlClient>;
8
9
  ping(): Promise<MaintenanceAPI_Ping_Response>;
9
10
  authMethods(): Promise<AuthAPI_ListMethods_Response>;
10
11
  requireAuth(): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"unauth_client.d.ts","sourceRoot":"","sources":["../../src/core/unauth_client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,KAAK,EACV,4BAA4B,EAC5B,4BAA4B,EAC7B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,wDAAwD;AACxD,qBAAa,uBAAuB;IAClC,SAAgB,EAAE,EAAE,UAAU,CAAC;gBAEnB,eAAe,EAAE,cAAc,GAAG,MAAM;IAIvC,IAAI,IAAI,OAAO,CAAC,4BAA4B,CAAC;IAI7C,WAAW,IAAI,OAAO,CAAC,4BAA4B,CAAC;IAIpD,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAI/B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;CAc7E"}
1
+ {"version":3,"file":"unauth_client.d.ts","sourceRoot":"","sources":["../../src/core/unauth_client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,KAAK,EACV,4BAA4B,EAC5B,4BAA4B,EAC7B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,wDAAwD;AACxD,qBAAa,uBAAuB;IAClC,SAAgB,EAAE,EAAE,UAAU,CAAC;IAE/B,OAAO;WAIa,KAAK,CAAC,eAAe,EAAE,cAAc,GAAG,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAKxF,IAAI,IAAI,OAAO,CAAC,4BAA4B,CAAC;IAI7C,WAAW,IAAI,OAAO,CAAC,4BAA4B,CAAC;IAIpD,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAI/B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;CAc7E"}
@@ -5,8 +5,12 @@ import { UnauthenticatedError } from './errors.js';
5
5
  /** Primarily used for initial authentication (login) */
6
6
  class UnauthenticatedPlClient {
7
7
  ll;
8
- constructor(configOrAddress) {
9
- this.ll = new LLPlClient(configOrAddress);
8
+ constructor(ll) {
9
+ this.ll = ll;
10
+ }
11
+ static async build(configOrAddress) {
12
+ const ll = await LLPlClient.build(configOrAddress);
13
+ return new UnauthenticatedPlClient(ll);
10
14
  }
11
15
  async ping() {
12
16
  return await this.ll.ping();
@@ -1 +1 @@
1
- {"version":3,"file":"unauth_client.js","sources":["../../src/core/unauth_client.ts"],"sourcesContent":["import type { AuthInformation, PlClientConfig } from './config';\nimport type {\n AuthAPI_ListMethods_Response,\n MaintenanceAPI_Ping_Response,\n} from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { LLPlClient } from './ll_client';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedError } from './errors';\n\n/** Primarily used for initial authentication (login) */\nexport class UnauthenticatedPlClient {\n public readonly ll: LLPlClient;\n\n constructor(configOrAddress: PlClientConfig | string) {\n this.ll = new LLPlClient(configOrAddress);\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async authMethods(): Promise<AuthAPI_ListMethods_Response> {\n return await this.ll.authMethods();\n }\n\n public async requireAuth(): Promise<boolean> {\n return (await this.authMethods()).methods.length > 0;\n }\n\n public async login(user: string, password: string): Promise<AuthInformation> {\n try {\n const token = await this.ll.getJwtToken(\n BigInt(this.ll.conf.authTTLSeconds),\n { authorization: 'Basic ' + Buffer.from(user + ':' + password).toString('base64') },\n );\n const jwtToken = notEmpty(token);\n if (jwtToken === '') throw new Error('empty token');\n return { jwtToken };\n } catch (e: any) {\n if (e.code === 'UNAUTHENTICATED') throw new UnauthenticatedError(e.message);\n throw new Error(e);\n }\n }\n}\n"],"names":[],"mappings":";;;;AASA;MACa,uBAAuB,CAAA;AAClB,IAAA,EAAE;AAElB,IAAA,WAAA,CAAY,eAAwC,EAAA;QAClD,IAAI,CAAC,EAAE,GAAG,IAAI,UAAU,CAAC,eAAe,CAAC;IAC3C;AAEO,IAAA,MAAM,IAAI,GAAA;AACf,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE;IAC7B;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,EAAE;IACpC;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC;IACtD;AAEO,IAAA,MAAM,KAAK,CAAC,IAAY,EAAE,QAAgB,EAAA;AAC/C,QAAA,IAAI;AACF,YAAA,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,CACrC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,EACnC,EAAE,aAAa,EAAE,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CACpF;AACD,YAAA,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC;YAChC,IAAI,QAAQ,KAAK,EAAE;AAAE,gBAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC;YACnD,OAAO,EAAE,QAAQ,EAAE;QACrB;QAAE,OAAO,CAAM,EAAE;AACf,YAAA,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB;AAAE,gBAAA,MAAM,IAAI,oBAAoB,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3E,YAAA,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC;QACpB;IACF;AACD;;;;"}
1
+ {"version":3,"file":"unauth_client.js","sources":["../../src/core/unauth_client.ts"],"sourcesContent":["import type { AuthInformation, PlClientConfig } from './config';\nimport type {\n AuthAPI_ListMethods_Response,\n MaintenanceAPI_Ping_Response,\n} from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { LLPlClient } from './ll_client';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedError } from './errors';\n\n/** Primarily used for initial authentication (login) */\nexport class UnauthenticatedPlClient {\n public readonly ll: LLPlClient;\n\n private constructor(ll: LLPlClient) {\n this.ll = ll;\n }\n\n public static async build(configOrAddress: PlClientConfig | string): Promise<UnauthenticatedPlClient> {\n const ll = await LLPlClient.build(configOrAddress);\n return new UnauthenticatedPlClient(ll);\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async authMethods(): Promise<AuthAPI_ListMethods_Response> {\n return await this.ll.authMethods();\n }\n\n public async requireAuth(): Promise<boolean> {\n return (await this.authMethods()).methods.length > 0;\n }\n\n public async login(user: string, password: string): Promise<AuthInformation> {\n try {\n const token = await this.ll.getJwtToken(\n BigInt(this.ll.conf.authTTLSeconds),\n { authorization: 'Basic ' + Buffer.from(user + ':' + password).toString('base64') },\n );\n const jwtToken = notEmpty(token);\n if (jwtToken === '') throw new Error('empty token');\n return { jwtToken };\n } catch (e: any) {\n if (e.code === 'UNAUTHENTICATED') throw new UnauthenticatedError(e.message);\n throw new Error(e);\n }\n }\n}\n"],"names":[],"mappings":";;;;AASA;MACa,uBAAuB,CAAA;AAClB,IAAA,EAAE;AAElB,IAAA,WAAA,CAAoB,EAAc,EAAA;AAChC,QAAA,IAAI,CAAC,EAAE,GAAG,EAAE;IACd;AAEO,IAAA,aAAa,KAAK,CAAC,eAAwC,EAAA;QAChE,MAAM,EAAE,GAAG,MAAM,UAAU,CAAC,KAAK,CAAC,eAAe,CAAC;AAClD,QAAA,OAAO,IAAI,uBAAuB,CAAC,EAAE,CAAC;IACxC;AAEO,IAAA,MAAM,IAAI,GAAA;AACf,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE;IAC7B;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,EAAE;IACpC;AAEO,IAAA,MAAM,WAAW,GAAA;AACtB,QAAA,OAAO,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC;IACtD;AAEO,IAAA,MAAM,KAAK,CAAC,IAAY,EAAE,QAAgB,EAAA;AAC/C,QAAA,IAAI;AACF,YAAA,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,WAAW,CACrC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,EACnC,EAAE,aAAa,EAAE,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CACpF;AACD,YAAA,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC;YAChC,IAAI,QAAQ,KAAK,EAAE;AAAE,gBAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC;YACnD,OAAO,EAAE,QAAQ,EAAE;QACrB;QAAE,OAAO,CAAM,EAAE;AACf,YAAA,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB;AAAE,gBAAA,MAAM,IAAI,oBAAoB,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3E,YAAA,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC;QACpB;IACF;AACD;;;;"}
@@ -3,6 +3,7 @@
3
3
  var undici = require('undici');
4
4
  var Denque = require('denque');
5
5
  var retry_strategy = require('../helpers/retry_strategy.cjs');
6
+ var errors = require('./errors.cjs');
6
7
 
7
8
  var ConnectionState;
8
9
  (function (ConnectionState) {
@@ -144,6 +145,19 @@ class WebSocketBiDiStream {
144
145
  }
145
146
  onClose() {
146
147
  this.progressConnectionState(ConnectionState.CLOSED);
148
+ // If abort signal was triggered, use that as the error source
149
+ if (this.options.abortSignal?.aborted && !this.lastError) {
150
+ const reason = this.options.abortSignal.reason;
151
+ if (reason instanceof Error) {
152
+ this.lastError = reason;
153
+ }
154
+ else if (reason !== undefined) {
155
+ this.lastError = new Error(String(reason), { cause: reason });
156
+ }
157
+ else {
158
+ this.lastError = this.createStreamClosedError();
159
+ }
160
+ }
147
161
  if (!this.lastError) {
148
162
  this.rejectAllSendOperations(this.createStreamClosedError());
149
163
  this.resolveAllPendingResponses(); // unblock active async iterator
@@ -307,8 +321,15 @@ class WebSocketBiDiStream {
307
321
  toError(error) {
308
322
  if (error instanceof Error)
309
323
  return error;
310
- if (error instanceof undici.ErrorEvent)
311
- return error.error;
324
+ if (error instanceof undici.ErrorEvent) {
325
+ const err = error.error;
326
+ // undici WebSocket throws TypeError with empty message on socket close
327
+ // (e.g., when connection is lost or server disconnects)
328
+ if (err instanceof TypeError && !err.message) {
329
+ return new errors.DisconnectedError('WebSocket connection closed unexpectedly');
330
+ }
331
+ return err instanceof Error ? err : new Error('WebSocket error', { cause: error });
332
+ }
312
333
  return new Error(String(error));
313
334
  }
314
335
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"websocket_stream.cjs","sources":["../../src/core/websocket_stream.ts"],"sourcesContent":["import { WebSocket, type WebSocketInit, type Dispatcher, ErrorEvent } from 'undici';\nimport type { BiDiStream } from './abstract_stream';\nimport Denque from 'denque';\nimport type { RetryConfig } from '../helpers/retry_strategy';\nimport { RetryStrategy } from '../helpers/retry_strategy';\n\ninterface QueuedMessage<InType extends object> {\n message: InType;\n resolve: () => void;\n reject: (error: Error) => void;\n}\n\ninterface ResponseResolver<OutType extends object> {\n resolve: (value: IteratorResult<OutType>) => void;\n reject: (error: Error) => void;\n}\n\nenum ConnectionState {\n NEW = 0,\n CONNECTING = 1,\n CONNECTED = 2,\n CLOSING = 3,\n CLOSED = 4,\n}\n\nexport type WSStreamOptions<ClientMsg extends object, ServerMsg extends object> = {\n abortSignal?: AbortSignal;\n\n dispatcher?: Dispatcher;\n jwtToken?: string;\n retryConfig?: Partial<RetryConfig>;\n\n onComplete?: (stream: WebSocketBiDiStream<ClientMsg, ServerMsg>) => void | Promise<void>;\n};\n\n/**\n * WebSocket-based bidirectional stream implementation for LLTransaction.\n * Implements BiDiStream interface which is compatible with DuplexStreamingCall.\n */\nexport class WebSocketBiDiStream<ClientMsg extends object, ServerMsg extends object> implements BiDiStream<ClientMsg, ServerMsg> {\n // Connection\n private ws: WebSocket | null = null;\n private connectionState: ConnectionState = ConnectionState.NEW;\n private readonly reconnection: RetryStrategy;\n\n // Send management\n private readonly sendQueue = new Denque<QueuedMessage<ClientMsg>>();\n private sendCompleted = false;\n private readonly onComplete: (stream: WebSocketBiDiStream<ClientMsg, ServerMsg>) => void | Promise<void>;\n\n // Response management\n private readonly responseQueue = new Denque<ServerMsg>();\n private responseResolvers: ResponseResolver<ServerMsg>[] = [];\n\n // Error tracking\n private lastError?: Error;\n\n // === Public API ===\n\n public readonly requests = {\n send: async (message: ClientMsg): Promise<void> => {\n return await this.enqueueSend(message);\n },\n\n complete: async (): Promise<void> => {\n if (this.sendCompleted) return;\n\n await this.drainSendQueue(); // ensure we sent all already queued messages before closing the stream\n try {\n await this.onComplete(this); // custom onComplete may send additional messages\n } catch (_: unknown) {\n // When 'complete' gets called concurrently with connection break or over a broken\n // transaction stream (server decided it should drop transaction), server would close\n // connection anyway on its end. We can safely ignore error here and just continue working.\n }\n this.sendCompleted = true;\n },\n };\n\n public readonly responses: AsyncIterable<ServerMsg> = {\n [Symbol.asyncIterator]: () => this.createResponseIterator(),\n };\n\n public close(): void {\n this.reconnection.cancel();\n\n if (this.connectionState < ConnectionState.CONNECTED) {\n // Never reached CONNECTED state. ws.close() will never trigger 'close' event.\n this.ws?.close();\n this.onClose();\n return;\n }\n\n if (!this.progressConnectionState(ConnectionState.CLOSING)) return;\n this.ws!.close();\n }\n\n constructor(\n private readonly url: string,\n private readonly serializeClientMessage: (message: ClientMsg) => Uint8Array,\n private readonly parseServerMessage: (data: Uint8Array) => ServerMsg,\n private readonly options: WSStreamOptions<ClientMsg, ServerMsg> = {},\n ) {\n this.onComplete = this.options.onComplete ?? ((stream) => stream.close());\n\n const retryConfig = this.options.retryConfig ?? {};\n this.reconnection = new RetryStrategy(retryConfig, {\n onRetry: () => { void this.connect(); },\n onMaxAttemptsReached: (error) => this.handleError(error),\n });\n\n if (this.options.abortSignal?.aborted) {\n this.progressConnectionState(ConnectionState.CLOSED);\n return;\n }\n\n this.options.abortSignal?.addEventListener('abort', () => this.close());\n this.connect();\n }\n\n // === Connection Lifecycle ===\n\n private connect(): void {\n if (this.options.abortSignal?.aborted) return;\n\n // Prevent reconnecting after first successful connection.\n if (!this.progressConnectionState(ConnectionState.CONNECTING)) return;\n\n try {\n this.ws = this.createWebSocket();\n\n this.ws.addEventListener('open', () => this.onOpen());\n this.ws.addEventListener('message', (event) => this.onMessage(event.data));\n this.ws.addEventListener('error', (error) => this.onError(error));\n this.ws.addEventListener('close', () => this.onClose());\n } catch (error) {\n this.lastError = this.toError(error);\n this.reconnection.schedule();\n }\n }\n\n private createWebSocket(): WebSocket {\n const options: WebSocketInit = {};\n\n if (this.options.jwtToken) options.headers = { authorization: `Bearer ${this.options.jwtToken}` };\n if (this.options.dispatcher) options.dispatcher = this.options.dispatcher;\n\n const ws = new WebSocket(this.url, options);\n ws.binaryType = 'arraybuffer';\n return ws;\n }\n\n private onOpen(): void {\n this.progressConnectionState(ConnectionState.CONNECTED);\n this.processSendQueue();\n }\n\n private onMessage(data: unknown): void {\n if (!(data instanceof ArrayBuffer)) {\n this.handleError(new Error(`Unexpected WS message format: ${typeof data}`));\n return;\n }\n\n try {\n const message = this.parseServerMessage(new Uint8Array(data));\n this.deliverResponse(message);\n } catch (error) {\n this.handleError(this.toError(error));\n }\n }\n\n private onError(error: unknown): void {\n if (this.connectionState < ConnectionState.CONNECTED) {\n // Try to connect several times until we succeed or run out of attempts.\n this.lastError = this.toError(error);\n this.reconnection.schedule();\n return;\n }\n\n this.handleError(this.toError(error));\n }\n\n private onClose(): void {\n this.progressConnectionState(ConnectionState.CLOSED);\n\n if (!this.lastError) {\n this.rejectAllSendOperations(this.createStreamClosedError());\n this.resolveAllPendingResponses(); // unblock active async iterator\n } else {\n this.rejectAllPendingOperations(this.lastError);\n }\n }\n\n // === Send Queue Management ===\n\n private enqueueSend(message: ClientMsg): Promise<void> {\n if (this.sendCompleted) {\n throw new Error('Cannot send: stream already completed');\n }\n\n if (this.options.abortSignal?.aborted) {\n throw new Error('Cannot send: stream aborted');\n }\n\n return new Promise<void>((resolve, reject) => {\n this.sendQueue.push({ message, resolve, reject });\n this.processSendQueue();\n });\n }\n\n private processSendQueue(): void {\n if (!this.canSendMessages()) return;\n\n while (this.sendQueue.length > 0) {\n const queued = this.sendQueue.shift()!;\n this.sendQueuedMessage(queued);\n }\n }\n\n private canSendMessages(): boolean {\n return this.connectionState === ConnectionState.CONNECTED;\n }\n\n private sendQueuedMessage(queued: QueuedMessage<ClientMsg>): void {\n try {\n const ws = this.ws;\n if (!ws) {\n throw new Error('WebSocket is not connected');\n }\n\n // Check if WebSocket is in a valid state for sending\n if (ws.readyState !== WebSocket.OPEN) {\n throw new Error(`WebSocket is not open (readyState: ${ws.readyState})`);\n }\n\n const binary = this.serializeClientMessage(queued.message);\n ws.send(binary);\n queued.resolve();\n } catch (error) {\n queued.reject(this.toError(error));\n }\n }\n\n private async drainSendQueue(): Promise<void> {\n const POLL_INTERVAL_MS = 5;\n\n while (this.sendQueue.length > 0) {\n await this.waitForCondition(\n () => this.sendQueue.length === 0,\n POLL_INTERVAL_MS,\n );\n }\n }\n\n private waitForCondition(\n condition: () => boolean,\n intervalMs: number,\n ): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (this.options.abortSignal?.aborted) {\n return reject(this.toError(this.options.abortSignal.reason) ?? new Error('Stream aborted'));\n }\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(this.toError(this.options.abortSignal?.reason) ?? new Error('Stream aborted'));\n };\n\n this.options.abortSignal?.addEventListener('abort', onAbort, { once: true });\n\n const check = () => {\n if (condition() || this.isStreamEnded()) {\n this.options.abortSignal?.removeEventListener('abort', onAbort);\n resolve();\n } else {\n timeoutId = setTimeout(check, intervalMs);\n }\n };\n\n check();\n });\n }\n\n // === Response Delivery ===\n\n private deliverResponse(message: ServerMsg): void {\n if (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.resolve({ value: message, done: false });\n } else {\n this.responseQueue.push(message);\n }\n }\n\n private async *createResponseIterator(): AsyncIterator<ServerMsg> {\n while (true) {\n const result = await this.nextResponse();\n\n if (result.done) break;\n\n yield result.value;\n }\n }\n\n private nextResponse(): Promise<IteratorResult<ServerMsg>> {\n return new Promise<IteratorResult<ServerMsg>>((resolve, reject) => {\n // Fast path: message already available\n if (this.responseQueue.length > 0) {\n const message = this.responseQueue.shift()!;\n resolve({ value: message, done: false });\n return;\n }\n\n // Stream ended\n if (this.isStreamEnded()) {\n if (this.lastError) {\n reject(this.lastError);\n } else {\n resolve({ value: undefined as any, done: true });\n }\n return;\n }\n\n // Wait for next message\n this.responseResolvers.push({ resolve, reject });\n });\n }\n\n private resolveAllPendingResponses(): void {\n while (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.resolve({ value: undefined as any, done: true });\n }\n }\n\n // === Error Handling ===\n\n private handleError(error: Error): void {\n this.lastError = error;\n this.close();\n }\n\n private rejectAllPendingOperations(error: Error): void {\n this.rejectAllSendOperations(error);\n this.rejectAllResponseResolvers(error);\n }\n\n private rejectAllSendOperations(error: Error): void {\n while (this.sendQueue.length > 0) {\n const queued = this.sendQueue.shift()!;\n queued.reject(error);\n }\n }\n\n private rejectAllResponseResolvers(error: Error): void {\n while (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.reject(error);\n }\n }\n\n private createStreamClosedError(): Error {\n if (this.options.abortSignal?.aborted) {\n const reason = this.options.abortSignal.reason;\n if (reason instanceof Error) {\n return reason;\n }\n return new Error('Stream aborted', { cause: reason });\n }\n\n return new Error('Stream closed');\n }\n\n // === Helpers ===\n\n private isStreamEnded(): boolean {\n return this.connectionState === ConnectionState.CLOSED || this.options.abortSignal?.aborted || false;\n }\n\n private toError(error: unknown): Error {\n if (error instanceof Error) return error;\n if (error instanceof ErrorEvent) return error.error;\n return new Error(String(error));\n }\n\n /**\n * Connection state progresses linearly from NEW to CLOSED and never goes back.\n * This internal contract dramatically simplifies the internal stream state management.\n *\n * If you ever feel the need to make this contract less strict, think twice.\n */\n private progressConnectionState(newState: ConnectionState): boolean {\n if (newState < this.connectionState) {\n return false;\n }\n this.connectionState = newState;\n return true;\n }\n}\n"],"names":["RetryStrategy","WebSocket","ErrorEvent"],"mappings":";;;;;;AAiBA,IAAK,eAMJ;AAND,CAAA,UAAK,eAAe,EAAA;AAClB,IAAA,eAAA,CAAA,eAAA,CAAA,KAAA,CAAA,GAAA,CAAA,CAAA,GAAA,KAAO;AACP,IAAA,eAAA,CAAA,eAAA,CAAA,YAAA,CAAA,GAAA,CAAA,CAAA,GAAA,YAAc;AACd,IAAA,eAAA,CAAA,eAAA,CAAA,WAAA,CAAA,GAAA,CAAA,CAAA,GAAA,WAAa;AACb,IAAA,eAAA,CAAA,eAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAW;AACX,IAAA,eAAA,CAAA,eAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACZ,CAAC,EANI,eAAe,KAAf,eAAe,GAAA,EAAA,CAAA,CAAA;AAkBpB;;;AAGG;MACU,mBAAmB,CAAA;AA2DX,IAAA,GAAA;AACA,IAAA,sBAAA;AACA,IAAA,kBAAA;AACA,IAAA,OAAA;;IA5DX,EAAE,GAAqB,IAAI;AAC3B,IAAA,eAAe,GAAoB,eAAe,CAAC,GAAG;AAC7C,IAAA,YAAY;;AAGZ,IAAA,SAAS,GAAG,IAAI,MAAM,EAA4B;IAC3D,aAAa,GAAG,KAAK;AACZ,IAAA,UAAU;;AAGV,IAAA,aAAa,GAAG,IAAI,MAAM,EAAa;IAChD,iBAAiB,GAAkC,EAAE;;AAGrD,IAAA,SAAS;;AAID,IAAA,QAAQ,GAAG;AACzB,QAAA,IAAI,EAAE,OAAO,OAAkB,KAAmB;AAChD,YAAA,OAAO,MAAM,IAAI,CA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AAO,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACjC;AAEA;;;;;AAKG;AACK,IAAA,uBAAuB,CAAC,QAAyB,EAAA;AACvD,QAAA,IAAI,QAAQ,GAAG,IAAI,CAAC,eAAe,EAAE;AACnC,YAAA,OAAO,KAAK;QACd;AACA,QAAA,IAAI,CAAC,eAAe,GAAG,QAAQ;AAC/B,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
1
+ {"version":3,"file":"websocket_stream.cjs","sources":["../../src/core/websocket_stream.ts"],"sourcesContent":["import { WebSocket, type WebSocketInit, type Dispatcher, ErrorEvent } from 'undici';\nimport type { BiDiStream } from './abstract_stream';\nimport Denque from 'denque';\nimport type { RetryConfig } from '../helpers/retry_strategy';\nimport { RetryStrategy } from '../helpers/retry_strategy';\nimport { DisconnectedError } from './errors';\n\ninterface QueuedMessage<InType extends object> {\n message: InType;\n resolve: () => void;\n reject: (error: Error) => void;\n}\n\ninterface ResponseResolver<OutType extends object> {\n resolve: (value: IteratorResult<OutType>) => void;\n reject: (error: Error) => void;\n}\n\nenum ConnectionState {\n NEW = 0,\n CONNECTING = 1,\n CONNECTED = 2,\n CLOSING = 3,\n CLOSED = 4,\n}\n\nexport type WSStreamOptions<ClientMsg extends object, ServerMsg extends object> = {\n abortSignal?: AbortSignal;\n\n dispatcher?: Dispatcher;\n jwtToken?: string;\n retryConfig?: Partial<RetryConfig>;\n\n onComplete?: (stream: WebSocketBiDiStream<ClientMsg, ServerMsg>) => void | Promise<void>;\n};\n\n/**\n * WebSocket-based bidirectional stream implementation for LLTransaction.\n * Implements BiDiStream interface which is compatible with DuplexStreamingCall.\n */\nexport class WebSocketBiDiStream<ClientMsg extends object, ServerMsg extends object> implements BiDiStream<ClientMsg, ServerMsg> {\n // Connection\n private ws: WebSocket | null = null;\n private connectionState: ConnectionState = ConnectionState.NEW;\n private readonly reconnection: RetryStrategy;\n\n // Send management\n private readonly sendQueue = new Denque<QueuedMessage<ClientMsg>>();\n private sendCompleted = false;\n private readonly onComplete: (stream: WebSocketBiDiStream<ClientMsg, ServerMsg>) => void | Promise<void>;\n\n // Response management\n private readonly responseQueue = new Denque<ServerMsg>();\n private responseResolvers: ResponseResolver<ServerMsg>[] = [];\n\n // Error tracking\n private lastError?: Error;\n\n // === Public API ===\n\n public readonly requests = {\n send: async (message: ClientMsg): Promise<void> => {\n return await this.enqueueSend(message);\n },\n\n complete: async (): Promise<void> => {\n if (this.sendCompleted) return;\n\n await this.drainSendQueue(); // ensure we sent all already queued messages before closing the stream\n try {\n await this.onComplete(this); // custom onComplete may send additional messages\n } catch (_: unknown) {\n // When 'complete' gets called concurrently with connection break or over a broken\n // transaction stream (server decided it should drop transaction), server would close\n // connection anyway on its end. We can safely ignore error here and just continue working.\n }\n this.sendCompleted = true;\n },\n };\n\n public readonly responses: AsyncIterable<ServerMsg> = {\n [Symbol.asyncIterator]: () => this.createResponseIterator(),\n };\n\n public close(): void {\n this.reconnection.cancel();\n\n if (this.connectionState < ConnectionState.CONNECTED) {\n // Never reached CONNECTED state. ws.close() will never trigger 'close' event.\n this.ws?.close();\n this.onClose();\n return;\n }\n\n if (!this.progressConnectionState(ConnectionState.CLOSING)) return;\n this.ws!.close();\n }\n\n constructor(\n private readonly url: string,\n private readonly serializeClientMessage: (message: ClientMsg) => Uint8Array,\n private readonly parseServerMessage: (data: Uint8Array) => ServerMsg,\n private readonly options: WSStreamOptions<ClientMsg, ServerMsg> = {},\n ) {\n this.onComplete = this.options.onComplete ?? ((stream) => stream.close());\n\n const retryConfig = this.options.retryConfig ?? {};\n this.reconnection = new RetryStrategy(retryConfig, {\n onRetry: () => { void this.connect(); },\n onMaxAttemptsReached: (error) => this.handleError(error),\n });\n\n if (this.options.abortSignal?.aborted) {\n this.progressConnectionState(ConnectionState.CLOSED);\n return;\n }\n\n this.options.abortSignal?.addEventListener('abort', () => this.close());\n this.connect();\n }\n\n // === Connection Lifecycle ===\n\n private connect(): void {\n if (this.options.abortSignal?.aborted) return;\n\n // Prevent reconnecting after first successful connection.\n if (!this.progressConnectionState(ConnectionState.CONNECTING)) return;\n\n try {\n this.ws = this.createWebSocket();\n\n this.ws.addEventListener('open', () => this.onOpen());\n this.ws.addEventListener('message', (event) => this.onMessage(event.data));\n this.ws.addEventListener('error', (error) => this.onError(error));\n this.ws.addEventListener('close', () => this.onClose());\n } catch (error) {\n this.lastError = this.toError(error);\n this.reconnection.schedule();\n }\n }\n\n private createWebSocket(): WebSocket {\n const options: WebSocketInit = {};\n\n if (this.options.jwtToken) options.headers = { authorization: `Bearer ${this.options.jwtToken}` };\n if (this.options.dispatcher) options.dispatcher = this.options.dispatcher;\n\n const ws = new WebSocket(this.url, options);\n ws.binaryType = 'arraybuffer';\n return ws;\n }\n\n private onOpen(): void {\n this.progressConnectionState(ConnectionState.CONNECTED);\n this.processSendQueue();\n }\n\n private onMessage(data: unknown): void {\n if (!(data instanceof ArrayBuffer)) {\n this.handleError(new Error(`Unexpected WS message format: ${typeof data}`));\n return;\n }\n\n try {\n const message = this.parseServerMessage(new Uint8Array(data));\n this.deliverResponse(message);\n } catch (error) {\n this.handleError(this.toError(error));\n }\n }\n\n private onError(error: unknown): void {\n if (this.connectionState < ConnectionState.CONNECTED) {\n // Try to connect several times until we succeed or run out of attempts.\n this.lastError = this.toError(error);\n this.reconnection.schedule();\n return;\n }\n\n this.handleError(this.toError(error));\n }\n\n private onClose(): void {\n this.progressConnectionState(ConnectionState.CLOSED);\n\n // If abort signal was triggered, use that as the error source\n if (this.options.abortSignal?.aborted && !this.lastError) {\n const reason = this.options.abortSignal.reason;\n if (reason instanceof Error) {\n this.lastError = reason;\n } else if (reason !== undefined) {\n this.lastError = new Error(String(reason), { cause: reason });\n } else {\n this.lastError = this.createStreamClosedError();\n }\n }\n\n if (!this.lastError) {\n this.rejectAllSendOperations(this.createStreamClosedError());\n this.resolveAllPendingResponses(); // unblock active async iterator\n } else {\n this.rejectAllPendingOperations(this.lastError);\n }\n }\n\n // === Send Queue Management ===\n\n private enqueueSend(message: ClientMsg): Promise<void> {\n if (this.sendCompleted) {\n throw new Error('Cannot send: stream already completed');\n }\n\n if (this.options.abortSignal?.aborted) {\n throw new Error('Cannot send: stream aborted');\n }\n\n return new Promise<void>((resolve, reject) => {\n this.sendQueue.push({ message, resolve, reject });\n this.processSendQueue();\n });\n }\n\n private processSendQueue(): void {\n if (!this.canSendMessages()) return;\n\n while (this.sendQueue.length > 0) {\n const queued = this.sendQueue.shift()!;\n this.sendQueuedMessage(queued);\n }\n }\n\n private canSendMessages(): boolean {\n return this.connectionState === ConnectionState.CONNECTED;\n }\n\n private sendQueuedMessage(queued: QueuedMessage<ClientMsg>): void {\n try {\n const ws = this.ws;\n if (!ws) {\n throw new Error('WebSocket is not connected');\n }\n\n // Check if WebSocket is in a valid state for sending\n if (ws.readyState !== WebSocket.OPEN) {\n throw new Error(`WebSocket is not open (readyState: ${ws.readyState})`);\n }\n\n const binary = this.serializeClientMessage(queued.message);\n ws.send(binary);\n queued.resolve();\n } catch (error) {\n queued.reject(this.toError(error));\n }\n }\n\n private async drainSendQueue(): Promise<void> {\n const POLL_INTERVAL_MS = 5;\n\n while (this.sendQueue.length > 0) {\n await this.waitForCondition(\n () => this.sendQueue.length === 0,\n POLL_INTERVAL_MS,\n );\n }\n }\n\n private waitForCondition(\n condition: () => boolean,\n intervalMs: number,\n ): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (this.options.abortSignal?.aborted) {\n return reject(this.toError(this.options.abortSignal.reason) ?? new Error('Stream aborted'));\n }\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(this.toError(this.options.abortSignal?.reason) ?? new Error('Stream aborted'));\n };\n\n this.options.abortSignal?.addEventListener('abort', onAbort, { once: true });\n\n const check = () => {\n if (condition() || this.isStreamEnded()) {\n this.options.abortSignal?.removeEventListener('abort', onAbort);\n resolve();\n } else {\n timeoutId = setTimeout(check, intervalMs);\n }\n };\n\n check();\n });\n }\n\n // === Response Delivery ===\n\n private deliverResponse(message: ServerMsg): void {\n if (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.resolve({ value: message, done: false });\n } else {\n this.responseQueue.push(message);\n }\n }\n\n private async *createResponseIterator(): AsyncIterator<ServerMsg> {\n while (true) {\n const result = await this.nextResponse();\n\n if (result.done) break;\n\n yield result.value;\n }\n }\n\n private nextResponse(): Promise<IteratorResult<ServerMsg>> {\n return new Promise<IteratorResult<ServerMsg>>((resolve, reject) => {\n // Fast path: message already available\n if (this.responseQueue.length > 0) {\n const message = this.responseQueue.shift()!;\n resolve({ value: message, done: false });\n return;\n }\n\n // Stream ended\n if (this.isStreamEnded()) {\n if (this.lastError) {\n reject(this.lastError);\n } else {\n resolve({ value: undefined as any, done: true });\n }\n return;\n }\n\n // Wait for next message\n this.responseResolvers.push({ resolve, reject });\n });\n }\n\n private resolveAllPendingResponses(): void {\n while (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.resolve({ value: undefined as any, done: true });\n }\n }\n\n // === Error Handling ===\n\n private handleError(error: Error): void {\n this.lastError = error;\n this.close();\n }\n\n private rejectAllPendingOperations(error: Error): void {\n this.rejectAllSendOperations(error);\n this.rejectAllResponseResolvers(error);\n }\n\n private rejectAllSendOperations(error: Error): void {\n while (this.sendQueue.length > 0) {\n const queued = this.sendQueue.shift()!;\n queued.reject(error);\n }\n }\n\n private rejectAllResponseResolvers(error: Error): void {\n while (this.responseResolvers.length > 0) {\n const resolver = this.responseResolvers.shift()!;\n resolver.reject(error);\n }\n }\n\n private createStreamClosedError(): Error {\n if (this.options.abortSignal?.aborted) {\n const reason = this.options.abortSignal.reason;\n if (reason instanceof Error) {\n return reason;\n }\n return new Error('Stream aborted', { cause: reason });\n }\n\n return new Error('Stream closed');\n }\n\n // === Helpers ===\n\n private isStreamEnded(): boolean {\n return this.connectionState === ConnectionState.CLOSED || this.options.abortSignal?.aborted || false;\n }\n\n private toError(error: unknown): Error {\n if (error instanceof Error) return error;\n if (error instanceof ErrorEvent) {\n const err = error.error;\n // undici WebSocket throws TypeError with empty message on socket close\n // (e.g., when connection is lost or server disconnects)\n if (err instanceof TypeError && !err.message) {\n return new DisconnectedError('WebSocket connection closed unexpectedly');\n }\n return err instanceof Error ? err : new Error('WebSocket error', { cause: error });\n }\n return new Error(String(error));\n }\n\n /**\n * Connection state progresses linearly from NEW to CLOSED and never goes back.\n * This internal contract dramatically simplifies the internal stream state management.\n *\n * If you ever feel the need to make this contract less strict, think twice.\n */\n private progressConnectionState(newState: ConnectionState): boolean {\n if (newState < this.connectionState) {\n return false;\n }\n this.connectionState = newState;\n return true;\n }\n}\n"],"names":["RetryStrategy","WebSocket","ErrorEvent","DisconnectedError"],"mappings":";;;;;;;AAkBA,IAAK,eAMJ;AAND,CAAA,UAAK,eAAe,EAAA;AAClB,IAAA,eAAA,CAAA,eAAA,CAAA,KAAA,CAAA,GAAA,CAAA,CAAA,GAAA,KAAO;AACP,IAAA,eAAA,CAAA,eAAA,CAAA,YAAA,CAAA,GAAA,CAAA,CAAA,GAAA,YAAc;AACd,IAAA,eAAA,CAAA,eAAA,CAAA,WAAA,CAAA,GAAA,CAAA,CAAA,GAAA,WAAa;AACb,IAAA,eAAA,CAAA,eAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAW;AACX,IAAA,eAAA,CAAA,eAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACZ,CAAC,EANI,eAAe,KAAf,eAAe,GAAA,EAAA,CAAA,CAAA;AAkBpB;;;AAGG;MACU,mBAAmB,CAAA;AA2DX,IAAA,GAAA;AACA,IAAA,sBAAA;AACA,IAAA,kBAAA;AACA,IAAA,OAAA;;IA5DX,EAAE,GAAqB,IAAI;AAC3B,IAAA,eAAe,GAAoB,eAAe,CAAC,GAAG;AAC7C,IAAA,YAAY;;AAGZ,IAAA,SAAS,GAAG,IAAI,MAAM,EAA4B;IAC3D,aAAa,G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