@milaboratories/pl-client 2.11.8 → 2.11.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 (242) hide show
  1. package/dist/core/auth.cjs +24 -0
  2. package/dist/core/auth.cjs.map +1 -0
  3. package/dist/core/auth.d.ts +0 -1
  4. package/dist/core/auth.js +21 -0
  5. package/dist/core/auth.js.map +1 -0
  6. package/dist/core/cache.d.ts +0 -1
  7. package/dist/core/client.cjs +288 -0
  8. package/dist/core/client.cjs.map +1 -0
  9. package/dist/core/client.d.ts +0 -1
  10. package/dist/core/client.js +267 -0
  11. package/dist/core/client.js.map +1 -0
  12. package/dist/core/config.cjs +111 -0
  13. package/dist/core/config.cjs.map +1 -0
  14. package/dist/core/config.d.ts +0 -1
  15. package/dist/core/config.js +95 -0
  16. package/dist/core/config.js.map +1 -0
  17. package/dist/core/default_client.cjs +143 -0
  18. package/dist/core/default_client.cjs.map +1 -0
  19. package/dist/core/default_client.d.ts +0 -1
  20. package/dist/core/default_client.js +120 -0
  21. package/dist/core/default_client.js.map +1 -0
  22. package/dist/core/driver.cjs +14 -0
  23. package/dist/core/driver.cjs.map +1 -0
  24. package/dist/core/driver.d.ts +0 -1
  25. package/dist/core/driver.js +12 -0
  26. package/dist/core/driver.js.map +1 -0
  27. package/dist/core/error_resource.cjs +9 -0
  28. package/dist/core/error_resource.cjs.map +1 -0
  29. package/dist/core/error_resource.d.ts +0 -1
  30. package/dist/core/error_resource.js +7 -0
  31. package/dist/core/error_resource.js.map +1 -0
  32. package/dist/core/errors.cjs +106 -0
  33. package/dist/core/errors.cjs.map +1 -0
  34. package/dist/core/errors.d.ts +0 -1
  35. package/dist/core/errors.js +93 -0
  36. package/dist/core/errors.js.map +1 -0
  37. package/dist/core/final.cjs +98 -0
  38. package/dist/core/final.cjs.map +1 -0
  39. package/dist/core/final.d.ts +0 -1
  40. package/dist/core/final.js +96 -0
  41. package/dist/core/final.js.map +1 -0
  42. package/dist/core/grpc.d.ts +0 -1
  43. package/dist/core/http.d.ts +1 -1
  44. package/dist/core/ll_client.cjs +266 -0
  45. package/dist/core/ll_client.cjs.map +1 -0
  46. package/dist/core/ll_client.d.ts +0 -1
  47. package/dist/core/ll_client.js +264 -0
  48. package/dist/core/ll_client.js.map +1 -0
  49. package/dist/core/ll_transaction.cjs +236 -0
  50. package/dist/core/ll_transaction.cjs.map +1 -0
  51. package/dist/core/ll_transaction.d.ts +0 -1
  52. package/dist/core/ll_transaction.js +233 -0
  53. package/dist/core/ll_transaction.js.map +1 -0
  54. package/dist/core/stat.cjs +74 -0
  55. package/dist/core/stat.cjs.map +1 -0
  56. package/dist/core/stat.d.ts +0 -1
  57. package/dist/core/stat.js +70 -0
  58. package/dist/core/stat.js.map +1 -0
  59. package/dist/core/transaction.cjs +626 -0
  60. package/dist/core/transaction.cjs.map +1 -0
  61. package/dist/core/transaction.d.ts +0 -1
  62. package/dist/core/transaction.js +613 -0
  63. package/dist/core/transaction.js.map +1 -0
  64. package/dist/core/type_conversion.cjs +106 -0
  65. package/dist/core/type_conversion.cjs.map +1 -0
  66. package/dist/core/type_conversion.d.ts +0 -1
  67. package/dist/core/type_conversion.js +102 -0
  68. package/dist/core/type_conversion.js.map +1 -0
  69. package/dist/core/types.cjs +159 -0
  70. package/dist/core/types.cjs.map +1 -0
  71. package/dist/core/types.d.ts +0 -1
  72. package/dist/core/types.js +134 -0
  73. package/dist/core/types.js.map +1 -0
  74. package/dist/core/unauth_client.cjs +43 -0
  75. package/dist/core/unauth_client.cjs.map +1 -0
  76. package/dist/core/unauth_client.d.ts +0 -1
  77. package/dist/core/unauth_client.js +41 -0
  78. package/dist/core/unauth_client.js.map +1 -0
  79. package/dist/helpers/pl.cjs +124 -0
  80. package/dist/helpers/pl.cjs.map +1 -0
  81. package/dist/helpers/pl.d.ts +0 -1
  82. package/dist/helpers/pl.js +94 -0
  83. package/dist/helpers/pl.js.map +1 -0
  84. package/dist/helpers/poll.cjs +148 -0
  85. package/dist/helpers/poll.cjs.map +1 -0
  86. package/dist/helpers/poll.d.ts +0 -1
  87. package/dist/helpers/poll.js +123 -0
  88. package/dist/helpers/poll.js.map +1 -0
  89. package/dist/helpers/rich_resource_types.d.ts +1 -1
  90. package/dist/helpers/smart_accessors.d.ts +1 -1
  91. package/dist/helpers/state_helpers.d.ts +0 -1
  92. package/dist/helpers/tx_helpers.cjs +25 -0
  93. package/dist/helpers/tx_helpers.cjs.map +1 -0
  94. package/dist/helpers/tx_helpers.d.ts +0 -1
  95. package/dist/helpers/tx_helpers.js +23 -0
  96. package/dist/helpers/tx_helpers.js.map +1 -0
  97. package/dist/index.cjs +99 -0
  98. package/dist/index.cjs.map +1 -0
  99. package/dist/index.d.ts +0 -1
  100. package/dist/index.js +16 -1
  101. package/dist/index.js.map +1 -1
  102. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.cjs +71 -0
  103. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.cjs.map +1 -0
  104. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.d.ts +0 -1
  105. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.js +69 -0
  106. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.js.map +1 -0
  107. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/downloadapi/protocol.client.d.ts +3 -5
  108. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/downloadapi/protocol.d.ts +0 -1
  109. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/lsapi/protocol.client.d.ts +3 -5
  110. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/lsapi/protocol.d.ts +0 -1
  111. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/progressapi/protocol.client.d.ts +3 -5
  112. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/progressapi/protocol.d.ts +0 -1
  113. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/streamingapi/protocol.client.d.ts +3 -5
  114. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/streamingapi/protocol.d.ts +0 -1
  115. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +12238 -0
  116. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -0
  117. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs +223 -0
  118. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs.map +1 -0
  119. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts +3 -5
  120. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.js +221 -0
  121. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.js.map +1 -0
  122. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +0 -1
  123. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.js +12086 -0
  124. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -0
  125. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs +1127 -0
  126. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.cjs.map +1 -0
  127. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts +0 -1
  128. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.js +1113 -0
  129. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.js.map +1 -0
  130. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs +152 -0
  131. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.cjs.map +1 -0
  132. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts +0 -1
  133. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.js +149 -0
  134. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.js.map +1 -0
  135. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts +0 -1
  136. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs +500 -0
  137. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.cjs.map +1 -0
  138. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts +0 -1
  139. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js +496 -0
  140. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.js.map +1 -0
  141. package/dist/proto/google/api/http.d.ts +0 -1
  142. package/dist/proto/google/protobuf/any.cjs +151 -0
  143. package/dist/proto/google/protobuf/any.cjs.map +1 -0
  144. package/dist/proto/google/protobuf/any.d.ts +0 -1
  145. package/dist/proto/google/protobuf/any.js +149 -0
  146. package/dist/proto/google/protobuf/any.js.map +1 -0
  147. package/dist/proto/google/protobuf/descriptor.d.ts +0 -1
  148. package/dist/proto/google/protobuf/duration.cjs +105 -0
  149. package/dist/proto/google/protobuf/duration.cjs.map +1 -0
  150. package/dist/proto/google/protobuf/duration.d.ts +0 -1
  151. package/dist/proto/google/protobuf/duration.js +103 -0
  152. package/dist/proto/google/protobuf/duration.js.map +1 -0
  153. package/dist/proto/google/protobuf/empty.d.ts +0 -1
  154. package/dist/proto/google/protobuf/struct.d.ts +0 -1
  155. package/dist/proto/google/protobuf/timestamp.cjs +133 -0
  156. package/dist/proto/google/protobuf/timestamp.cjs.map +1 -0
  157. package/dist/proto/google/protobuf/timestamp.d.ts +0 -1
  158. package/dist/proto/google/protobuf/timestamp.js +131 -0
  159. package/dist/proto/google/protobuf/timestamp.js.map +1 -0
  160. package/dist/proto/google/protobuf/wrappers.d.ts +0 -1
  161. package/dist/test/test_config.cjs +149 -0
  162. package/dist/test/test_config.cjs.map +1 -0
  163. package/dist/test/test_config.d.ts +0 -1
  164. package/dist/test/test_config.js +123 -0
  165. package/dist/test/test_config.js.map +1 -0
  166. package/dist/util/branding.d.ts +0 -1
  167. package/dist/util/pl.cjs +8 -0
  168. package/dist/util/pl.cjs.map +1 -0
  169. package/dist/util/pl.d.ts +0 -1
  170. package/dist/util/pl.js +6 -0
  171. package/dist/util/pl.js.map +1 -0
  172. package/dist/util/util.cjs +17 -0
  173. package/dist/util/util.cjs.map +1 -0
  174. package/dist/util/util.d.ts +0 -1
  175. package/dist/util/util.js +15 -0
  176. package/dist/util/util.js.map +1 -0
  177. package/package.json +14 -11
  178. package/src/core/client.test.ts +1 -0
  179. package/src/core/config.test.ts +1 -0
  180. package/src/core/error.test.ts +1 -0
  181. package/src/core/ll_client.test.ts +1 -0
  182. package/src/core/ll_transaction.test.ts +1 -0
  183. package/src/core/transaction.test.ts +1 -0
  184. package/src/core/types.test.ts +1 -0
  185. package/src/core/unauth_client.test.ts +1 -0
  186. package/src/helpers/rich_resource_types.test.ts +2 -0
  187. package/src/test/test_config.test.ts +1 -0
  188. package/src/util/util.test.ts +1 -0
  189. package/dist/core/auth.d.ts.map +0 -1
  190. package/dist/core/cache.d.ts.map +0 -1
  191. package/dist/core/client.d.ts.map +0 -1
  192. package/dist/core/config.d.ts.map +0 -1
  193. package/dist/core/default_client.d.ts.map +0 -1
  194. package/dist/core/driver.d.ts.map +0 -1
  195. package/dist/core/error_resource.d.ts.map +0 -1
  196. package/dist/core/errors.d.ts.map +0 -1
  197. package/dist/core/final.d.ts.map +0 -1
  198. package/dist/core/grpc.d.ts.map +0 -1
  199. package/dist/core/http.d.ts.map +0 -1
  200. package/dist/core/ll_client.d.ts.map +0 -1
  201. package/dist/core/ll_transaction.d.ts.map +0 -1
  202. package/dist/core/stat.d.ts.map +0 -1
  203. package/dist/core/transaction.d.ts.map +0 -1
  204. package/dist/core/type_conversion.d.ts.map +0 -1
  205. package/dist/core/types.d.ts.map +0 -1
  206. package/dist/core/unauth_client.d.ts.map +0 -1
  207. package/dist/helpers/pl.d.ts.map +0 -1
  208. package/dist/helpers/poll.d.ts.map +0 -1
  209. package/dist/helpers/rich_resource_types.d.ts.map +0 -1
  210. package/dist/helpers/smart_accessors.d.ts.map +0 -1
  211. package/dist/helpers/state_helpers.d.ts.map +0 -1
  212. package/dist/helpers/tx_helpers.d.ts.map +0 -1
  213. package/dist/index.d.ts.map +0 -1
  214. package/dist/index.mjs +0 -14537
  215. package/dist/index.mjs.map +0 -1
  216. package/dist/proto/github.com/googleapis/googleapis/google/rpc/status.d.ts.map +0 -1
  217. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/downloadapi/protocol.client.d.ts.map +0 -1
  218. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/downloadapi/protocol.d.ts.map +0 -1
  219. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/lsapi/protocol.client.d.ts.map +0 -1
  220. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/lsapi/protocol.d.ts.map +0 -1
  221. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/progressapi/protocol.client.d.ts.map +0 -1
  222. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/progressapi/protocol.d.ts.map +0 -1
  223. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/streamingapi/protocol.client.d.ts.map +0 -1
  224. package/dist/proto/github.com/milaboratory/pl/controllers/shared/grpc/streamingapi/protocol.d.ts.map +0 -1
  225. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts.map +0 -1
  226. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +0 -1
  227. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts.map +0 -1
  228. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts.map +0 -1
  229. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/import.d.ts.map +0 -1
  230. package/dist/proto/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts.map +0 -1
  231. package/dist/proto/google/api/http.d.ts.map +0 -1
  232. package/dist/proto/google/protobuf/any.d.ts.map +0 -1
  233. package/dist/proto/google/protobuf/descriptor.d.ts.map +0 -1
  234. package/dist/proto/google/protobuf/duration.d.ts.map +0 -1
  235. package/dist/proto/google/protobuf/empty.d.ts.map +0 -1
  236. package/dist/proto/google/protobuf/struct.d.ts.map +0 -1
  237. package/dist/proto/google/protobuf/timestamp.d.ts.map +0 -1
  238. package/dist/proto/google/protobuf/wrappers.d.ts.map +0 -1
  239. package/dist/test/test_config.d.ts.map +0 -1
  240. package/dist/util/branding.d.ts.map +0 -1
  241. package/dist/util/pl.d.ts.map +0 -1
  242. package/dist/util/util.d.ts.map +0 -1
