@milaboratories/pl-client 2.17.7 → 2.17.9

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 (276) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +43 -0
  2. package/dist/_virtual/_rolldown/runtime.js +18 -0
  3. package/dist/core/PromiseTracker.cjs +33 -33
  4. package/dist/core/PromiseTracker.cjs.map +1 -1
  5. package/dist/core/PromiseTracker.d.ts +10 -7
  6. package/dist/core/PromiseTracker.js +33 -31
  7. package/dist/core/PromiseTracker.js.map +1 -1
  8. package/dist/core/StatefulPromise.cjs +60 -61
  9. package/dist/core/StatefulPromise.cjs.map +1 -1
  10. package/dist/core/StatefulPromise.js +60 -60
  11. package/dist/core/StatefulPromise.js.map +1 -1
  12. package/dist/core/abstract_stream.d.ts +18 -15
  13. package/dist/core/advisory_locks.cjs +42 -49
  14. package/dist/core/advisory_locks.cjs.map +1 -1
  15. package/dist/core/advisory_locks.js +42 -48
  16. package/dist/core/advisory_locks.js.map +1 -1
  17. package/dist/core/auth.cjs +10 -15
  18. package/dist/core/auth.cjs.map +1 -1
  19. package/dist/core/auth.d.ts +7 -3
  20. package/dist/core/auth.js +10 -13
  21. package/dist/core/auth.js.map +1 -1
  22. package/dist/core/cache.d.ts +11 -7
  23. package/dist/core/client.cjs +255 -306
  24. package/dist/core/client.cjs.map +1 -1
  25. package/dist/core/client.d.ts +72 -68
  26. package/dist/core/client.js +253 -285
  27. package/dist/core/client.js.map +1 -1
  28. package/dist/core/config.cjs +81 -99
  29. package/dist/core/config.cjs.map +1 -1
  30. package/dist/core/config.d.ts +93 -90
  31. package/dist/core/config.js +81 -98
  32. package/dist/core/config.js.map +1 -1
  33. package/dist/core/default_client.cjs +84 -125
  34. package/dist/core/default_client.cjs.map +1 -1
  35. package/dist/core/default_client.d.ts +9 -6
  36. package/dist/core/default_client.js +78 -103
  37. package/dist/core/default_client.js.map +1 -1
  38. package/dist/core/driver.cjs +12 -16
  39. package/dist/core/driver.cjs.map +1 -1
  40. package/dist/core/driver.d.ts +18 -14
  41. package/dist/core/driver.js +12 -15
  42. package/dist/core/driver.js.map +1 -1
  43. package/dist/core/error_resource.cjs +5 -4
  44. package/dist/core/error_resource.cjs.map +1 -1
  45. package/dist/core/error_resource.js +5 -3
  46. package/dist/core/error_resource.js.map +1 -1
  47. package/dist/core/errors.cjs +104 -140
  48. package/dist/core/errors.cjs.map +1 -1
  49. package/dist/core/errors.d.ts +34 -30
  50. package/dist/core/errors.js +102 -137
  51. package/dist/core/errors.js.map +1 -1
  52. package/dist/core/final.cjs +63 -89
  53. package/dist/core/final.cjs.map +1 -1
  54. package/dist/core/final.d.ts +8 -4
  55. package/dist/core/final.js +63 -87
  56. package/dist/core/final.js.map +1 -1
  57. package/dist/core/ll_client.cjs +416 -521
  58. package/dist/core/ll_client.cjs.map +1 -1
  59. package/dist/core/ll_client.d.ts +100 -97
  60. package/dist/core/ll_client.js +415 -519
  61. package/dist/core/ll_client.js.map +1 -1
  62. package/dist/core/ll_transaction.cjs +206 -240
  63. package/dist/core/ll_transaction.cjs.map +1 -1
  64. package/dist/core/ll_transaction.d.ts +50 -52
  65. package/dist/core/ll_transaction.js +205 -238
  66. package/dist/core/ll_transaction.js.map +1 -1
  67. package/dist/core/stat.cjs +64 -63
  68. package/dist/core/stat.cjs.map +1 -1
  69. package/dist/core/stat.d.ts +35 -36
  70. package/dist/core/stat.js +64 -62
  71. package/dist/core/stat.js.map +1 -1
  72. package/dist/core/transaction.cjs +613 -650
  73. package/dist/core/transaction.cjs.map +1 -1
  74. package/dist/core/transaction.d.ts +165 -162
  75. package/dist/core/transaction.js +612 -648
  76. package/dist/core/transaction.js.map +1 -1
  77. package/dist/core/type_conversion.cjs +62 -83
  78. package/dist/core/type_conversion.cjs.map +1 -1
  79. package/dist/core/type_conversion.js +61 -81
  80. package/dist/core/type_conversion.js.map +1 -1
  81. package/dist/core/types.cjs +56 -86
  82. package/dist/core/types.cjs.map +1 -1
  83. package/dist/core/types.d.ts +63 -62
  84. package/dist/core/types.js +54 -83
  85. package/dist/core/types.js.map +1 -1
  86. package/dist/core/unauth_client.cjs +35 -41
  87. package/dist/core/unauth_client.cjs.map +1 -1
  88. package/dist/core/unauth_client.d.ts +18 -14
  89. package/dist/core/unauth_client.js +34 -39
  90. package/dist/core/unauth_client.js.map +1 -1
  91. package/dist/core/websocket_stream.cjs +280 -349
  92. package/dist/core/websocket_stream.cjs.map +1 -1
  93. package/dist/core/websocket_stream.js +278 -347
  94. package/dist/core/websocket_stream.js.map +1 -1
  95. package/dist/core/wire.d.ts +21 -17
  96. package/dist/helpers/pl.cjs +71 -73
  97. package/dist/helpers/pl.cjs.map +1 -1
  98. package/dist/helpers/pl.d.ts +40 -41
  99. package/dist/helpers/pl.js +66 -46
  100. package/dist/helpers/pl.js.map +1 -1
  101. package/dist/helpers/poll.cjs +99 -134
  102. package/dist/helpers/poll.cjs.map +1 -1
  103. package/dist/helpers/poll.d.ts +37 -34
  104. package/dist/helpers/poll.js +97 -113
  105. package/dist/helpers/poll.js.map +1 -1
  106. package/dist/helpers/retry_strategy.cjs +82 -87
  107. package/dist/helpers/retry_strategy.cjs.map +1 -1
  108. package/dist/helpers/retry_strategy.js +83 -86
  109. package/dist/helpers/retry_strategy.js.map +1 -1
  110. package/dist/helpers/tx_helpers.cjs +21 -20
  111. package/dist/helpers/tx_helpers.cjs.map +1 -1
  112. package/dist/helpers/tx_helpers.d.ts +11 -7
  113. package/dist/helpers/tx_helpers.js +20 -18
  114. package/dist/helpers/tx_helpers.js.map +1 -1
  115. package/dist/index.cjs +117 -106
  116. package/dist/index.d.ts +17 -17
  117. package/dist/index.js +17 -19
  118. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.cjs +72 -66
  119. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.cjs.map +1 -1
  120. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts +35 -37
  121. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.js +71 -64
  122. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.js.map +1 -1
  123. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +12611 -12866
  124. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -1
  125. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs +226 -226
  126. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs.map +1 -1
  127. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts +281 -330
  128. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js +225 -224
  129. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js.map +1 -1
  130. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +2640 -4294
  131. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js +12608 -12706
  132. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -1
  133. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs +1230 -1089
  134. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs.map +1 -1
  135. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts +393 -420
  136. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.js +1228 -1083
  137. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.js.map +1 -1
  138. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs +142 -143
  139. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs.map +1 -1
  140. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts +62 -64
  141. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.js +140 -141
  142. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.js.map +1 -1
  143. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs +572 -487
  144. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs.map +1 -1
  145. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts +125 -228
  146. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js +572 -485
  147. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js.map +1 -1
  148. package/dist/proto-grpc/google/protobuf/any.cjs +131 -146
  149. package/dist/proto-grpc/google/protobuf/any.cjs.map +1 -1
  150. package/dist/proto-grpc/google/protobuf/any.d.ts +78 -84
  151. package/dist/proto-grpc/google/protobuf/any.js +130 -144
  152. package/dist/proto-grpc/google/protobuf/any.js.map +1 -1
  153. package/dist/proto-grpc/google/protobuf/duration.cjs +92 -100
  154. package/dist/proto-grpc/google/protobuf/duration.cjs.map +1 -1
  155. package/dist/proto-grpc/google/protobuf/duration.d.ts +38 -43
  156. package/dist/proto-grpc/google/protobuf/duration.js +91 -98
  157. package/dist/proto-grpc/google/protobuf/duration.js.map +1 -1
  158. package/dist/proto-grpc/google/protobuf/timestamp.cjs +117 -128
  159. package/dist/proto-grpc/google/protobuf/timestamp.cjs.map +1 -1
  160. package/dist/proto-grpc/google/protobuf/timestamp.d.ts +50 -55
  161. package/dist/proto-grpc/google/protobuf/timestamp.js +116 -126
  162. package/dist/proto-grpc/google/protobuf/timestamp.js.map +1 -1
  163. package/dist/proto-grpc/google/rpc/code.cjs +223 -238
  164. package/dist/proto-grpc/google/rpc/code.cjs.map +1 -1
  165. package/dist/proto-grpc/google/rpc/code.d.ts +209 -206
  166. package/dist/proto-grpc/google/rpc/code.js +221 -237
  167. package/dist/proto-grpc/google/rpc/code.js.map +1 -1
  168. package/dist/proto-rest/index.cjs +67 -66
  169. package/dist/proto-rest/index.cjs.map +1 -1
  170. package/dist/proto-rest/index.d.ts +24 -18
  171. package/dist/proto-rest/index.js +61 -65
  172. package/dist/proto-rest/index.js.map +1 -1
  173. package/dist/proto-rest/plapi.d.ts +1400 -1477
  174. package/dist/test/tcp-proxy.cjs +100 -126
  175. package/dist/test/tcp-proxy.cjs.map +1 -1
  176. package/dist/test/tcp-proxy.d.ts +17 -13
  177. package/dist/test/tcp-proxy.js +97 -104
  178. package/dist/test/tcp-proxy.js.map +1 -1
  179. package/dist/test/test_config.cjs +145 -194
  180. package/dist/test/test_config.cjs.map +1 -1
  181. package/dist/test/test_config.d.ts +34 -30
  182. package/dist/test/test_config.js +138 -166
  183. package/dist/test/test_config.js.map +1 -1
  184. package/dist/util/pl.cjs +4 -3
  185. package/dist/util/pl.cjs.map +1 -1
  186. package/dist/util/pl.js +4 -2
  187. package/dist/util/pl.js.map +1 -1
  188. package/dist/util/util.cjs +7 -10
  189. package/dist/util/util.cjs.map +1 -1
  190. package/dist/util/util.js +7 -9
  191. package/dist/util/util.js.map +1 -1
  192. package/package.json +8 -8
  193. package/src/core/errors.ts +1 -1
  194. package/src/core/transaction.ts +123 -133
  195. package/src/core/websocket_stream.ts +10 -1
  196. package/dist/__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 +0 -61
  197. package/dist/__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.map +0 -1
  198. package/dist/__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 +0 -58
  199. package/dist/__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.map +0 -1
  200. package/dist/core/PromiseTracker.d.ts.map +0 -1
  201. package/dist/core/StatefulPromise.d.ts +0 -39
  202. package/dist/core/StatefulPromise.d.ts.map +0 -1
  203. package/dist/core/abstract_stream.d.ts.map +0 -1
  204. package/dist/core/advisory_locks.d.ts +0 -10
  205. package/dist/core/advisory_locks.d.ts.map +0 -1
  206. package/dist/core/auth.d.ts.map +0 -1
  207. package/dist/core/cache.d.ts.map +0 -1
  208. package/dist/core/client.d.ts.map +0 -1
  209. package/dist/core/config.d.ts.map +0 -1
  210. package/dist/core/default_client.d.ts.map +0 -1
  211. package/dist/core/driver.d.ts.map +0 -1
  212. package/dist/core/error_resource.d.ts +0 -6
  213. package/dist/core/error_resource.d.ts.map +0 -1
  214. package/dist/core/errors.d.ts.map +0 -1
  215. package/dist/core/final.d.ts.map +0 -1
  216. package/dist/core/ll_client.d.ts.map +0 -1
  217. package/dist/core/ll_transaction.d.ts.map +0 -1
  218. package/dist/core/stat.d.ts.map +0 -1
  219. package/dist/core/transaction.d.ts.map +0 -1
  220. package/dist/core/type_conversion.d.ts +0 -8
  221. package/dist/core/type_conversion.d.ts.map +0 -1
  222. package/dist/core/types.d.ts.map +0 -1
  223. package/dist/core/unauth_client.d.ts.map +0 -1
  224. package/dist/core/websocket_stream.d.ts +0 -67
  225. package/dist/core/websocket_stream.d.ts.map +0 -1
  226. package/dist/core/wire.d.ts.map +0 -1
  227. package/dist/helpers/pl.d.ts.map +0 -1
  228. package/dist/helpers/poll.d.ts.map +0 -1
  229. package/dist/helpers/retry_strategy.d.ts +0 -24
  230. package/dist/helpers/retry_strategy.d.ts.map +0 -1
  231. package/dist/helpers/state_helpers.d.ts +0 -3
  232. package/dist/helpers/state_helpers.d.ts.map +0 -1
  233. package/dist/helpers/tx_helpers.d.ts.map +0 -1
  234. package/dist/index.cjs.map +0 -1
  235. package/dist/index.d.ts.map +0 -1
  236. package/dist/index.js.map +0 -1
  237. package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts.map +0 -1
  238. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts.map +0 -1
  239. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +0 -1
  240. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts.map +0 -1
  241. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts.map +0 -1
  242. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts +0 -106
  243. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts.map +0 -1
  244. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts.map +0 -1
  245. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/ws-test.d.ts +0 -73
  246. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/ws-test.d.ts.map +0 -1
  247. package/dist/proto-grpc/google/api/http.d.ts +0 -456
  248. package/dist/proto-grpc/google/api/http.d.ts.map +0 -1
  249. package/dist/proto-grpc/google/protobuf/any.d.ts.map +0 -1
  250. package/dist/proto-grpc/google/protobuf/descriptor.d.ts +0 -2340
  251. package/dist/proto-grpc/google/protobuf/descriptor.d.ts.map +0 -1
  252. package/dist/proto-grpc/google/protobuf/duration.d.ts.map +0 -1
  253. package/dist/proto-grpc/google/protobuf/empty.d.ts +0 -32
  254. package/dist/proto-grpc/google/protobuf/empty.d.ts.map +0 -1
  255. package/dist/proto-grpc/google/protobuf/struct.d.ts +0 -187
  256. package/dist/proto-grpc/google/protobuf/struct.d.ts.map +0 -1
  257. package/dist/proto-grpc/google/protobuf/timestamp.d.ts.map +0 -1
  258. package/dist/proto-grpc/google/protobuf/wrappers.d.ts +0 -308
  259. package/dist/proto-grpc/google/protobuf/wrappers.d.ts.map +0 -1
  260. package/dist/proto-grpc/google/rpc/code.d.ts.map +0 -1
  261. package/dist/proto-grpc/google/rpc/error_details.d.ts +0 -654
  262. package/dist/proto-grpc/google/rpc/error_details.d.ts.map +0 -1
  263. package/dist/proto-grpc/google/rpc/http.d.ts +0 -121
  264. package/dist/proto-grpc/google/rpc/http.d.ts.map +0 -1
  265. package/dist/proto-grpc/google/rpc/status.d.ts +0 -55
  266. package/dist/proto-grpc/google/rpc/status.d.ts.map +0 -1
  267. package/dist/proto-rest/index.d.ts.map +0 -1
  268. package/dist/proto-rest/plapi.d.ts.map +0 -1
  269. package/dist/test/tcp-proxy.d.ts.map +0 -1
  270. package/dist/test/test_config.d.ts.map +0 -1
  271. package/dist/util/branding.d.ts +0 -7
  272. package/dist/util/branding.d.ts.map +0 -1
  273. package/dist/util/pl.d.ts +0 -9
  274. package/dist/util/pl.d.ts.map +0 -1
  275. package/dist/util/util.d.ts +0 -2
  276. package/dist/util/util.d.ts.map +0 -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-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { BiDiStream } from \"./abstract_stream\";\nimport Denque from \"denque\";\nimport type { Status } from \"../proto-grpc/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 = BiDiStream<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 // After receiving a terminal response (txCommit or txDiscard), we proactively close the client stream.\n // This ensures consistent behavior between the gRPC and WebSocket transports,\n // since the server closes the connection automatically upon transaction completion in both cases.\n if (this.isTerminalResponse(message) && this.responseHandlerQueue.length === 0) {\n await this.stream.requests.complete();\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(\n new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\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 private isTerminalResponse(message: TxAPI_ServerMessage): boolean {\n const kind = message.response.oneofKind;\n return kind === \"txCommit\" || kind === \"txDiscard\";\n }\n}\n"],"names":["PlErrorCodeNotFound","RecoverablePlError","UnrecoverablePlError","rethrowMeaningfulError","StatefulPromise"],"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,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;AAExE;;AAEoG;IAC5F,sBA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AI;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;AAEQ,IAAA,kBAAkB,CAAC,OAA4B,EAAA;AACrD,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,SAAS;AACvC,QAAA,OAAO,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,WAAW;IACpD;AACD;;;;;"}
