@milaboratories/pl-client 2.16.1 → 2.16.3

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 (58) hide show
  1. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.7.0_typescript@5.6.3/__external/tslib/tslib.es6.cjs +61 -0
  2. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.7.0_typescript@5.6.3/__external/tslib/tslib.es6.cjs.map +1 -0
  3. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.7.0_typescript@5.6.3/__external/tslib/tslib.es6.js +58 -0
  4. package/dist/__external/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.52.4_tslib@2.7.0_typescript@5.6.3/__external/tslib/tslib.es6.js.map +1 -0
  5. package/dist/core/PromiseTracker.cjs +39 -0
  6. package/dist/core/PromiseTracker.cjs.map +1 -0
  7. package/dist/core/PromiseTracker.d.ts +14 -0
  8. package/dist/core/PromiseTracker.d.ts.map +1 -0
  9. package/dist/core/PromiseTracker.js +37 -0
  10. package/dist/core/PromiseTracker.js.map +1 -0
  11. package/dist/core/StatefulPromise.cjs +65 -0
  12. package/dist/core/StatefulPromise.cjs.map +1 -0
  13. package/dist/core/StatefulPromise.d.ts +39 -0
  14. package/dist/core/StatefulPromise.d.ts.map +1 -0
  15. package/dist/core/StatefulPromise.js +63 -0
  16. package/dist/core/StatefulPromise.js.map +1 -0
  17. package/dist/core/ll_transaction.cjs +3 -2
  18. package/dist/core/ll_transaction.cjs.map +1 -1
  19. package/dist/core/ll_transaction.d.ts.map +1 -1
  20. package/dist/core/ll_transaction.js +3 -2
  21. package/dist/core/ll_transaction.js.map +1 -1
  22. package/dist/core/transaction.cjs +577 -515
  23. package/dist/core/transaction.cjs.map +1 -1
  24. package/dist/core/transaction.d.ts +6 -4
  25. package/dist/core/transaction.d.ts.map +1 -1
  26. package/dist/core/transaction.js +578 -516
  27. package/dist/core/transaction.js.map +1 -1
  28. package/dist/test/tcp-proxy.cjs +129 -0
  29. package/dist/test/tcp-proxy.cjs.map +1 -0
  30. package/dist/test/tcp-proxy.d.ts +17 -0
  31. package/dist/test/tcp-proxy.d.ts.map +1 -0
  32. package/dist/test/tcp-proxy.js +107 -0
  33. package/dist/test/tcp-proxy.js.map +1 -0
  34. package/dist/test/test_config.cjs +54 -7
  35. package/dist/test/test_config.cjs.map +1 -1
  36. package/dist/test/test_config.d.ts +18 -2
  37. package/dist/test/test_config.d.ts.map +1 -1
  38. package/dist/test/test_config.js +54 -7
  39. package/dist/test/test_config.js.map +1 -1
  40. package/package.json +7 -8
  41. package/src/core/PromiseTracker.ts +39 -0
  42. package/src/core/StatefulPromise.ts +92 -0
  43. package/src/core/client.test.ts +1 -1
  44. package/src/core/config.test.ts +1 -1
  45. package/src/core/connectivity.test.ts +70 -0
  46. package/src/core/error.test.ts +1 -1
  47. package/src/core/ll_client.test.ts +1 -1
  48. package/src/core/ll_transaction.test.ts +1 -1
  49. package/src/core/ll_transaction.ts +3 -2
  50. package/src/core/transaction.test.ts +6 -1
  51. package/src/core/transaction.ts +91 -48
  52. package/src/core/types.test.ts +1 -1
  53. package/src/core/unauth_client.test.ts +1 -1
  54. package/src/helpers/rich_resource_types.test.ts +1 -1
  55. package/src/test/tcp-proxy.ts +126 -0
  56. package/src/test/test_config.test.ts +1 -1
  57. package/src/test/test_config.ts +82 -7
  58. package/src/util/util.test.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ll_transaction.cjs","sources":["../../src/core/ll_transaction.ts"],"sourcesContent":["import type {\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from '../proto/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport type { DuplexStreamingCall } from '@protobuf-ts/runtime-rpc';\nimport Denque from 'denque';\nimport type { Status } from '../proto/github.com/googleapis/googleapis/google/rpc/status';\nimport {\n PlErrorCodeNotFound,\n RecoverablePlError,\n rethrowMeaningfulError,\n UnrecoverablePlError,\n} from './errors';\n\nexport type ClientMessageRequest = TxAPI_ClientMessage['request'];\n\nexport type ServerMessageResponse = TxAPI_ServerMessage['response'];\n\ntype TxStream = DuplexStreamingCall<TxAPI_ClientMessage, TxAPI_ServerMessage>;\n\nexport type OneOfKind<T extends { oneofKind: unknown }, Kind extends T['oneofKind']> = Extract<\n T,\n { oneofKind: Kind }\n>;\n\ninterface SingleResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: false;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>) => void;\n reject: (e: Error) => void;\n}\n\ninterface MultiResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: true;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>[]) => void;\n reject: (e: Error) => void;\n}\n\ntype AnySingleResponseHandler = SingleResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyMultiResponseHandler = MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyResponseHandler =\n | SingleResponseHandler<ServerMessageResponse['oneofKind']>\n | MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\nfunction createResponseHandler<Kind extends ServerMessageResponse['oneofKind']>(\n kind: Kind,\n expectMultiResponse: boolean,\n resolve:\n | ((v: OneOfKind<ServerMessageResponse, Kind>) => void)\n | ((v: OneOfKind<ServerMessageResponse, Kind>[]) => void),\n reject: (e: Error) => void,\n): AnyResponseHandler {\n return { kind, expectMultiResponse, resolve, reject } as AnyResponseHandler;\n}\n\nfunction isRecoverable(status: Status): boolean {\n return status.code === PlErrorCodeNotFound;\n}\n\nexport class RethrowError extends Error {\n name = 'RethrowError';\n constructor(public readonly rethrowLambda: () => never) {\n super('Rethrow error, you should never see this one.');\n }\n}\n\nexport class LLPlTransaction {\n /** Bidirectional channel through which transaction communicates with the server */\n private readonly stream: TxStream;\n\n /** Used to abort ongoing transaction stream */\n private readonly abortController = new AbortController();\n\n /** Counter of sent requests, used to calculate which future response will correspond to this request.\n * Incremented on each sent request. */\n private requestIdxCounter = 0;\n\n /** Queue from which incoming message processor takes handlers to which pass incoming messages */\n private readonly responseHandlerQueue = new Denque<AnyResponseHandler>();\n\n /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible\n * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the\n * same way it is tracked on the server, so client can synchronously return such ids to the user. */\n private localResourceIdCounter = 0n;\n\n /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages\n * to be sent to the stream. */\n private closed = false;\n /** Whether the outgoing stream was already closed. */\n private completed = false;\n\n /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */\n private errorFactory?: () => never;\n\n /** Timestamp when transaction was opened */\n private readonly openTimestamp = Date.now();\n\n private readonly incomingProcessorResult: Promise<(() => never) | null>;\n\n constructor(streamFactory: (abortSignal: AbortSignal) => TxStream) {\n this.stream = streamFactory(this.abortController.signal);\n\n // Starting incoming event processor\n this.incomingProcessorResult = this.incomingEventProcessor();\n }\n\n private assignErrorFactoryIfNotSet(\n errorFactory: () => never,\n reject?: (e: Error) => void,\n ): () => never {\n if (reject !== undefined) reject(new RethrowError(errorFactory));\n if (this.errorFactory) return errorFactory;\n this.errorFactory = errorFactory;\n return errorFactory;\n }\n\n private async incomingEventProcessor(): Promise<(() => never) | null> {\n /** Counter of received responses, used to check consistency of responses.\n * Increments on each received message. */\n let expectedId = -1;\n\n // defined externally to make possible to communicate any processing errors\n // to the specific request on which it happened\n let currentHandler: AnyResponseHandler | undefined = undefined;\n let responseAggregator: ServerMessageResponse[] | undefined = undefined;\n try {\n for await (const message of this.stream.responses) {\n if (currentHandler === undefined) {\n currentHandler = this.responseHandlerQueue.shift();\n\n if (currentHandler === undefined) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`orphan incoming message`);\n });\n break;\n }\n\n // allocating response aggregator array\n if (currentHandler.expectMultiResponse) responseAggregator = [];\n\n expectedId++;\n }\n\n if (message.requestId !== expectedId) {\n const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n });\n break;\n }\n\n if (message.error !== undefined) {\n const status = message.error;\n\n if (isRecoverable(status)) {\n currentHandler.reject(\n new RethrowError(() => {\n throw new RecoverablePlError(status);\n }),\n );\n currentHandler = undefined;\n\n if (message.multiMessage !== undefined && !message.multiMessage.isLast) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error('Unexpected message sequence.');\n });\n break;\n }\n\n // We can continue to work after recoverable errors\n continue;\n } else {\n this.assignErrorFactoryIfNotSet(() => {\n throw new UnrecoverablePlError(status);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n // In case of unrecoverable errors we close the transaction\n break;\n }\n }\n\n if (\n currentHandler.kind !== message.response.oneofKind\n && message?.multiMessage?.isEmpty !== true\n ) {\n const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n if (currentHandler.expectMultiResponse !== (message.multiMessage !== undefined)) {\n const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== undefined}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n // <- at this point we validated everything we can at this level\n\n if (message.multiMessage !== undefined) {\n if (!message.multiMessage.isEmpty) {\n if (message.multiMessage.id !== responseAggregator!.length + 1) {\n const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator!.length + 1}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n responseAggregator!.push(message.response);\n }\n\n if (message.multiMessage.isLast) {\n (currentHandler as AnyMultiResponseHandler).resolve(responseAggregator!);\n responseAggregator = undefined;\n currentHandler = undefined;\n }\n } else {\n (currentHandler as AnySingleResponseHandler).resolve(message.response);\n currentHandler = undefined;\n }\n }\n } catch (e: any) {\n return this.assignErrorFactoryIfNotSet(() => {\n rethrowMeaningfulError(e, true);\n }, currentHandler?.reject);\n } finally {\n await this.close();\n }\n return null;\n }\n\n /** Executed after termination of incoming message processor */\n private async close(): Promise<void> {\n if (this.closed) return;\n\n this.closed = true;\n\n // Rejecting all messages\n\n while (true) {\n const handler = this.responseHandlerQueue.shift();\n if (!handler) break;\n if (this.errorFactory) handler.reject(new RethrowError(this.errorFactory));\n else handler.reject(new Error('no reply'));\n }\n\n // closing outgoing stream\n await this.stream.requests.complete();\n }\n\n /** Forcefully close the transaction, terminate all connections and reject all pending requests */\n public abort(cause?: Error) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`transaction aborted`, { cause });\n });\n this.abortController.abort(cause);\n }\n\n /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */\n public async await(): Promise<void> {\n // for those who want to understand \"why?\":\n // this way there is no hanging promise that will complete with rejection\n // until await is implicitly requested, the this.incomingProcessorResult\n // always resolves with success\n\n const processingResult = await this.incomingProcessorResult;\n if (processingResult !== null) processingResult();\n }\n\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: false\n ): Promise<OneOfKind<ServerMessageResponse, Kind>>;\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: true\n ): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;\n /** Generate proper client message and send it to the server, and returns a promise of future response. */\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: boolean,\n ): Promise<OneOfKind<ServerMessageResponse, Kind> | OneOfKind<ServerMessageResponse, Kind>[]> {\n if (this.errorFactory) return Promise.reject(new RethrowError(this.errorFactory));\n\n if (this.closed) return Promise.reject(new Error('Transaction already closed'));\n\n // Note: Promise synchronously executes a callback passed to a constructor\n const result = new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\n });\n\n // Awaiting message dispatch to catch any associated errors.\n // There is no hurry, we are not going to receive a response until message is sent.\n await this.stream.requests.send({\n requestId: this.requestIdxCounter++,\n request: r,\n });\n\n try {\n return await result;\n } catch (e: any) {\n if (e instanceof RethrowError) e.rethrowLambda();\n throw new Error('Error while waiting for response', { cause: e });\n }\n }\n\n private _completed = false;\n\n /** Safe to call multiple times */\n public async complete() {\n if (this._completed) return;\n this._completed = true;\n await this.stream.requests.complete();\n }\n}\n"],"names":["PlErrorCodeNotFound","RecoverablePlError","UnrecoverablePlError","rethrowMeaningfulError"],"mappings":";;;;;AA+CA,SAAS,qBAAqB,CAC5B,IAAU,EACV,mBAA4B,EAC5B,OAE2D,EAC3D,MAA0B,EAAA;IAE1B,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAwB;AAC7E;AAEA,SAAS,aAAa,CAAC,MAAc,EAAA;AACnC,IAAA,OAAO,MAAM,CAAC,IAAI,KAAKA,0BAAmB;AAC5C;AAEM,MAAO,YAAa,SAAQ,KAAK,CAAA;AAET,IAAA,aAAA;IAD5B,IAAI,GAAG,cAAc;AACrB,IAAA,WAAA,CAA4B,aAA0B,EAAA;QACpD,KAAK,CAAC,+CAA+C,CAAC;QAD5B,IAAA,CAAA,aAAa,GAAb,aAAa;IAEzC;AACD;MAEY,eAAe,CAAA;;AAET,IAAA,MAAM;;AAGN,IAAA,eAAe,GAAG,IAAI,eAAe,EAAE;AAExD;AACuC;IAC/B,iBAAiB,GAAG,CAAC;;AAGZ,IAAA,oBAAoB,GAAG,IAAI,MAAM,EAAsB;AA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F;IAEQ,UAAU,GAAG,KAAK;;AAGnB,IAAA,MAAM,QAAQ,GAAA;QACnB,IAAI,IAAI,CAAC,UAAU;YAAE;AACrB,QAAA,IAAI,CAAC,UAAU,GAAG,IAAI;QACtB,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE;IACvC;AACD;;;;;"}
1
+ {"version":3,"file":"ll_transaction.cjs","sources":["../../src/core/ll_transaction.ts"],"sourcesContent":["import type {\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from '../proto/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport type { DuplexStreamingCall } from '@protobuf-ts/runtime-rpc';\nimport Denque from 'denque';\nimport type { Status } from '../proto/github.com/googleapis/googleapis/google/rpc/status';\nimport {\n PlErrorCodeNotFound,\n RecoverablePlError,\n rethrowMeaningfulError,\n UnrecoverablePlError,\n} from './errors';\nimport { StatefulPromise } from './StatefulPromise';\n\nexport type ClientMessageRequest = TxAPI_ClientMessage['request'];\n\nexport type ServerMessageResponse = TxAPI_ServerMessage['response'];\n\ntype TxStream = DuplexStreamingCall<TxAPI_ClientMessage, TxAPI_ServerMessage>;\n\nexport type OneOfKind<T extends { oneofKind: unknown }, Kind extends T['oneofKind']> = Extract<\n T,\n { oneofKind: Kind }\n>;\n\ninterface SingleResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: false;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>) => void;\n reject: (e: Error) => void;\n}\n\ninterface MultiResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: true;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>[]) => void;\n reject: (e: Error) => void;\n}\n\ntype AnySingleResponseHandler = SingleResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyMultiResponseHandler = MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyResponseHandler =\n | SingleResponseHandler<ServerMessageResponse['oneofKind']>\n | MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\nfunction createResponseHandler<Kind extends ServerMessageResponse['oneofKind']>(\n kind: Kind,\n expectMultiResponse: boolean,\n resolve:\n | ((v: OneOfKind<ServerMessageResponse, Kind>) => void)\n | ((v: OneOfKind<ServerMessageResponse, Kind>[]) => void),\n reject: (e: Error) => void,\n): AnyResponseHandler {\n return { kind, expectMultiResponse, resolve, reject } as AnyResponseHandler;\n}\n\nfunction isRecoverable(status: Status): boolean {\n return status.code === PlErrorCodeNotFound;\n}\n\nexport class RethrowError extends Error {\n name = 'RethrowError';\n constructor(public readonly rethrowLambda: () => never) {\n super('Rethrow error, you should never see this one.');\n }\n}\n\nexport class LLPlTransaction {\n /** Bidirectional channel through which transaction communicates with the server */\n private readonly stream: TxStream;\n\n /** Used to abort ongoing transaction stream */\n private readonly abortController = new AbortController();\n\n /** Counter of sent requests, used to calculate which future response will correspond to this request.\n * Incremented on each sent request. */\n private requestIdxCounter = 0;\n\n /** Queue from which incoming message processor takes handlers to which pass incoming messages */\n private readonly responseHandlerQueue = new Denque<AnyResponseHandler>();\n\n /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible\n * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the\n * same way it is tracked on the server, so client can synchronously return such ids to the user. */\n private localResourceIdCounter = 0n;\n\n /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages\n * to be sent to the stream. */\n private closed = false;\n /** Whether the outgoing stream was already closed. */\n private completed = false;\n\n /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */\n private errorFactory?: () => never;\n\n /** Timestamp when transaction was opened */\n private readonly openTimestamp = Date.now();\n\n private readonly incomingProcessorResult: Promise<(() => never) | null>;\n\n constructor(streamFactory: (abortSignal: AbortSignal) => TxStream) {\n this.stream = streamFactory(this.abortController.signal);\n\n // Starting incoming event processor\n this.incomingProcessorResult = this.incomingEventProcessor();\n }\n\n private assignErrorFactoryIfNotSet(\n errorFactory: () => never,\n reject?: (e: Error) => void,\n ): () => never {\n if (reject !== undefined) reject(new RethrowError(errorFactory));\n if (this.errorFactory) return errorFactory;\n this.errorFactory = errorFactory;\n return errorFactory;\n }\n\n private async incomingEventProcessor(): Promise<(() => never) | null> {\n /** Counter of received responses, used to check consistency of responses.\n * Increments on each received message. */\n let expectedId = -1;\n\n // defined externally to make possible to communicate any processing errors\n // to the specific request on which it happened\n let currentHandler: AnyResponseHandler | undefined = undefined;\n let responseAggregator: ServerMessageResponse[] | undefined = undefined;\n try {\n for await (const message of this.stream.responses) {\n if (currentHandler === undefined) {\n currentHandler = this.responseHandlerQueue.shift();\n\n if (currentHandler === undefined) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`orphan incoming message`);\n });\n break;\n }\n\n // allocating response aggregator array\n if (currentHandler.expectMultiResponse) responseAggregator = [];\n\n expectedId++;\n }\n\n if (message.requestId !== expectedId) {\n const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n });\n break;\n }\n\n if (message.error !== undefined) {\n const status = message.error;\n\n if (isRecoverable(status)) {\n currentHandler.reject(\n new RethrowError(() => {\n throw new RecoverablePlError(status);\n }),\n );\n currentHandler = undefined;\n\n if (message.multiMessage !== undefined && !message.multiMessage.isLast) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error('Unexpected message sequence.');\n });\n break;\n }\n\n // We can continue to work after recoverable errors\n continue;\n } else {\n this.assignErrorFactoryIfNotSet(() => {\n throw new UnrecoverablePlError(status);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n // In case of unrecoverable errors we close the transaction\n break;\n }\n }\n\n if (\n currentHandler.kind !== message.response.oneofKind\n && message?.multiMessage?.isEmpty !== true\n ) {\n const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n if (currentHandler.expectMultiResponse !== (message.multiMessage !== undefined)) {\n const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== undefined}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n // <- at this point we validated everything we can at this level\n\n if (message.multiMessage !== undefined) {\n if (!message.multiMessage.isEmpty) {\n if (message.multiMessage.id !== responseAggregator!.length + 1) {\n const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator!.length + 1}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n responseAggregator!.push(message.response);\n }\n\n if (message.multiMessage.isLast) {\n (currentHandler as AnyMultiResponseHandler).resolve(responseAggregator!);\n responseAggregator = undefined;\n currentHandler = undefined;\n }\n } else {\n (currentHandler as AnySingleResponseHandler).resolve(message.response);\n currentHandler = undefined;\n }\n }\n } catch (e: any) {\n return this.assignErrorFactoryIfNotSet(() => {\n rethrowMeaningfulError(e, true);\n }, currentHandler?.reject);\n } finally {\n await this.close();\n }\n return null;\n }\n\n /** Executed after termination of incoming message processor */\n private async close(): Promise<void> {\n if (this.closed) return;\n\n this.closed = true;\n\n // Rejecting all messages\n\n while (true) {\n const handler = this.responseHandlerQueue.shift();\n if (!handler) break;\n if (this.errorFactory) handler.reject(new RethrowError(this.errorFactory));\n else handler.reject(new Error('no reply'));\n }\n\n // closing outgoing stream\n await this.stream.requests.complete();\n }\n\n /** Forcefully close the transaction, terminate all connections and reject all pending requests */\n public abort(cause?: Error) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`transaction aborted`, { cause });\n });\n this.abortController.abort(cause);\n }\n\n /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */\n public async await(): Promise<void> {\n // for those who want to understand \"why?\":\n // this way there is no hanging promise that will complete with rejection\n // until await is implicitly requested, the this.incomingProcessorResult\n // always resolves with success\n\n const processingResult = await this.incomingProcessorResult;\n if (processingResult !== null) processingResult();\n }\n\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: false\n ): Promise<OneOfKind<ServerMessageResponse, Kind>>;\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: true\n ): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;\n /** Generate proper client message and send it to the server, and returns a promise of future response. */\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: boolean,\n ): Promise<OneOfKind<ServerMessageResponse, Kind> | OneOfKind<ServerMessageResponse, Kind>[]> {\n if (this.errorFactory) return Promise.reject(new RethrowError(this.errorFactory));\n\n if (this.closed) return Promise.reject(new Error('Transaction already closed'));\n\n // Note: Promise synchronously executes a callback passed to a constructor\n const result = StatefulPromise.fromDeferredReject(new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\n }));\n\n // Awaiting message dispatch to catch any associated errors.\n // There is no hurry, we are not going to receive a response until message is sent.\n await this.stream.requests.send({\n requestId: this.requestIdxCounter++,\n request: r,\n });\n\n try {\n return await result;\n } catch (e: any) {\n if (e instanceof RethrowError) e.rethrowLambda();\n throw new Error('Error while waiting for response', { cause: e });\n }\n }\n\n private _completed = false;\n\n /** Safe to call multiple times */\n public async complete() {\n if (this._completed) return;\n this._completed = true;\n await this.stream.requests.complete();\n }\n}\n"],"names":["PlErrorCodeNotFound","RecoverablePlError","UnrecoverablePlError","rethrowMeaningfulError","StatefulPromise"],"mappings":";;;;;;AAgDA,SAAS,qBAAqB,CAC5B,IAAU,EACV,mBAA4B,EAC5B,OAE2D,EAC3D,MA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, rethrowMeaningfulError, PlErrorCodeNotFound } from './errors.js';
3
+ import { StatefulPromise } from './StatefulPromise.js';
3
4
 
4
5
  function createResponseHandler(kind, expectMultiResponse, resolve, reject) {
5
6
  return { kind, expectMultiResponse, resolve, reject };
@@ -201,9 +202,9 @@ class LLPlTransaction {
201
202
  if (this.closed)
202
203
  return Promise.reject(new Error('Transaction already closed'));
203
204
  // Note: Promise synchronously executes a callback passed to a constructor
204
- const result = new Promise((resolve, reject) => {
205
+ const result = StatefulPromise.fromDeferredReject(new Promise((resolve, reject) => {
205
206
  this.responseHandlerQueue.push(createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject));
206
- });
207
+ }));
207
208
  // Awaiting message dispatch to catch any associated errors.
208
209
  // There is no hurry, we are not going to receive a response until message is sent.
209
210
  await this.stream.requests.send({
@@ -1 +1 @@
1
- {"version":3,"file":"ll_transaction.js","sources":["../../src/core/ll_transaction.ts"],"sourcesContent":["import type {\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from '../proto/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport type { DuplexStreamingCall } from '@protobuf-ts/runtime-rpc';\nimport Denque from 'denque';\nimport type { Status } from '../proto/github.com/googleapis/googleapis/google/rpc/status';\nimport {\n PlErrorCodeNotFound,\n RecoverablePlError,\n rethrowMeaningfulError,\n UnrecoverablePlError,\n} from './errors';\n\nexport type ClientMessageRequest = TxAPI_ClientMessage['request'];\n\nexport type ServerMessageResponse = TxAPI_ServerMessage['response'];\n\ntype TxStream = DuplexStreamingCall<TxAPI_ClientMessage, TxAPI_ServerMessage>;\n\nexport type OneOfKind<T extends { oneofKind: unknown }, Kind extends T['oneofKind']> = Extract<\n T,\n { oneofKind: Kind }\n>;\n\ninterface SingleResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: false;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>) => void;\n reject: (e: Error) => void;\n}\n\ninterface MultiResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: true;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>[]) => void;\n reject: (e: Error) => void;\n}\n\ntype AnySingleResponseHandler = SingleResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyMultiResponseHandler = MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyResponseHandler =\n | SingleResponseHandler<ServerMessageResponse['oneofKind']>\n | MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\nfunction createResponseHandler<Kind extends ServerMessageResponse['oneofKind']>(\n kind: Kind,\n expectMultiResponse: boolean,\n resolve:\n | ((v: OneOfKind<ServerMessageResponse, Kind>) => void)\n | ((v: OneOfKind<ServerMessageResponse, Kind>[]) => void),\n reject: (e: Error) => void,\n): AnyResponseHandler {\n return { kind, expectMultiResponse, resolve, reject } as AnyResponseHandler;\n}\n\nfunction isRecoverable(status: Status): boolean {\n return status.code === PlErrorCodeNotFound;\n}\n\nexport class RethrowError extends Error {\n name = 'RethrowError';\n constructor(public readonly rethrowLambda: () => never) {\n super('Rethrow error, you should never see this one.');\n }\n}\n\nexport class LLPlTransaction {\n /** Bidirectional channel through which transaction communicates with the server */\n private readonly stream: TxStream;\n\n /** Used to abort ongoing transaction stream */\n private readonly abortController = new AbortController();\n\n /** Counter of sent requests, used to calculate which future response will correspond to this request.\n * Incremented on each sent request. */\n private requestIdxCounter = 0;\n\n /** Queue from which incoming message processor takes handlers to which pass incoming messages */\n private readonly responseHandlerQueue = new Denque<AnyResponseHandler>();\n\n /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible\n * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the\n * same way it is tracked on the server, so client can synchronously return such ids to the user. */\n private localResourceIdCounter = 0n;\n\n /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages\n * to be sent to the stream. */\n private closed = false;\n /** Whether the outgoing stream was already closed. */\n private completed = false;\n\n /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */\n private errorFactory?: () => never;\n\n /** Timestamp when transaction was opened */\n private readonly openTimestamp = Date.now();\n\n private readonly incomingProcessorResult: Promise<(() => never) | null>;\n\n constructor(streamFactory: (abortSignal: AbortSignal) => TxStream) {\n this.stream = streamFactory(this.abortController.signal);\n\n // Starting incoming event processor\n this.incomingProcessorResult = this.incomingEventProcessor();\n }\n\n private assignErrorFactoryIfNotSet(\n errorFactory: () => never,\n reject?: (e: Error) => void,\n ): () => never {\n if (reject !== undefined) reject(new RethrowError(errorFactory));\n if (this.errorFactory) return errorFactory;\n this.errorFactory = errorFactory;\n return errorFactory;\n }\n\n private async incomingEventProcessor(): Promise<(() => never) | null> {\n /** Counter of received responses, used to check consistency of responses.\n * Increments on each received message. */\n let expectedId = -1;\n\n // defined externally to make possible to communicate any processing errors\n // to the specific request on which it happened\n let currentHandler: AnyResponseHandler | undefined = undefined;\n let responseAggregator: ServerMessageResponse[] | undefined = undefined;\n try {\n for await (const message of this.stream.responses) {\n if (currentHandler === undefined) {\n currentHandler = this.responseHandlerQueue.shift();\n\n if (currentHandler === undefined) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`orphan incoming message`);\n });\n break;\n }\n\n // allocating response aggregator array\n if (currentHandler.expectMultiResponse) responseAggregator = [];\n\n expectedId++;\n }\n\n if (message.requestId !== expectedId) {\n const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n });\n break;\n }\n\n if (message.error !== undefined) {\n const status = message.error;\n\n if (isRecoverable(status)) {\n currentHandler.reject(\n new RethrowError(() => {\n throw new RecoverablePlError(status);\n }),\n );\n currentHandler = undefined;\n\n if (message.multiMessage !== undefined && !message.multiMessage.isLast) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error('Unexpected message sequence.');\n });\n break;\n }\n\n // We can continue to work after recoverable errors\n continue;\n } else {\n this.assignErrorFactoryIfNotSet(() => {\n throw new UnrecoverablePlError(status);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n // In case of unrecoverable errors we close the transaction\n break;\n }\n }\n\n if (\n currentHandler.kind !== message.response.oneofKind\n && message?.multiMessage?.isEmpty !== true\n ) {\n const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n if (currentHandler.expectMultiResponse !== (message.multiMessage !== undefined)) {\n const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== undefined}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n // <- at this point we validated everything we can at this level\n\n if (message.multiMessage !== undefined) {\n if (!message.multiMessage.isEmpty) {\n if (message.multiMessage.id !== responseAggregator!.length + 1) {\n const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator!.length + 1}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n responseAggregator!.push(message.response);\n }\n\n if (message.multiMessage.isLast) {\n (currentHandler as AnyMultiResponseHandler).resolve(responseAggregator!);\n responseAggregator = undefined;\n currentHandler = undefined;\n }\n } else {\n (currentHandler as AnySingleResponseHandler).resolve(message.response);\n currentHandler = undefined;\n }\n }\n } catch (e: any) {\n return this.assignErrorFactoryIfNotSet(() => {\n rethrowMeaningfulError(e, true);\n }, currentHandler?.reject);\n } finally {\n await this.close();\n }\n return null;\n }\n\n /** Executed after termination of incoming message processor */\n private async close(): Promise<void> {\n if (this.closed) return;\n\n this.closed = true;\n\n // Rejecting all messages\n\n while (true) {\n const handler = this.responseHandlerQueue.shift();\n if (!handler) break;\n if (this.errorFactory) handler.reject(new RethrowError(this.errorFactory));\n else handler.reject(new Error('no reply'));\n }\n\n // closing outgoing stream\n await this.stream.requests.complete();\n }\n\n /** Forcefully close the transaction, terminate all connections and reject all pending requests */\n public abort(cause?: Error) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`transaction aborted`, { cause });\n });\n this.abortController.abort(cause);\n }\n\n /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */\n public async await(): Promise<void> {\n // for those who want to understand \"why?\":\n // this way there is no hanging promise that will complete with rejection\n // until await is implicitly requested, the this.incomingProcessorResult\n // always resolves with success\n\n const processingResult = await this.incomingProcessorResult;\n if (processingResult !== null) processingResult();\n }\n\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: false\n ): Promise<OneOfKind<ServerMessageResponse, Kind>>;\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: true\n ): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;\n /** Generate proper client message and send it to the server, and returns a promise of future response. */\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: boolean,\n ): Promise<OneOfKind<ServerMessageResponse, Kind> | OneOfKind<ServerMessageResponse, Kind>[]> {\n if (this.errorFactory) return Promise.reject(new RethrowError(this.errorFactory));\n\n if (this.closed) return Promise.reject(new Error('Transaction already closed'));\n\n // Note: Promise synchronously executes a callback passed to a constructor\n const result = new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\n });\n\n // Awaiting message dispatch to catch any associated errors.\n // There is no hurry, we are not going to receive a response until message is sent.\n await this.stream.requests.send({\n requestId: this.requestIdxCounter++,\n request: r,\n });\n\n try {\n return await result;\n } catch (e: any) {\n if (e instanceof RethrowError) e.rethrowLambda();\n throw new Error('Error while waiting for response', { cause: e });\n }\n }\n\n private _completed = false;\n\n /** Safe to call multiple times */\n public async complete() {\n if (this._completed) return;\n this._completed = true;\n await this.stream.requests.complete();\n }\n}\n"],"names":[],"mappings":";;;AA+CA,SAAS,qBAAqB,CAC5B,IAAU,EACV,mBAA4B,EAC5B,OAE2D,EAC3D,MAA0B,EAAA;IAE1B,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAwB;AAC7E;AAEA,SAAS,aAAa,CAAC,MAAc,EAAA;AACnC,IAAA,OAAO,MAAM,CAAC,IAAI,KAAK,mBAAmB;AAC5C;AAEM,MAAO,YAAa,SAAQ,KAAK,CAAA;AAET,IAAA,aAAA;IAD5B,IAAI,GAAG,cAAc;AACrB,IAAA,WAAA,CAA4B,aAA0B,EAAA;QACpD,KAAK,CAAC,+CAA+C,CAAC;QAD5B,IAAA,CAAA,aAAa,GAAb,aAAa;IAEzC;AACD;MAEY,eAAe,CAAA;;AAET,IAAA,MAAM;;AAGN,IAAA,eAAe,GAAG,IAAI,eAAe,EAAE;AAExD;AACuC;IAC/B,iBAAiB,GAAG,CAAC;;AAGZ,IAAA,oBAAoB,GAAG,IAAI,MAAM,EAAsB;AAExE;;AAEoG;IAC5F,sBAAsB,GAAG,EAAE;AAEnC;AAC+B;IACvB,MAAM,GAAG,KAAK;;IAEd,SAAS,GAAG,KAAK;;AAGjB,IAAA,YAAY;;AAGH,IAAA,aAAa,GAAG,IAAI,CAAC,GAAG,EAAE;AAE1B,IAAA,uBAAuB;AAExC,IAAA,WAAA,CAAY,aAAqD,EAAA;QAC/D,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC;;AAGxD,QAAA,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC,sBAAsB,EAAE;IAC9D;IAEQ,0BAA0B,CAChC,YAAyB,EACzB,MAA2B,EAAA;QAE3B,IAAI,MAAM,KAAK,SAAS;AAAE,YAAA,MAAM,CAAC,IAAI,YAAY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QAEjF,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;;QAG/E,MAAM,MAAM,GAAG,IAAI,OAAO,CAAyC,CAAC,OAAO,EAAE,MAAM,KAAI;AACrF,YAAA,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAC5B,qBAAqB,CAAC,CAAC,CAAC,SAAS,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,CAAC,CACzE;AACH,QAAA,CAAC,CAAC;;;AAIF,QAAA,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC9B,YAAA,SAAS,EAAE,IAAI,CAAC,iBAAiB,EAAE;AACnC,YAAA,OAAO,EAAE,CAAC;AACX,SAAA,CAAC;AAEF,QAAA,IAAI;YACF,OAAO,MAAM,MAAM;QACrB;QAAE,OAAO,CAAM,EAAE;YACf,IAAI,CAAC,YAAY,YAAY;gBAAE,CAAC,CAAC,aAAa,EAAE;YAChD,MAAM,IAAI,KAAK,CAAC,kCAAkC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;QACnE;IACF;IAEQ,UAAU,GAAG,KAAK;;AAGnB,IAAA,MAAM,QAAQ,GAAA;QACnB,IAAI,IAAI,CAAC,UAAU;YAAE;AACrB,QAAA,IAAI,CAAC,UAAU,GAAG,IAAI;QACtB,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE;IACvC;AACD;;;;"}
1
+ {"version":3,"file":"ll_transaction.js","sources":["../../src/core/ll_transaction.ts"],"sourcesContent":["import type {\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from '../proto/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport type { DuplexStreamingCall } from '@protobuf-ts/runtime-rpc';\nimport Denque from 'denque';\nimport type { Status } from '../proto/github.com/googleapis/googleapis/google/rpc/status';\nimport {\n PlErrorCodeNotFound,\n RecoverablePlError,\n rethrowMeaningfulError,\n UnrecoverablePlError,\n} from './errors';\nimport { StatefulPromise } from './StatefulPromise';\n\nexport type ClientMessageRequest = TxAPI_ClientMessage['request'];\n\nexport type ServerMessageResponse = TxAPI_ServerMessage['response'];\n\ntype TxStream = DuplexStreamingCall<TxAPI_ClientMessage, TxAPI_ServerMessage>;\n\nexport type OneOfKind<T extends { oneofKind: unknown }, Kind extends T['oneofKind']> = Extract<\n T,\n { oneofKind: Kind }\n>;\n\ninterface SingleResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: false;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>) => void;\n reject: (e: Error) => void;\n}\n\ninterface MultiResponseHandler<Kind extends ServerMessageResponse['oneofKind']> {\n kind: Kind;\n expectMultiResponse: true;\n resolve: (v: OneOfKind<ServerMessageResponse, Kind>[]) => void;\n reject: (e: Error) => void;\n}\n\ntype AnySingleResponseHandler = SingleResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyMultiResponseHandler = MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\ntype AnyResponseHandler =\n | SingleResponseHandler<ServerMessageResponse['oneofKind']>\n | MultiResponseHandler<ServerMessageResponse['oneofKind']>;\n\nfunction createResponseHandler<Kind extends ServerMessageResponse['oneofKind']>(\n kind: Kind,\n expectMultiResponse: boolean,\n resolve:\n | ((v: OneOfKind<ServerMessageResponse, Kind>) => void)\n | ((v: OneOfKind<ServerMessageResponse, Kind>[]) => void),\n reject: (e: Error) => void,\n): AnyResponseHandler {\n return { kind, expectMultiResponse, resolve, reject } as AnyResponseHandler;\n}\n\nfunction isRecoverable(status: Status): boolean {\n return status.code === PlErrorCodeNotFound;\n}\n\nexport class RethrowError extends Error {\n name = 'RethrowError';\n constructor(public readonly rethrowLambda: () => never) {\n super('Rethrow error, you should never see this one.');\n }\n}\n\nexport class LLPlTransaction {\n /** Bidirectional channel through which transaction communicates with the server */\n private readonly stream: TxStream;\n\n /** Used to abort ongoing transaction stream */\n private readonly abortController = new AbortController();\n\n /** Counter of sent requests, used to calculate which future response will correspond to this request.\n * Incremented on each sent request. */\n private requestIdxCounter = 0;\n\n /** Queue from which incoming message processor takes handlers to which pass incoming messages */\n private readonly responseHandlerQueue = new Denque<AnyResponseHandler>();\n\n /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible\n * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the\n * same way it is tracked on the server, so client can synchronously return such ids to the user. */\n private localResourceIdCounter = 0n;\n\n /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages\n * to be sent to the stream. */\n private closed = false;\n /** Whether the outgoing stream was already closed. */\n private completed = false;\n\n /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */\n private errorFactory?: () => never;\n\n /** Timestamp when transaction was opened */\n private readonly openTimestamp = Date.now();\n\n private readonly incomingProcessorResult: Promise<(() => never) | null>;\n\n constructor(streamFactory: (abortSignal: AbortSignal) => TxStream) {\n this.stream = streamFactory(this.abortController.signal);\n\n // Starting incoming event processor\n this.incomingProcessorResult = this.incomingEventProcessor();\n }\n\n private assignErrorFactoryIfNotSet(\n errorFactory: () => never,\n reject?: (e: Error) => void,\n ): () => never {\n if (reject !== undefined) reject(new RethrowError(errorFactory));\n if (this.errorFactory) return errorFactory;\n this.errorFactory = errorFactory;\n return errorFactory;\n }\n\n private async incomingEventProcessor(): Promise<(() => never) | null> {\n /** Counter of received responses, used to check consistency of responses.\n * Increments on each received message. */\n let expectedId = -1;\n\n // defined externally to make possible to communicate any processing errors\n // to the specific request on which it happened\n let currentHandler: AnyResponseHandler | undefined = undefined;\n let responseAggregator: ServerMessageResponse[] | undefined = undefined;\n try {\n for await (const message of this.stream.responses) {\n if (currentHandler === undefined) {\n currentHandler = this.responseHandlerQueue.shift();\n\n if (currentHandler === undefined) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`orphan incoming message`);\n });\n break;\n }\n\n // allocating response aggregator array\n if (currentHandler.expectMultiResponse) responseAggregator = [];\n\n expectedId++;\n }\n\n if (message.requestId !== expectedId) {\n const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n });\n break;\n }\n\n if (message.error !== undefined) {\n const status = message.error;\n\n if (isRecoverable(status)) {\n currentHandler.reject(\n new RethrowError(() => {\n throw new RecoverablePlError(status);\n }),\n );\n currentHandler = undefined;\n\n if (message.multiMessage !== undefined && !message.multiMessage.isLast) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error('Unexpected message sequence.');\n });\n break;\n }\n\n // We can continue to work after recoverable errors\n continue;\n } else {\n this.assignErrorFactoryIfNotSet(() => {\n throw new UnrecoverablePlError(status);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n // In case of unrecoverable errors we close the transaction\n break;\n }\n }\n\n if (\n currentHandler.kind !== message.response.oneofKind\n && message?.multiMessage?.isEmpty !== true\n ) {\n const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n if (currentHandler.expectMultiResponse !== (message.multiMessage !== undefined)) {\n const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== undefined}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n // <- at this point we validated everything we can at this level\n\n if (message.multiMessage !== undefined) {\n if (!message.multiMessage.isEmpty) {\n if (message.multiMessage.id !== responseAggregator!.length + 1) {\n const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator!.length + 1}`;\n\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(errorMessage);\n }, currentHandler.reject);\n currentHandler = undefined;\n\n break;\n }\n\n responseAggregator!.push(message.response);\n }\n\n if (message.multiMessage.isLast) {\n (currentHandler as AnyMultiResponseHandler).resolve(responseAggregator!);\n responseAggregator = undefined;\n currentHandler = undefined;\n }\n } else {\n (currentHandler as AnySingleResponseHandler).resolve(message.response);\n currentHandler = undefined;\n }\n }\n } catch (e: any) {\n return this.assignErrorFactoryIfNotSet(() => {\n rethrowMeaningfulError(e, true);\n }, currentHandler?.reject);\n } finally {\n await this.close();\n }\n return null;\n }\n\n /** Executed after termination of incoming message processor */\n private async close(): Promise<void> {\n if (this.closed) return;\n\n this.closed = true;\n\n // Rejecting all messages\n\n while (true) {\n const handler = this.responseHandlerQueue.shift();\n if (!handler) break;\n if (this.errorFactory) handler.reject(new RethrowError(this.errorFactory));\n else handler.reject(new Error('no reply'));\n }\n\n // closing outgoing stream\n await this.stream.requests.complete();\n }\n\n /** Forcefully close the transaction, terminate all connections and reject all pending requests */\n public abort(cause?: Error) {\n this.assignErrorFactoryIfNotSet(() => {\n throw new Error(`transaction aborted`, { cause });\n });\n this.abortController.abort(cause);\n }\n\n /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */\n public async await(): Promise<void> {\n // for those who want to understand \"why?\":\n // this way there is no hanging promise that will complete with rejection\n // until await is implicitly requested, the this.incomingProcessorResult\n // always resolves with success\n\n const processingResult = await this.incomingProcessorResult;\n if (processingResult !== null) processingResult();\n }\n\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: false\n ): Promise<OneOfKind<ServerMessageResponse, Kind>>;\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: true\n ): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;\n /** Generate proper client message and send it to the server, and returns a promise of future response. */\n public async send<Kind extends ClientMessageRequest['oneofKind']>(\n r: OneOfKind<ClientMessageRequest, Kind>,\n expectMultiResponse: boolean,\n ): Promise<OneOfKind<ServerMessageResponse, Kind> | OneOfKind<ServerMessageResponse, Kind>[]> {\n if (this.errorFactory) return Promise.reject(new RethrowError(this.errorFactory));\n\n if (this.closed) return Promise.reject(new Error('Transaction already closed'));\n\n // Note: Promise synchronously executes a callback passed to a constructor\n const result = StatefulPromise.fromDeferredReject(new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\n }));\n\n // Awaiting message dispatch to catch any associated errors.\n // There is no hurry, we are not going to receive a response until message is sent.\n await this.stream.requests.send({\n requestId: this.requestIdxCounter++,\n request: r,\n });\n\n try {\n return await result;\n } catch (e: any) {\n if (e instanceof RethrowError) e.rethrowLambda();\n throw new Error('Error while waiting for response', { cause: e });\n }\n }\n\n private _completed = false;\n\n /** Safe to call multiple times */\n public async complete() {\n if (this._completed) return;\n this._completed = true;\n await this.stream.requests.complete();\n }\n}\n"],"names":[],"mappings":";;;;AAgDA,SAAS,qBAAqB,CAC5B,IAAU,EACV,mBAA4B,EAC5B,OAE2D,EAC3D,MAA0B,EAAA;IAE1B,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAwB;AAC7E;AAEA,SAAS,aAAa,CAAC,MAAc,EAAA;AACnC,IAAA,OAAO,MAAM,CAAC,IAAI,KAAK,mBAAmB;AAC5C;AAEM,MAAO,YAAa,SAAQ,KAAK,CAAA;AAET,IAAA,aAAA;IAD5B,IAAI,GAAG,cAAc;AACrB,IAAA,WAAA,CAA4B,aAA0B,EAAA;QACpD,KAAK,CAAC,+CAA+C,CAAC;QAD5B,IAAA,CAAA,aAAa,GAAb,aAAa;IAEzC;AACD;MAEY,eAAe,CAAA;;AAET,IAAA,MAAM;;AAGN,IAAA,eAAe,GAAG,IAAI,eAAe,EAAE;AAExD;AACuC;IAC/B,iBAAiB,GAAG,CAAC;;AAGZ,IAAA,oBAAoB,GAAG,IAAI,MAAM,EAAsB;AAExE;;AAEoG;IAC5F,sB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