@@ -0,0 +1,613 @@
1
+ import { isLocalResourceId, isNullResourceId, ensureResourceIdNotNull, extractBasicResourceData, createLocalResourceId, MaxTxId } from './types.js';
2
+ import { TxAPI_Open_Request_WritableTx } from '../proto/github.com/milaboratory/pl/plapi/plapiproto/api.js';
3
+ import { toBytes } from '../util/util.js';
4
+ import { protoToResource, fieldTypeToProto, protoToField } from './type_conversion.js';
5
+ import { notEmpty, canonicalJsonBytes, canonicalJsonGzBytes, deepFreeze } from '@milaboratories/ts-helpers';
6
+ import { isNotFoundError } from './errors.js';
7
+ import { initialTxStatWithoutTime } from './stat.js';
8
+ import { ErrorResourceType } from './error_resource.js';
9
+ import { JsonObject, JsonGzObject } from '../helpers/pl.js';
10
+
11
+ function isField(ref) {
12
+ return ref.hasOwnProperty('resourceId') && ref.hasOwnProperty('fieldName');
13
+ }
14
+ function isResource(ref) {
15
+ return (typeof ref === 'bigint' || (ref.hasOwnProperty('globalId') && ref.hasOwnProperty('localId')));
16
+ }
17
+ function isResourceId(ref) {
18
+ return typeof ref === 'bigint' && !isLocalResourceId(ref) && !isNullResourceId(ref);
19
+ }
20
+ function isFieldRef(ref) {
21
+ return isResourceRef(ref.resourceId);
22
+ }
23
+ function isResourceRef(ref) {
24
+ return ref.hasOwnProperty('globalId') && ref.hasOwnProperty('localId');
25
+ }
26
+ function toFieldId(ref) {
27
+ if (isFieldRef(ref))
28
+ return { resourceId: ref.resourceId.localId, fieldName: ref.fieldName };
29
+ else
30
+ return ref;
31
+ }
32
+ async function toGlobalFieldId(ref) {
33
+ if (isFieldRef(ref))
34
+ return { resourceId: await ref.resourceId.globalId, fieldName: ref.fieldName };
35
+ else
36
+ return ref;
37
+ }
38
+ function toResourceId(ref) {
39
+ if (isResourceRef(ref))
40
+ return ref.localId;
41
+ else
42
+ return ref;
43
+ }
44
+ async function toGlobalResourceId(ref) {
45
+ if (isResourceRef(ref))
46
+ return await ref.globalId;
47
+ else
48
+ return ref;
49
+ }
50
+ function field(resourceId, fieldName) {
51
+ return { resourceId, fieldName };
52
+ }
53
+ /** If transaction commit failed due to write conflicts */
54
+ class TxCommitConflict extends Error {
55
+ name = 'TxCommitConflict';
56
+ }
57
+ async function notFoundToUndefined(cb) {
58
+ try {
59
+ return await cb();
60
+ }
61
+ catch (e) {
62
+ if (isNotFoundError(e))
63
+ return undefined;
64
+ throw e;
65
+ }
66
+ }
67
+ /**
68
+ * Each platform transaction has 3 stages:
69
+ * - initialization (txOpen message -> txInfo response)
70
+ * - communication (create resources, fields, references and so on)
71
+ * - finalization (txCommit or txDiscard message)
72
+ *
73
+ * This class encapsulates finalization stage and provides ready-to-communication transaction object.
74
+ * */
75
+ class PlTransaction {
76
+ ll;
77
+ name;
78
+ writable;
79
+ _clientRoot;
80
+ finalPredicate;
81
+ sharedResourceDataCache;
82
+ enableFormattedErrors;
83
+ globalTxId;
84
+ localTxId = PlTransaction.nextLocalTxId();
85
+ /** Used in caching */
86
+ txOpenTimestamp = Date.now();
87
+ localResourceIdCounter = 0;
88
+ /** Store logical tx open / closed state to prevent invalid sequence of requests.
89
+ * True means output stream was completed.
90
+ * Contract: there must be no async operations between setting this field to true and sending complete signal to stream. */
91
+ _completed = false;
92
+ /** Void operation futures are placed into this pool, and corresponding method return immediately.
93
+ * This is done to save number of round-trips. Next operation producing result will also await those
94
+ * pending ops, to throw any pending errors. */
95
+ pendingVoidOps = [];
96
+ globalTxIdWasAwaited = false;
97
+ _startTime = Date.now();
98
+ _stat = initialTxStatWithoutTime();
99
+ get stat() {
100
+ return {
101
+ ...this._stat,
102
+ timeMs: Date.now() - this._startTime,
103
+ };
104
+ }
105
+ constructor(ll, name, writable, _clientRoot, finalPredicate, sharedResourceDataCache, enableFormattedErrors = false) {
106
+ this.ll = ll;
107
+ this.name = name;
108
+ this.writable = writable;
109
+ this._clientRoot = _clientRoot;
110
+ this.finalPredicate = finalPredicate;
111
+ this.sharedResourceDataCache = sharedResourceDataCache;
112
+ this.enableFormattedErrors = enableFormattedErrors;
113
+ // initiating transaction
114
+ this.globalTxId = this.sendSingleAndParse({
115
+ oneofKind: 'txOpen',
116
+ txOpen: {
117
+ name,
118
+ enableFormattedErrors,
119
+ writable: writable
120
+ ? TxAPI_Open_Request_WritableTx.WRITABLE
121
+ : TxAPI_Open_Request_WritableTx.NOT_WRITABLE,
122
+ },
123
+ }, (r) => notEmpty(r.txOpen.tx?.id));
124
+ // To avoid floating promise
125
+ this.globalTxId.catch((err) => {
126
+ if (!this.globalTxIdWasAwaited) {
127
+ console.warn(err);
128
+ }
129
+ });
130
+ // Adding stats
131
+ this._stat.txCount++;
132
+ }
133
+ async drainAndAwaitPendingOps() {
134
+ if (this.pendingVoidOps.length === 0)
135
+ return;
136
+ // drain pending operations into temp array
137
+ const pending = this.pendingVoidOps;
138
+ this.pendingVoidOps = [];
139
+ // awaiting these pending operations first, to catch any errors
140
+ await Promise.all(pending);
141
+ }
142
+ async sendSingleAndParse(r, parser) {
143
+ // pushing operation packet to server
144
+ const rawResponsePromise = this.ll.send(r, false);
145
+ await this.drainAndAwaitPendingOps();
146
+ // awaiting our result, and parsing the response
147
+ return parser(await rawResponsePromise);
148
+ }
149
+ async sendMultiAndParse(r, parser) {
150
+ // pushing operation packet to server
151
+ const rawResponsePromise = this.ll.send(r, true);
152
+ await this.drainAndAwaitPendingOps();
153
+ // awaiting our result, and parsing the response
154
+ return parser(await rawResponsePromise);
155
+ }
156
+ async sendVoidSync(r) {
157
+ await this.ll.send(r, false);
158
+ }
159
+ /** Requests sent with this method should never produce recoverable errors */
160
+ sendVoidAsync(r) {
161
+ this.pendingVoidOps.push(this.sendVoidSync(r));
162
+ }
163
+ checkTxOpen() {
164
+ if (this._completed)
165
+ throw new Error('Transaction already closed');
166
+ }
167
+ get completed() {
168
+ return this._completed;
169
+ }
170
+ /** Commit & closes transaction. {@link TxCommitConflict} is thrown on
171
+ * commit conflicts. */
172
+ async commit() {
173
+ this.checkTxOpen();
174
+ // tx will accept no requests after this one
175
+ this._completed = true;
176
+ if (!this.writable) {
177
+ // no need to explicitly commit or reject read-only tx
178
+ const completeResult = this.ll.complete();
179
+ await this.drainAndAwaitPendingOps();
180
+ await completeResult;
181
+ await this.ll.await();
182
+ }
183
+ else {
184
+ // @TODO, also floating promises
185
+ const commitResponse = this.sendSingleAndParse({ oneofKind: 'txCommit', txCommit: {} }, (r) => r.txCommit.success);
186
+ // send closing frame right after commit to save some time on round-trips
187
+ const completeResult = this.ll.complete();
188
+ // now when we pushed all packets into the stream, we should wait for any
189
+ // pending void operations from before, to catch any errors
190
+ await this.drainAndAwaitPendingOps();
191
+ if (!(await commitResponse))
192
+ throw new TxCommitConflict();
193
+ await completeResult;
194
+ // await event-loop completion
195
+ await this.ll.await();
196
+ }
197
+ }
198
+ async discard() {
199
+ this.checkTxOpen();
200
+ // tx will accept no requests after this one
201
+ this._completed = true;
202
+ const discardResponse = this.sendVoidSync({ oneofKind: 'txDiscard', txDiscard: {} });
203
+ // send closing frame right after commit to save some time on round-trips
204
+ const completeResult = this.ll.complete();
205
+ // now when we pushed all packets into the stream, we should wait for any
206
+ // pending void operations from before, to catch any errors
207
+ await this.drainAndAwaitPendingOps();
208
+ await discardResponse;
209
+ await completeResult;
210
+ await this.ll.await();
211
+ }
212
+ //
213
+ // Main tx methods
214
+ //
215
+ get clientRoot() {
216
+ return ensureResourceIdNotNull(this._clientRoot);
217
+ }
218
+ //
219
+ // Resources
220
+ //
221
+ createSingleton(name, type, errorIfExists = false) {
222
+ const localId = this.nextLocalResourceId(false);
223
+ const globalId = this.sendSingleAndParse({
224
+ oneofKind: 'resourceCreateSingleton',
225
+ resourceCreateSingleton: {
226
+ type,
227
+ id: localId,
228
+ data: Buffer.from(name),
229
+ errorIfExists,
230
+ },
231
+ }, (r) => r.resourceCreateSingleton.resourceId);
232
+ return { globalId, localId };
233
+ }
234
+ async getSingleton(name, loadFields = true) {
235
+ return await this.sendSingleAndParse({
236
+ oneofKind: 'resourceGetSingleton',
237
+ resourceGetSingleton: {
238
+ data: Buffer.from(name),
239
+ loadFields,
240
+ },
241
+ }, (r) => protoToResource(notEmpty(r.resourceGetSingleton.resource)));
242
+ }
243
+ createResource(root, req, parser) {
244
+ const localId = this.nextLocalResourceId(root);
245
+ const globalId = this.sendSingleAndParse(req(localId), (r) => parser(r));
246
+ return { globalId, localId };
247
+ }
248
+ createRoot(type) {
249
+ this._stat.rootsCreated++;
250
+ return this.createResource(true, (localId) => ({ oneofKind: 'resourceCreateRoot', resourceCreateRoot: { type, id: localId } }), (r) => r.resourceCreateRoot.resourceId);
251
+ }
252
+ createStruct(type, data) {
253
+ this._stat.structsCreated++;
254
+ this._stat.structsCreatedDataBytes += data?.length ?? 0;
255
+ return this.createResource(false, (localId) => ({
256
+ oneofKind: 'resourceCreateStruct',
257
+ resourceCreateStruct: {
258
+ type,
259
+ id: localId,
260
+ data: data === undefined ? undefined : typeof data === 'string' ? Buffer.from(data) : data,
261
+ },
262
+ }), (r) => r.resourceCreateStruct.resourceId);
263
+ }
264
+ createEphemeral(type, data) {
265
+ this._stat.ephemeralsCreated++;
266
+ this._stat.ephemeralsCreatedDataBytes += data?.length ?? 0;
267
+ return this.createResource(false, (localId) => ({
268
+ oneofKind: 'resourceCreateEphemeral',
269
+ resourceCreateEphemeral: {
270
+ type,
271
+ id: localId,
272
+ data: data === undefined ? undefined : typeof data === 'string' ? Buffer.from(data) : data,
273
+ },
274
+ }), (r) => r.resourceCreateEphemeral.resourceId);
275
+ }
276
+ createValue(type, data, errorIfExists = false) {
277
+ this._stat.valuesCreated++;
278
+ this._stat.valuesCreatedDataBytes += data?.length ?? 0;
279
+ return this.createResource(false, (localId) => ({
280
+ oneofKind: 'resourceCreateValue',
281
+ resourceCreateValue: {
282
+ type,
283
+ id: localId,
284
+ data: typeof data === 'string' ? Buffer.from(data) : data,
285
+ errorIfExists,
286
+ },
287
+ }), (r) => r.resourceCreateValue.resourceId);
288
+ }
289
+ createJsonValue(data) {
290
+ const jsonData = canonicalJsonBytes(data);
291
+ return this.createValue(JsonObject, jsonData, false);
292
+ }
293
+ createJsonGzValue(data, minSizeToGzip = 16_384) {
294
+ const { data: jsonData, isGzipped } = canonicalJsonGzBytes(data, minSizeToGzip);
295
+ return this.createValue(isGzipped ? JsonGzObject : JsonObject, jsonData, false);
296
+ }
297
+ createError(message) {
298
+ return this.createValue(ErrorResourceType, JSON.stringify({ message }));
299
+ }
300
+ setResourceName(name, rId) {
301
+ this.sendVoidAsync({
302
+ oneofKind: 'resourceNameSet',
303
+ resourceNameSet: { resourceId: toResourceId(rId), name },
304
+ });
305
+ }
306
+ deleteResourceName(name) {
307
+ this.sendVoidAsync({ oneofKind: 'resourceNameDelete', resourceNameDelete: { name } });
308
+ }
309
+ async getResourceByName(name) {
310
+ return await this.sendSingleAndParse({ oneofKind: 'resourceNameGet', resourceNameGet: { name } }, (r) => ensureResourceIdNotNull(r.resourceNameGet.resourceId));
311
+ }
312
+ async checkResourceNameExists(name) {
313
+ return await this.sendSingleAndParse({ oneofKind: 'resourceNameExists', resourceNameExists: { name } }, (r) => r.resourceNameExists.exists);
314
+ }
315
+ removeResource(rId) {
316
+ this.sendVoidAsync({ oneofKind: 'resourceRemove', resourceRemove: { id: rId } });
317
+ }
318
+ async resourceExists(rId) {
319
+ return await this.sendSingleAndParse({ oneofKind: 'resourceExists', resourceExists: { resourceId: rId } }, (r) => r.resourceExists.exists);
320
+ }
321
+ async getResourceData(rId, loadFields = true, ignoreCache = false) {
322
+ if (!ignoreCache && !isResourceRef(rId) && !isLocalResourceId(rId)) {
323
+ // checking if we can return result from cache
324
+ const fromCache = this.sharedResourceDataCache.get(rId);
325
+ if (fromCache && fromCache.cacheTxOpenTimestamp < this.txOpenTimestamp) {
326
+ if (!loadFields) {
327
+ this._stat.rGetDataCacheHits++;
328
+ this._stat.rGetDataCacheBytes += fromCache.basicData.data?.length ?? 0;
329
+ return fromCache.basicData;
330
+ }
331
+ else if (fromCache.data) {
332
+ this._stat.rGetDataCacheHits++;
333
+ this._stat.rGetDataCacheBytes += fromCache.basicData.data?.length ?? 0;
334
+ this._stat.rGetDataCacheFields += fromCache.data.fields.length;
335
+ return fromCache.data;
336
+ }
337
+ }
338
+ }
339
+ const result = await this.sendSingleAndParse({
340
+ oneofKind: 'resourceGet',
341
+ resourceGet: { resourceId: toResourceId(rId), loadFields: loadFields },
342
+ }, (r) => protoToResource(notEmpty(r.resourceGet.resource)));
343
+ this._stat.rGetDataNetRequests++;
344
+ this._stat.rGetDataNetBytes += result.data?.length ?? 0;
345
+ this._stat.rGetDataNetFields += result.fields.length;
346
+ // we will cache only final resource data states
347
+ // caching result even if we were ignore the cache
348
+ if (!isResourceRef(rId) && !isLocalResourceId(rId) && this.finalPredicate(result)) {
349
+ deepFreeze(result);
350
+ const fromCache = this.sharedResourceDataCache.get(rId);
351
+ if (fromCache) {
352
+ if (loadFields && !fromCache.data) {
353
+ fromCache.data = result;
354
+ // updating timestamp becuse we updated the record
355
+ fromCache.cacheTxOpenTimestamp = this.txOpenTimestamp;
356
+ }
357
+ }
358
+ else {
359
+ const basicData = extractBasicResourceData(result);
360
+ deepFreeze(basicData);
361
+ if (loadFields)
362
+ this.sharedResourceDataCache.set(rId, {
363
+ basicData,
364
+ data: result,
365
+ cacheTxOpenTimestamp: this.txOpenTimestamp,
366
+ });
367
+ else
368
+ this.sharedResourceDataCache.set(rId, {
369
+ basicData,
370
+ data: undefined,
371
+ cacheTxOpenTimestamp: this.txOpenTimestamp,
372
+ });
373
+ }
374
+ }
375
+ return result;
376
+ }
377
+ async getResourceDataIfExists(rId, loadFields = true) {
378
+ // calling this mehtod will ignore cache, because user intention is to detect resource absence
379
+ // which cache will prevent
380
+ const result = await notFoundToUndefined(async () => await this.getResourceData(rId, loadFields, true));
381
+ // cleaning cache record if resorce was removed from the db
382
+ if (result === undefined && !isResourceRef(rId) && !isLocalResourceId(rId))
383
+ this.sharedResourceDataCache.delete(rId);
384
+ return result;
385
+ }
386
+ /**
387
+ * Inform platform that resource will not get any new input fields.
388
+ * This is required, when client creates resource without schema and wants
389
+ * controller to start calculations.
390
+ * Most controllers will not start calculations even when all inputs
391
+ * have their values, if inputs list is not locked.
392
+ */
393
+ lockInputs(rId) {
394
+ this._stat.inputsLocked++;
395
+ this.sendVoidAsync({
396
+ oneofKind: 'resourceLockInputs',
397
+ resourceLockInputs: { resourceId: toResourceId(rId) },
398
+ });
399
+ }
400
+ /**
401
+ * Inform platform that resource will not get any new output fields.
402
+ * This is required for resource to pass deduplication.
403
+ */
404
+ lockOutputs(rId) {
405
+ this._stat.outputsLocked++;
406
+ this.sendVoidAsync({
407
+ oneofKind: 'resourceLockOutputs',
408
+ resourceLockOutputs: { resourceId: toResourceId(rId) },
409
+ });
410
+ }
411
+ lock(rID) {
412
+ this.lockInputs(rID);
413
+ this.lockOutputs(rID);
414
+ }
415
+ setResourceError(rId, ref) {
416
+ this.sendVoidAsync({
417
+ oneofKind: 'resourceSetError',
418
+ resourceSetError: { resourceId: toResourceId(rId), errorResourceId: toResourceId(ref) },
419
+ });
420
+ }
421
+ //
422
+ // Fields
423
+ //
424
+ createField(fId, fieldType, value) {
425
+ this._stat.fieldsCreated++;
426
+ this.sendVoidAsync({
427
+ oneofKind: 'fieldCreate',
428
+ fieldCreate: { type: fieldTypeToProto(fieldType), id: toFieldId(fId) },
429
+ });
430
+ if (value !== undefined)
431
+ this.setField(fId, value);
432
+ }
433
+ async fieldExists(fId) {
434
+ return await this.sendSingleAndParse({
435
+ oneofKind: 'fieldExists',
436
+ fieldExists: { field: toFieldId(fId) },
437
+ }, (r) => r.fieldExists.exists);
438
+ }
439
+ setField(fId, ref) {
440
+ this._stat.fieldsSet++;
441
+ if (isResource(ref))
442
+ this.sendVoidAsync({
443
+ oneofKind: 'fieldSet',
444
+ fieldSet: {
445
+ field: toFieldId(fId),
446
+ value: {
447
+ resourceId: toResourceId(ref),
448
+ fieldName: '', // default value, read as undefined
449
+ },
450
+ },
451
+ });
452
+ else
453
+ this.sendVoidAsync({
454
+ oneofKind: 'fieldSet',
455
+ fieldSet: {
456
+ field: toFieldId(fId),
457
+ value: toFieldId(ref),
458
+ },
459
+ });
460
+ }
461
+ setFieldError(fId, ref) {
462
+ this._stat.fieldsSet++;
463
+ this.sendVoidAsync({
464
+ oneofKind: 'fieldSetError',
465
+ fieldSetError: { field: toFieldId(fId), errResourceId: toResourceId(ref) },
466
+ });
467
+ }
468
+ async getField(fId) {
469
+ this._stat.fieldsGet++;
470
+ return await this.sendSingleAndParse({ oneofKind: 'fieldGet', fieldGet: { field: toFieldId(fId) } }, (r) => protoToField(notEmpty(r.fieldGet.field)));
471
+ }
472
+ async getFieldIfExists(fId) {
473
+ return notFoundToUndefined(async () => await this.getField(fId));
474
+ }
475
+ resetField(fId) {
476
+ this.sendVoidAsync({ oneofKind: 'fieldReset', fieldReset: { field: toFieldId(fId) } });
477
+ }
478
+ removeField(fId) {
479
+ this.sendVoidAsync({ oneofKind: 'fieldRemove', fieldRemove: { field: toFieldId(fId) } });
480
+ }
481
+ //
482
+ // KV
483
+ //
484
+ async listKeyValues(rId) {
485
+ const result = await this.sendMultiAndParse({
486
+ oneofKind: 'resourceKeyValueList',
487
+ resourceKeyValueList: { resourceId: toResourceId(rId), startFrom: '', limit: 0 },
488
+ }, (r) => r.map((e) => e.resourceKeyValueList.record));
489
+ this._stat.kvListRequests++;
490
+ this._stat.kvListEntries += result.length;
491
+ for (const kv of result)
492
+ this._stat.kvListBytes += kv.key.length + kv.value.length;
493
+ return result;
494
+ }
495
+ async listKeyValuesString(rId) {
496
+ return (await this.listKeyValues(rId)).map(({ key, value }) => ({
497
+ key,
498
+ value: Buffer.from(value).toString(),
499
+ }));
500
+ }
501
+ async listKeyValuesIfResourceExists(rId) {
502
+ return notFoundToUndefined(async () => await this.listKeyValues(rId));
503
+ }
504
+ async listKeyValuesStringIfResourceExists(rId) {
505
+ return notFoundToUndefined(async () => await this.listKeyValuesString(rId));
506
+ }
507
+ setKValue(rId, key, value) {
508
+ this._stat.kvSetRequests++;
509
+ this._stat.kvSetBytes++;
510
+ this.sendVoidAsync({
511
+ oneofKind: 'resourceKeyValueSet',
512
+ resourceKeyValueSet: {
513
+ resourceId: toResourceId(rId),
514
+ key,
515
+ value: toBytes(value),
516
+ },
517
+ });
518
+ }
519
+ deleteKValue(rId, key) {
520
+ this.sendVoidAsync({
521
+ oneofKind: 'resourceKeyValueDelete',
522
+ resourceKeyValueDelete: {
523
+ resourceId: toResourceId(rId),
524
+ key,
525
+ },
526
+ });
527
+ }
528
+ async getKValue(rId, key) {
529
+ const result = await this.sendSingleAndParse({
530
+ oneofKind: 'resourceKeyValueGet',
531
+ resourceKeyValueGet: { resourceId: toResourceId(rId), key },
532
+ }, (r) => r.resourceKeyValueGet.value);
533
+ this._stat.kvGetRequests++;
534
+ this._stat.kvGetBytes += result.length;
535
+ return result;
536
+ }
537
+ async getKValueString(rId, key) {
538
+ return Buffer.from(await this.getKValue(rId, key)).toString();
539
+ }
540
+ async getKValueJson(rId, key) {
541
+ return JSON.parse(await this.getKValueString(rId, key));
542
+ }
543
+ async getKValueIfExists(rId, key) {
544
+ const result = await this.sendSingleAndParse({
545
+ oneofKind: 'resourceKeyValueGetIfExists',
546
+ resourceKeyValueGetIfExists: { resourceId: toResourceId(rId), key },
547
+ }, (r) => r.resourceKeyValueGetIfExists.exists ? r.resourceKeyValueGetIfExists.value : undefined);
548
+ this._stat.kvGetRequests++;
549
+ this._stat.kvGetBytes += result?.length ?? 0;
550
+ return result;
551
+ }
552
+ async getKValueStringIfExists(rId, key) {
553
+ const data = await this.getKValueIfExists(rId, key);
554
+ return data === undefined ? undefined : Buffer.from(data).toString();
555
+ }
556
+ async getKValueJsonIfExists(rId, key) {
557
+ const str = await this.getKValueString(rId, key);
558
+ if (str === undefined)
559
+ return undefined;
560
+ return JSON.parse(str);
561
+ }
562
+ //
563
+ // Cache
564
+ //
565
+ // TODO
566
+ //
567
+ // High level ops
568
+ //
569
+ /** Resolves existing or create first level resource from */
570
+ getFutureFieldValue(rId, fieldName, fieldType) {
571
+ const data = Buffer.from(JSON.stringify({ fieldName, fieldType }));
572
+ const getFieldResource = this.createEphemeral({ name: 'json/getField', version: '1' }, data);
573
+ this.setField({ resourceId: getFieldResource, fieldName: 'resource' }, rId);
574
+ return { resourceId: getFieldResource, fieldName: 'result' };
575
+ }
576
+ //
577
+ // Technical
578
+ //
579
+ async getGlobalTxId() {
580
+ this.globalTxIdWasAwaited = true;
581
+ return await this.globalTxId;
582
+ }
583
+ /** Closes output event stream */
584
+ async complete() {
585
+ if (this._completed)
586
+ return;
587
+ this._completed = true;
588
+ const completeResult = this.ll.complete();
589
+ await this.drainAndAwaitPendingOps();
590
+ await completeResult;
591
+ }
592
+ /** Await incoming message loop termination and throw
593
+ * any leftover errors if it was unsuccessful */
594
+ async await() {
595
+ await this.ll.await();
596
+ }
597
+ //
598
+ // Helpers
599
+ //
600
+ nextLocalResourceId(root) {
601
+ return createLocalResourceId(root, ++this.localResourceIdCounter, this.localTxId);
602
+ }
603
+ static localTxIdCounter = 0;
604
+ static nextLocalTxId() {
605
+ PlTransaction.localTxIdCounter++;
606
+ if (PlTransaction.localTxIdCounter === MaxTxId)
607
+ PlTransaction.localTxIdCounter = 1;
608
+ return PlTransaction.localTxIdCounter;
609
+ }
610
+ }
611
+
612
+ export { PlTransaction, TxCommitConflict, field, isField, isFieldRef, isResource, isResourceId, isResourceRef, toFieldId, toGlobalFieldId, toGlobalResourceId, toResourceId };
613
+ //# sourceMappingURL=transaction.js.map