1
+ {"version":3,"file":"ll_transaction.cjs","names":["PlErrorCodeNotFound","Denque","RecoverablePlError","UnrecoverablePlError","StatefulPromise"],"sources":["../../src/core/ll_transaction.ts"],"sourcesContent":["import type {\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { BiDiStream } from \"./abstract_stream\";\nimport Denque from \"denque\";\nimport type { Status } from \"../proto-grpc/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 = BiDiStream<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 // After receiving a terminal response (txCommit or txDiscard), we proactively close the client stream.\n // This ensures consistent behavior between the gRPC and WebSocket transports,\n // since the server closes the connection automatically upon transaction completion in both cases.\n if (this.isTerminalResponse(message) && this.responseHandlerQueue.length === 0) {\n await this.stream.requests.complete();\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(\n new Promise<OneOfKind<ServerMessageResponse, Kind>>((resolve, reject) => {\n this.responseHandlerQueue.push(\n createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject),\n );\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 private isTerminalResponse(message: TxAPI_ServerMessage): boolean {\n const kind = message.response.oneofKind;\n return kind === \"txCommit\" || kind === \"txDiscard\";\n }\n}\n"],"mappings":";;;;;;;AAgDA,SAAS,sBACP,MACA,qBACA,SAGA,QACoB;AACpB,QAAO;EAAE;EAAM;EAAqB;EAAS;EAAQ;;AAGvD,SAAS,cAAc,QAAyB;AAC9C,QAAO,OAAO,SAASA;;AAGzB,IAAa,eAAb,cAAkC,MAAM;CACtC,OAAO;CACP,YAAY,AAAgB,eAA4B;AACtD,QAAM,gDAAgD;EAD5B;;;AAK9B,IAAa,kBAAb,MAA6B;;CAE3B,AAAiB;;CAGjB,AAAiB,kBAAkB,IAAI,iBAAiB;;;CAIxD,AAAQ,oBAAoB;;CAG5B,AAAiB,uBAAuB,IAAIC,gBAA4B;;;;CAKxE,AAAQ,yBAAyB;;;CAIjC,AAAQ,SAAS;;CAEjB,AAAQ,YAAY;;CAGpB,AAAQ;;CAGR,AAAiB,gBAAgB,KAAK,KAAK;CAE3C,AAAiB;CAEjB,YAAY,eAAuD;AACjE,OAAK,SAAS,cAAc,KAAK,gBA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,WAAW,CAAC;;AAI5C,QAAM,KAAK,OAAO,SAAS,UAAU;;;CAIvC,AAAO,MAAM,OAAe;AAC1B,OAAK,iCAAiC;AACpC,SAAM,IAAI,MAAM,uBAAuB,EAAE,OAAO,CAAC;IACjD;AACF,OAAK,gBAAgB,MAAM,MAAM;;;CAInC,MAAa,QAAuB;EAMlC,MAAM,mBAAmB,MAAM,KAAK;AACpC,MAAI,qBAAqB,KAAM,mBAAkB;;;CAYnD,MAAa,KACX,GACA,qBAC4F;AAC5F,MAAI,KAAK,aAAc,QAAO,QAAQ,OAAO,IAAI,aAAa,KAAK,aAAa,CAAC;AAEjF,MAAI,KAAK,OAAQ,QAAO,QAAQ,uBAAO,IAAI,MAAM,6BAA6B,CAAC;EAG/E,MAAM,SAASC,wCAAgB,mBAC7B,IAAI,SAAiD,SAAS,WAAW;AACvE,QAAK,qBAAqB,KACxB,sBAAsB,EAAE,WAAW,qBAAqB,SAAS,OAAO,CACzE;IACD,CACH;AAID,QAAM,KAAK,OAAO,SAAS,KAAK;GAC9B,WAAW,KAAK;GAChB,SAAS;GACV,CAAC;AAEF,MAAI;AACF,UAAO,MAAM;WACN,GAAQ;AACf,OAAI,aAAa,aAAc,GAAE,eAAe;AAChD,SAAM,IAAI,MAAM,oCAAoC,EAAE,OAAO,GAAG,CAAC;;;CAIrE,AAAQ,aAAa;;CAGrB,MAAa,WAAW;AACtB,MAAI,KAAK,WAAY;AACrB,OAAK,aAAa;AAClB,QAAM,KAAK,OAAO,SAAS,UAAU;;CAGvC,AAAQ,mBAAmB,SAAuC;EAChE,MAAM,OAAO,QAAQ,SAAS;AAC9B,SAAO,SAAS,cAAc,SAAS"}
@@ -1,57 +1,55 @@
1
- import type { TxAPI_ClientMessage, TxAPI_ServerMessage } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api";
2
- import type { BiDiStream } from "./abstract_stream";
3
- export type ClientMessageRequest = TxAPI_ClientMessage["request"];
4
- export type ServerMessageResponse = TxAPI_ServerMessage["response"];
1
+ import { TxAPI_ClientMessage, TxAPI_ServerMessage } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
2
+ import { BiDiStream } from "./abstract_stream.js";
3
+
4
+ //#region src/core/ll_transaction.d.ts
5
+ type ClientMessageRequest = TxAPI_ClientMessage["request"];
6
+ type ServerMessageResponse = TxAPI_ServerMessage["response"];
5
7
  type TxStream = BiDiStream<TxAPI_ClientMessage, TxAPI_ServerMessage>;
6
- export type OneOfKind<T extends {
7
- oneofKind: unknown;
8
+ type OneOfKind<T extends {
9
+ oneofKind: unknown;
8
10
  }, Kind extends T["oneofKind"]> = Extract<T, {
9
- oneofKind: Kind;
11
+ oneofKind: Kind;
10
12
  }>;
11
- export declare class RethrowError extends Error {
12
- readonly rethrowLambda: () => never;
13
- name: string;
14
- constructor(rethrowLambda: () => never);
13
+ declare class LLPlTransaction {
14
+ /** Bidirectional channel through which transaction communicates with the server */
15
+ private readonly stream;
16
+ /** Used to abort ongoing transaction stream */
17
+ private readonly abortController;
18
+ /** Counter of sent requests, used to calculate which future response will correspond to this request.
19
+ * Incremented on each sent request. */
20
+ private requestIdxCounter;
21
+ /** Queue from which incoming message processor takes handlers to which pass incoming messages */
22
+ private readonly responseHandlerQueue;
23
+ /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible
24
+ * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the
25
+ * same way it is tracked on the server, so client can synchronously return such ids to the user. */
26
+ private localResourceIdCounter;
27
+ /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages
28
+ * to be sent to the stream. */
29
+ private closed;
30
+ /** Whether the outgoing stream was already closed. */
31
+ private completed;
32
+ /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */
33
+ private errorFactory?;
34
+ /** Timestamp when transaction was opened */
35
+ private readonly openTimestamp;
36
+ private readonly incomingProcessorResult;
37
+ constructor(streamFactory: (abortSignal: AbortSignal) => TxStream);
38
+ private assignErrorFactoryIfNotSet;
39
+ private incomingEventProcessor;
40
+ /** Executed after termination of incoming message processor */
41
+ private close;
42
+ /** Forcefully close the transaction, terminate all connections and reject all pending requests */
43
+ abort(cause?: Error): void;
44
+ /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */
45
+ await(): Promise<void>;
46
+ send<Kind extends ClientMessageRequest["oneofKind"]>(r: OneOfKind<ClientMessageRequest, Kind>, expectMultiResponse: false): Promise<OneOfKind<ServerMessageResponse, Kind>>;
47
+ send<Kind extends ClientMessageRequest["oneofKind"]>(r: OneOfKind<ClientMessageRequest, Kind>, expectMultiResponse: true): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;
48
+ private _completed;
49
+ /** Safe to call multiple times */
50
+ complete(): Promise<void>;
51
+ private isTerminalResponse;
15
52
  }
16
- export declare class LLPlTransaction {
17
- /** Bidirectional channel through which transaction communicates with the server */
18
- private readonly stream;
19
- /** Used to abort ongoing transaction stream */
20
- private readonly abortController;
21
- /** Counter of sent requests, used to calculate which future response will correspond to this request.
22
- * Incremented on each sent request. */
23
- private requestIdxCounter;
24
- /** Queue from which incoming message processor takes handlers to which pass incoming messages */
25
- private readonly responseHandlerQueue;
26
- /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible
27
- * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the
28
- * same way it is tracked on the server, so client can synchronously return such ids to the user. */
29
- private localResourceIdCounter;
30
- /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages
31
- * to be sent to the stream. */
32
- private closed;
33
- /** Whether the outgoing stream was already closed. */
34
- private completed;
35
- /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */
36
- private errorFactory?;
37
- /** Timestamp when transaction was opened */
38
- private readonly openTimestamp;
39
- private readonly incomingProcessorResult;
40
- constructor(streamFactory: (abortSignal: AbortSignal) => TxStream);
41
- private assignErrorFactoryIfNotSet;
42
- private incomingEventProcessor;
43
- /** Executed after termination of incoming message processor */
44
- private close;
45
- /** Forcefully close the transaction, terminate all connections and reject all pending requests */
46
- abort(cause?: Error): void;
47
- /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */
48
- await(): Promise<void>;
49
- send<Kind extends ClientMessageRequest["oneofKind"]>(r: OneOfKind<ClientMessageRequest, Kind>, expectMultiResponse: false): Promise<OneOfKind<ServerMessageResponse, Kind>>;
50
- send<Kind extends ClientMessageRequest["oneofKind"]>(r: OneOfKind<ClientMessageRequest, Kind>, expectMultiResponse: true): Promise<OneOfKind<ServerMessageResponse, Kind>[]>;
51
- private _completed;
52
- /** Safe to call multiple times */
53
- complete(): Promise<void>;
54
- private isTerminalResponse;
55
- }
56
- export {};
53
+ //#endregion
54
+ export { LLPlTransaction };
57
55
  //# sourceMappingURL=ll_transaction.d.ts.map
@@ -1,244 +1,211 @@
1
- import Denque from 'denque';
2
- import { RecoverablePlError, UnrecoverablePlError, rethrowMeaningfulError, PlErrorCodeNotFound } from './errors.js';
3
- import { StatefulPromise } from './StatefulPromise.js';
1
+ import { PlErrorCodeNotFound, RecoverablePlError, UnrecoverablePlError, rethrowMeaningfulError } from "./errors.js";
2
+ import { StatefulPromise } from "./StatefulPromise.js";
3
+ import Denque from "denque";
4
4
 
5
+ //#region src/core/ll_transaction.ts
5
6
  function createResponseHandler(kind, expectMultiResponse, resolve, reject) {
6
- return { kind, expectMultiResponse, resolve, reject };
7
+ return {
8
+ kind,
9
+ expectMultiResponse,
10
+ resolve,
11
+ reject
12
+ };
7
13
  }
8
14
  function isRecoverable(status) {
9
- return status.code === PlErrorCodeNotFound;
10
- }
11
- class RethrowError extends Error {
12
- rethrowLambda;
13
- name = "RethrowError";
14
- constructor(rethrowLambda) {
15
- super("Rethrow error, you should never see this one.");
16
- this.rethrowLambda = rethrowLambda;
17
- }
18
- }
19
- class LLPlTransaction {
20
- /** Bidirectional channel through which transaction communicates with the server */
21
- stream;
22
- /** Used to abort ongoing transaction stream */
23
- abortController = new AbortController();
24
- /** Counter of sent requests, used to calculate which future response will correspond to this request.
25
- * Incremented on each sent request. */
26
- requestIdxCounter = 0;
27
- /** Queue from which incoming message processor takes handlers to which pass incoming messages */
28
- responseHandlerQueue = new Denque();
29
- /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible
30
- * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the
31
- * same way it is tracked on the server, so client can synchronously return such ids to the user. */
32
- localResourceIdCounter = 0n;
33
- /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages
34
- * to be sent to the stream. */
35
- closed = false;
36
- /** Whether the outgoing stream was already closed. */
37
- completed = false;
38
- /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */
39
- errorFactory;
40
- /** Timestamp when transaction was opened */
41
- openTimestamp = Date.now();
42
- incomingProcessorResult;
43
- constructor(streamFactory) {
44
- this.stream = streamFactory(this.abortController.signal);
45
- // Starting incoming event processor
46
- this.incomingProcessorResult = this.incomingEventProcessor();
47
- }
48
- assignErrorFactoryIfNotSet(errorFactory, reject) {
49
- if (reject !== undefined)
50
- reject(new RethrowError(errorFactory));
51
- if (this.errorFactory)
52
- return errorFactory;
53
- this.errorFactory = errorFactory;
54
- return errorFactory;
55
- }
56
- async incomingEventProcessor() {
57
- /** Counter of received responses, used to check consistency of responses.
58
- * Increments on each received message. */
59
- let expectedId = -1;
60
- // defined externally to make possible to communicate any processing errors
61
- // to the specific request on which it happened
62
- let currentHandler = undefined;
63
- let responseAggregator = undefined;
64
- try {
65
- for await (const message of this.stream.responses) {
66
- if (currentHandler === undefined) {
67
- currentHandler = this.responseHandlerQueue.shift();
68
- if (currentHandler === undefined) {
69
- this.assignErrorFactoryIfNotSet(() => {
70
- throw new Error(`orphan incoming message`);
71
- });
72
- break;
73
- }
74
- // allocating response aggregator array
75
- if (currentHandler.expectMultiResponse)
76
- responseAggregator = [];
77
- expectedId++;
78
- }
79
- if (message.requestId !== expectedId) {
80
- const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;
81
- this.assignErrorFactoryIfNotSet(() => {
82
- throw new Error(errorMessage);
83
- });
84
- break;
85
- }
86
- if (message.error !== undefined) {
87
- const status = message.error;
88
- if (isRecoverable(status)) {
89
- currentHandler.reject(new RethrowError(() => {
90
- throw new RecoverablePlError(status);
91
- }));
92
- currentHandler = undefined;
93
- if (message.multiMessage !== undefined && !message.multiMessage.isLast) {
94
- this.assignErrorFactoryIfNotSet(() => {
95
- throw new Error("Unexpected message sequence.");
96
- });
97
- break;
98
- }
99
- // We can continue to work after recoverable errors
100
- continue;
101
- }
102
- else {
103
- this.assignErrorFactoryIfNotSet(() => {
104
- throw new UnrecoverablePlError(status);
105
- }, currentHandler.reject);
106
- currentHandler = undefined;
107
- // In case of unrecoverable errors we close the transaction
108
- break;
109
- }
110
- }
111
- if (currentHandler.kind !== message.response.oneofKind &&
112
- message?.multiMessage?.isEmpty !== true) {
113
- const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;
114
- this.assignErrorFactoryIfNotSet(() => {
115
- throw new Error(errorMessage);
116
- }, currentHandler.reject);
117
- currentHandler = undefined;
118
- break;
119
- }
120
- if (currentHandler.expectMultiResponse !== (message.multiMessage !== undefined)) {
121
- const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== undefined}`;
122
- this.assignErrorFactoryIfNotSet(() => {
123
- throw new Error(errorMessage);
124
- }, currentHandler.reject);
125
- currentHandler = undefined;
126
- break;
127
- }
128
- // <- at this point we validated everything we can at this level
129
- if (message.multiMessage !== undefined) {
130
- if (!message.multiMessage.isEmpty) {
131
- if (message.multiMessage.id !== responseAggregator.length + 1) {
132
- const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator.length + 1}`;
133
- this.assignErrorFactoryIfNotSet(() => {
134
- throw new Error(errorMessage);
135
- }, currentHandler.reject);
136
- currentHandler = undefined;
137
- break;
138
- }
139
- responseAggregator.push(message.response);
140
- }
141
- if (message.multiMessage.isLast) {
142
- currentHandler.resolve(responseAggregator);
143
- responseAggregator = undefined;
144
- currentHandler = undefined;
145
- }
146
- }
147
- else {
148
- currentHandler.resolve(message.response);
149
- currentHandler = undefined;
150
- }
151
- // After receiving a terminal response (txCommit or txDiscard), we proactively close the client stream.
152
- // This ensures consistent behavior between the gRPC and WebSocket transports,
153
- // since the server closes the connection automatically upon transaction completion in both cases.
154
- if (this.isTerminalResponse(message) && this.responseHandlerQueue.length === 0) {
155
- await this.stream.requests.complete();
156
- }
157
- }
158
- }
159
- catch (e) {
160
- return this.assignErrorFactoryIfNotSet(() => {
161
- rethrowMeaningfulError(e, true);
162
- }, currentHandler?.reject);
163
- }
164
- finally {
165
- await this.close();
166
- }
167
- return null;
168
- }
169
- /** Executed after termination of incoming message processor */
170
- async close() {
171
- if (this.closed)
172
- return;
173
- this.closed = true;
174
- // Rejecting all messages
175
- while (true) {
176
- const handler = this.responseHandlerQueue.shift();
177
- if (!handler)
178
- break;
179
- if (this.errorFactory)
180
- handler.reject(new RethrowError(this.errorFactory));
181
- else
182
- handler.reject(new Error("no reply"));
183
- }
184
- // closing outgoing stream
185
- await this.stream.requests.complete();
186
- }
187
- /** Forcefully close the transaction, terminate all connections and reject all pending requests */
188
- abort(cause) {
189
- this.assignErrorFactoryIfNotSet(() => {
190
- throw new Error(`transaction aborted`, { cause });
191
- });
192
- this.abortController.abort(cause);
193
- }
194
- /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */
195
- async await() {
196
- // for those who want to understand "why?":
197
- // this way there is no hanging promise that will complete with rejection
198
- // until await is implicitly requested, the this.incomingProcessorResult
199
- // always resolves with success
200
- const processingResult = await this.incomingProcessorResult;
201
- if (processingResult !== null)
202
- processingResult();
203
- }
204
- /** Generate proper client message and send it to the server, and returns a promise of future response. */
205
- async send(r, expectMultiResponse) {
206
- if (this.errorFactory)
207
- return Promise.reject(new RethrowError(this.errorFactory));
208
- if (this.closed)
209
- return Promise.reject(new Error("Transaction already closed"));
210
- // Note: Promise synchronously executes a callback passed to a constructor
211
- const result = StatefulPromise.fromDeferredReject(new Promise((resolve, reject) => {
212
- this.responseHandlerQueue.push(createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject));
213
- }));
214
- // Awaiting message dispatch to catch any associated errors.
215
- // There is no hurry, we are not going to receive a response until message is sent.
216
- await this.stream.requests.send({
217
- requestId: this.requestIdxCounter++,
218
- request: r,
219
- });
220
- try {
221
- return await result;
222
- }
223
- catch (e) {
224
- if (e instanceof RethrowError)
225
- e.rethrowLambda();
226
- throw new Error("Error while waiting for response", { cause: e });
227
- }
228
- }
229
- _completed = false;
230
- /** Safe to call multiple times */
231
- async complete() {
232
- if (this._completed)
233
- return;
234
- this._completed = true;
235
- await this.stream.requests.complete();
236
- }
237
- isTerminalResponse(message) {
238
- const kind = message.response.oneofKind;
239
- return kind === "txCommit" || kind === "txDiscard";
240
- }
15
+ return status.code === PlErrorCodeNotFound;
241
16
  }
17
+ var RethrowError = class extends Error {
18
+ name = "RethrowError";
19
+ constructor(rethrowLambda) {
20
+ super("Rethrow error, you should never see this one.");
21
+ this.rethrowLambda = rethrowLambda;
22
+ }
23
+ };
24
+ var LLPlTransaction = class {
25
+ /** Bidirectional channel through which transaction communicates with the server */
26
+ stream;
27
+ /** Used to abort ongoing transaction stream */
28
+ abortController = new AbortController();
29
+ /** Counter of sent requests, used to calculate which future response will correspond to this request.
30
+ * Incremented on each sent request. */
31
+ requestIdxCounter = 0;
32
+ /** Queue from which incoming message processor takes handlers to which pass incoming messages */
33
+ responseHandlerQueue = new Denque();
34
+ /** Each new resource, created by the transaction, is assigned with virtual (local) resource id, to make it possible
35
+ * to populate its fields without awaiting actual resource id. This counter tracks those ids on client side, the
36
+ * same way it is tracked on the server, so client can synchronously return such ids to the user. */
37
+ localResourceIdCounter = 0n;
38
+ /** Switches to true, when this transaction closes due to normal or exceptional conditions. Prevents any new messages
39
+ * to be sent to the stream. */
40
+ closed = false;
41
+ /** Whether the outgoing stream was already closed. */
42
+ completed = false;
43
+ /** If this transaction was terminated due to error, this is a generator to create new errors if corresponding response is required. */
44
+ errorFactory;
45
+ /** Timestamp when transaction was opened */
46
+ openTimestamp = Date.now();
47
+ incomingProcessorResult;
48
+ constructor(streamFactory) {
49
+ this.stream = streamFactory(this.abortController.signal);
50
+ this.incomingProcessorResult = this.incomingEventProcessor();
51
+ }
52
+ assignErrorFactoryIfNotSet(errorFactory, reject) {
53
+ if (reject !== void 0) reject(new RethrowError(errorFactory));
54
+ if (this.errorFactory) return errorFactory;
55
+ this.errorFactory = errorFactory;
56
+ return errorFactory;
57
+ }
58
+ async incomingEventProcessor() {
59
+ /** Counter of received responses, used to check consistency of responses.
60
+ * Increments on each received message. */
61
+ let expectedId = -1;
62
+ let currentHandler = void 0;
63
+ let responseAggregator = void 0;
64
+ try {
65
+ for await (const message of this.stream.responses) {
66
+ if (currentHandler === void 0) {
67
+ currentHandler = this.responseHandlerQueue.shift();
68
+ if (currentHandler === void 0) {
69
+ this.assignErrorFactoryIfNotSet(() => {
70
+ throw new Error(`orphan incoming message`);
71
+ });
72
+ break;
73
+ }
74
+ if (currentHandler.expectMultiResponse) responseAggregator = [];
75
+ expectedId++;
76
+ }
77
+ if (message.requestId !== expectedId) {
78
+ const errorMessage = `out of order messages, ${message.requestId} !== ${expectedId}`;
79
+ this.assignErrorFactoryIfNotSet(() => {
80
+ throw new Error(errorMessage);
81
+ });
82
+ break;
83
+ }
84
+ if (message.error !== void 0) {
85
+ const status = message.error;
86
+ if (isRecoverable(status)) {
87
+ currentHandler.reject(new RethrowError(() => {
88
+ throw new RecoverablePlError(status);
89
+ }));
90
+ currentHandler = void 0;
91
+ if (message.multiMessage !== void 0 && !message.multiMessage.isLast) {
92
+ this.assignErrorFactoryIfNotSet(() => {
93
+ throw new Error("Unexpected message sequence.");
94
+ });
95
+ break;
96
+ }
97
+ continue;
98
+ } else {
99
+ this.assignErrorFactoryIfNotSet(() => {
100
+ throw new UnrecoverablePlError(status);
101
+ }, currentHandler.reject);
102
+ currentHandler = void 0;
103
+ break;
104
+ }
105
+ }
106
+ if (currentHandler.kind !== message.response.oneofKind && message?.multiMessage?.isEmpty !== true) {
107
+ const errorMessage = `inconsistent request response types: ${currentHandler.kind} !== ${message.response.oneofKind}`;
108
+ this.assignErrorFactoryIfNotSet(() => {
109
+ throw new Error(errorMessage);
110
+ }, currentHandler.reject);
111
+ currentHandler = void 0;
112
+ break;
113
+ }
114
+ if (currentHandler.expectMultiResponse !== (message.multiMessage !== void 0)) {
115
+ const errorMessage = `inconsistent multi state: ${currentHandler.expectMultiResponse} !== ${message.multiMessage !== void 0}`;
116
+ this.assignErrorFactoryIfNotSet(() => {
117
+ throw new Error(errorMessage);
118
+ }, currentHandler.reject);
119
+ currentHandler = void 0;
120
+ break;
121
+ }
122
+ if (message.multiMessage !== void 0) {
123
+ if (!message.multiMessage.isEmpty) {
124
+ if (message.multiMessage.id !== responseAggregator.length + 1) {
125
+ const errorMessage = `inconsistent multi id: ${message.multiMessage.id} !== ${responseAggregator.length + 1}`;
126
+ this.assignErrorFactoryIfNotSet(() => {
127
+ throw new Error(errorMessage);
128
+ }, currentHandler.reject);
129
+ currentHandler = void 0;
130
+ break;
131
+ }
132
+ responseAggregator.push(message.response);
133
+ }
134
+ if (message.multiMessage.isLast) {
135
+ currentHandler.resolve(responseAggregator);
136
+ responseAggregator = void 0;
137
+ currentHandler = void 0;
138
+ }
139
+ } else {
140
+ currentHandler.resolve(message.response);
141
+ currentHandler = void 0;
142
+ }
143
+ if (this.isTerminalResponse(message) && this.responseHandlerQueue.length === 0) await this.stream.requests.complete();
144
+ }
145
+ } catch (e) {
146
+ return this.assignErrorFactoryIfNotSet(() => {
147
+ rethrowMeaningfulError(e, true);
148
+ }, currentHandler?.reject);
149
+ } finally {
150
+ await this.close();
151
+ }
152
+ return null;
153
+ }
154
+ /** Executed after termination of incoming message processor */
155
+ async close() {
156
+ if (this.closed) return;
157
+ this.closed = true;
158
+ while (true) {
159
+ const handler = this.responseHandlerQueue.shift();
160
+ if (!handler) break;
161
+ if (this.errorFactory) handler.reject(new RethrowError(this.errorFactory));
162
+ else handler.reject(/* @__PURE__ */ new Error("no reply"));
163
+ }
164
+ await this.stream.requests.complete();
165
+ }
166
+ /** Forcefully close the transaction, terminate all connections and reject all pending requests */
167
+ abort(cause) {
168
+ this.assignErrorFactoryIfNotSet(() => {
169
+ throw new Error(`transaction aborted`, { cause });
170
+ });
171
+ this.abortController.abort(cause);
172
+ }
173
+ /** Await incoming message loop termination and throw any leftover errors if it was unsuccessful */
174
+ async await() {
175
+ const processingResult = await this.incomingProcessorResult;
176
+ if (processingResult !== null) processingResult();
177
+ }
178
+ /** Generate proper client message and send it to the server, and returns a promise of future response. */
179
+ async send(r, expectMultiResponse) {
180
+ if (this.errorFactory) return Promise.reject(new RethrowError(this.errorFactory));
181
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Transaction already closed"));
182
+ const result = StatefulPromise.fromDeferredReject(new Promise((resolve, reject) => {
183
+ this.responseHandlerQueue.push(createResponseHandler(r.oneofKind, expectMultiResponse, resolve, reject));
184
+ }));
185
+ await this.stream.requests.send({
186
+ requestId: this.requestIdxCounter++,
187
+ request: r
188
+ });
189
+ try {
190
+ return await result;
191
+ } catch (e) {
192
+ if (e instanceof RethrowError) e.rethrowLambda();
193
+ throw new Error("Error while waiting for response", { cause: e });
194
+ }
195
+ }
196
+ _completed = false;
197
+ /** Safe to call multiple times */
198
+ async complete() {
199
+ if (this._completed) return;
200
+ this._completed = true;
201
+ await this.stream.requests.complete();
202
+ }
203
+ isTerminalResponse(message) {
204
+ const kind = message.response.oneofKind;
205
+ return kind === "txCommit" || kind === "txDiscard";
206
+ }
207
+ };
242
208
 
243
- export { LLPlTransaction, RethrowError };
244
- //# sourceMappingURL=ll_transaction.js.map
209
+ //#endregion
210
+ export { LLPlTransaction };
211
+ //# sourceMappingURL=ll_transaction.js.map