@resonatehq/sdk 0.6.3 → 0.7.1

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 (202) hide show
  1. package/README.md +24 -45
  2. package/dist/dev/network.d.ts +16 -0
  3. package/dist/dev/network.d.ts.map +1 -0
  4. package/dist/dev/network.js +89 -0
  5. package/dist/dev/network.js.map +1 -0
  6. package/dist/dev/server.d.ts +87 -0
  7. package/dist/dev/server.d.ts.map +1 -0
  8. package/dist/dev/server.js +891 -0
  9. package/dist/dev/server.js.map +1 -0
  10. package/dist/sim/example-1.d.ts +2 -0
  11. package/dist/sim/example-1.d.ts.map +1 -0
  12. package/dist/sim/example-1.js +94 -0
  13. package/dist/sim/example-1.js.map +1 -0
  14. package/dist/sim/example-2.d.ts +2 -0
  15. package/dist/sim/example-2.d.ts.map +1 -0
  16. package/dist/sim/example-2.js +95 -0
  17. package/dist/sim/example-2.js.map +1 -0
  18. package/dist/sim/example-3.d.ts +2 -0
  19. package/dist/sim/example-3.d.ts.map +1 -0
  20. package/dist/sim/example-3.js +95 -0
  21. package/dist/sim/example-3.js.map +1 -0
  22. package/dist/sim/main.d.ts +14 -0
  23. package/dist/sim/main.d.ts.map +1 -0
  24. package/dist/sim/main.js +206 -0
  25. package/dist/sim/main.js.map +1 -0
  26. package/dist/sim/src/server.d.ts +15 -0
  27. package/dist/sim/src/server.d.ts.map +1 -0
  28. package/dist/sim/src/server.js +85 -0
  29. package/dist/sim/src/server.js.map +1 -0
  30. package/dist/sim/src/simulator.d.ts +65 -0
  31. package/dist/sim/src/simulator.d.ts.map +1 -0
  32. package/dist/sim/src/simulator.js +235 -0
  33. package/dist/sim/src/simulator.js.map +1 -0
  34. package/dist/sim/src/worker.d.ts +22 -0
  35. package/dist/sim/src/worker.d.ts.map +1 -0
  36. package/dist/sim/src/worker.js +175 -0
  37. package/dist/sim/src/worker.js.map +1 -0
  38. package/dist/src/clock.d.ts +11 -0
  39. package/dist/src/clock.d.ts.map +1 -0
  40. package/dist/src/clock.js +17 -0
  41. package/dist/src/clock.js.map +1 -0
  42. package/dist/src/computation.d.ts +40 -0
  43. package/dist/src/computation.d.ts.map +1 -0
  44. package/dist/src/computation.js +225 -0
  45. package/dist/src/computation.js.map +1 -0
  46. package/dist/src/context.d.ts +120 -0
  47. package/dist/src/context.d.ts.map +1 -0
  48. package/dist/src/context.js +288 -0
  49. package/dist/src/context.js.map +1 -0
  50. package/dist/src/coroutine.d.ts +34 -0
  51. package/dist/src/coroutine.d.ts.map +1 -0
  52. package/dist/src/coroutine.js +246 -0
  53. package/dist/src/coroutine.js.map +1 -0
  54. package/dist/src/decorator.d.ts +14 -0
  55. package/dist/src/decorator.d.ts.map +1 -0
  56. package/dist/src/decorator.js +208 -0
  57. package/dist/src/decorator.js.map +1 -0
  58. package/dist/src/handler.d.ts +40 -0
  59. package/dist/src/handler.d.ts.map +1 -0
  60. package/dist/src/handler.js +198 -0
  61. package/dist/src/handler.js.map +1 -0
  62. package/dist/src/heartbeat.d.ts +22 -0
  63. package/dist/src/heartbeat.d.ts.map +1 -0
  64. package/dist/src/heartbeat.js +87 -0
  65. package/dist/src/heartbeat.js.map +1 -0
  66. package/dist/src/index.d.ts +8 -0
  67. package/dist/src/index.d.ts.map +1 -0
  68. package/dist/src/index.js +25 -0
  69. package/dist/src/index.js.map +1 -0
  70. package/dist/src/network/network.d.ts +216 -0
  71. package/dist/src/network/network.d.ts.map +1 -0
  72. package/dist/{core/logger.js → src/network/network.js} +2 -1
  73. package/dist/src/network/network.js.map +1 -0
  74. package/dist/src/network/remote.d.ts +67 -0
  75. package/dist/src/network/remote.d.ts.map +1 -0
  76. package/dist/src/network/remote.js +515 -0
  77. package/dist/src/network/remote.js.map +1 -0
  78. package/dist/src/nursery.d.ts +19 -0
  79. package/dist/src/nursery.d.ts.map +1 -0
  80. package/dist/src/nursery.js +102 -0
  81. package/dist/src/nursery.js.map +1 -0
  82. package/dist/src/processor/processor.d.ts +11 -0
  83. package/dist/src/processor/processor.d.ts.map +1 -0
  84. package/dist/src/processor/processor.js +24 -0
  85. package/dist/src/processor/processor.js.map +1 -0
  86. package/dist/src/promises.d.ts +23 -0
  87. package/dist/src/promises.d.ts.map +1 -0
  88. package/dist/src/promises.js +157 -0
  89. package/dist/src/promises.js.map +1 -0
  90. package/dist/src/registry.d.ts +15 -0
  91. package/dist/src/registry.d.ts.map +1 -0
  92. package/dist/src/registry.js +26 -0
  93. package/dist/src/registry.js.map +1 -0
  94. package/dist/src/resonate-inner.d.ts +45 -0
  95. package/dist/src/resonate-inner.d.ts.map +1 -0
  96. package/dist/src/resonate-inner.js +157 -0
  97. package/dist/src/resonate-inner.js.map +1 -0
  98. package/dist/src/resonate.d.ts +92 -0
  99. package/dist/src/resonate.d.ts.map +1 -0
  100. package/dist/src/resonate.js +240 -0
  101. package/dist/src/resonate.js.map +1 -0
  102. package/dist/src/schedules.d.ts +9 -0
  103. package/dist/src/schedules.d.ts.map +1 -0
  104. package/dist/src/schedules.js +65 -0
  105. package/dist/src/schedules.js.map +1 -0
  106. package/dist/src/tasks.d.ts +9 -0
  107. package/dist/src/tasks.d.ts.map +1 -0
  108. package/dist/src/tasks.js +61 -0
  109. package/dist/src/tasks.js.map +1 -0
  110. package/dist/src/types.d.ts +86 -0
  111. package/dist/src/types.d.ts.map +1 -0
  112. package/dist/src/types.js +14 -0
  113. package/dist/src/types.js.map +1 -0
  114. package/dist/src/util.d.ts +14 -0
  115. package/dist/src/util.d.ts.map +1 -0
  116. package/dist/src/util.js +69 -0
  117. package/dist/src/util.js.map +1 -0
  118. package/dist/tsconfig.build.tsbuildinfo +1 -0
  119. package/package.json +51 -52
  120. package/dist/core/encoder.d.ts +0 -5
  121. package/dist/core/encoder.d.ts.map +0 -1
  122. package/dist/core/encoder.js +0 -3
  123. package/dist/core/encoder.js.map +0 -1
  124. package/dist/core/encoders/base64.d.ts +0 -6
  125. package/dist/core/encoders/base64.d.ts.map +0 -1
  126. package/dist/core/encoders/base64.js +0 -13
  127. package/dist/core/encoders/base64.js.map +0 -1
  128. package/dist/core/encoders/json.d.ts +0 -6
  129. package/dist/core/encoders/json.d.ts.map +0 -1
  130. package/dist/core/encoders/json.js +0 -77
  131. package/dist/core/encoders/json.js.map +0 -1
  132. package/dist/core/errors.d.ts +0 -24
  133. package/dist/core/errors.d.ts.map +0 -1
  134. package/dist/core/errors.js +0 -42
  135. package/dist/core/errors.js.map +0 -1
  136. package/dist/core/logger.d.ts +0 -10
  137. package/dist/core/logger.d.ts.map +0 -1
  138. package/dist/core/logger.js.map +0 -1
  139. package/dist/core/loggers/logger.d.ts +0 -13
  140. package/dist/core/loggers/logger.d.ts.map +0 -1
  141. package/dist/core/loggers/logger.js +0 -48
  142. package/dist/core/loggers/logger.js.map +0 -1
  143. package/dist/core/options.d.ts +0 -160
  144. package/dist/core/options.d.ts.map +0 -1
  145. package/dist/core/options.js +0 -18
  146. package/dist/core/options.js.map +0 -1
  147. package/dist/core/promises/promises.d.ts +0 -210
  148. package/dist/core/promises/promises.d.ts.map +0 -1
  149. package/dist/core/promises/promises.js +0 -300
  150. package/dist/core/promises/promises.js.map +0 -1
  151. package/dist/core/promises/types.d.ts +0 -42
  152. package/dist/core/promises/types.d.ts.map +0 -1
  153. package/dist/core/promises/types.js +0 -70
  154. package/dist/core/promises/types.js.map +0 -1
  155. package/dist/core/retry.d.ts +0 -37
  156. package/dist/core/retry.d.ts.map +0 -1
  157. package/dist/core/retry.js +0 -141
  158. package/dist/core/retry.js.map +0 -1
  159. package/dist/core/schedules/schedules.d.ts +0 -22
  160. package/dist/core/schedules/schedules.d.ts.map +0 -1
  161. package/dist/core/schedules/schedules.js +0 -29
  162. package/dist/core/schedules/schedules.js.map +0 -1
  163. package/dist/core/schedules/types.d.ts +0 -19
  164. package/dist/core/schedules/types.d.ts.map +0 -1
  165. package/dist/core/schedules/types.js +0 -8
  166. package/dist/core/schedules/types.js.map +0 -1
  167. package/dist/core/storage.d.ts +0 -6
  168. package/dist/core/storage.d.ts.map +0 -1
  169. package/dist/core/storage.js +0 -3
  170. package/dist/core/storage.js.map +0 -1
  171. package/dist/core/storages/memory.d.ts +0 -8
  172. package/dist/core/storages/memory.d.ts.map +0 -1
  173. package/dist/core/storages/memory.js +0 -29
  174. package/dist/core/storages/memory.js.map +0 -1
  175. package/dist/core/storages/withTimeout.d.ts +0 -10
  176. package/dist/core/storages/withTimeout.d.ts.map +0 -1
  177. package/dist/core/storages/withTimeout.js +0 -44
  178. package/dist/core/storages/withTimeout.js.map +0 -1
  179. package/dist/core/store.d.ts +0 -142
  180. package/dist/core/store.d.ts.map +0 -1
  181. package/dist/core/store.js +0 -3
  182. package/dist/core/store.js.map +0 -1
  183. package/dist/core/stores/local.d.ts +0 -57
  184. package/dist/core/stores/local.d.ts.map +0 -1
  185. package/dist/core/stores/local.js +0 -405
  186. package/dist/core/stores/local.js.map +0 -1
  187. package/dist/core/stores/remote.d.ts +0 -51
  188. package/dist/core/stores/remote.d.ts.map +0 -1
  189. package/dist/core/stores/remote.js +0 -431
  190. package/dist/core/stores/remote.js.map +0 -1
  191. package/dist/core/utils.d.ts +0 -85
  192. package/dist/core/utils.d.ts.map +0 -1
  193. package/dist/core/utils.js +0 -121
  194. package/dist/core/utils.js.map +0 -1
  195. package/dist/index.d.ts +0 -19
  196. package/dist/index.d.ts.map +0 -1
  197. package/dist/index.js +0 -57
  198. package/dist/index.js.map +0 -1
  199. package/dist/resonate.d.ts +0 -337
  200. package/dist/resonate.d.ts.map +0 -1
  201. package/dist/resonate.js +0 -730
  202. package/dist/resonate.js.map +0 -1
package/dist/resonate.js DELETED
@@ -1,730 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.InvocationHandle = exports.Context = exports.Resonate = void 0;
27
- const json_1 = require("./core/encoders/json");
28
- const errors_1 = require("./core/errors");
29
- const logger_1 = require("./core/loggers/logger");
30
- const options_1 = require("./core/options");
31
- const durablePromises = __importStar(require("./core/promises/promises"));
32
- const types_1 = require("./core/promises/types");
33
- const retryPolicies = __importStar(require("./core/retry"));
34
- const retry_1 = require("./core/retry");
35
- const schedules = __importStar(require("./core/schedules/schedules"));
36
- const local_1 = require("./core/stores/local");
37
- const remote_1 = require("./core/stores/remote");
38
- const utils = __importStar(require("./core/utils"));
39
- const utils_1 = require("./core/utils");
40
- //////////////////////////////////////////////////////////////////////
41
- class Resonate {
42
- #registeredFunctions = {};
43
- #invocationHandles;
44
- #interval;
45
- #resources;
46
- store;
47
- logger;
48
- defaultInvocationOptions;
49
- promises;
50
- schedules;
51
- constructor({ auth = undefined, encoder = new json_1.JSONEncoder(), heartbeat = 15000, // 15s
52
- logger = new logger_1.Logger(), pid = utils.randomId(), pollFrequency = 5000, // 5s
53
- retryPolicy = retryPolicies.exponential(), store = undefined, tags = {}, timeout = 10000, // 10s
54
- url = undefined, } = {}) {
55
- if (store) {
56
- this.store = store;
57
- }
58
- else if (url) {
59
- this.store = new remote_1.RemoteStore(url, {
60
- auth,
61
- heartbeat,
62
- logger,
63
- pid,
64
- });
65
- }
66
- else {
67
- this.store = new local_1.LocalStore({
68
- auth,
69
- heartbeat,
70
- logger,
71
- pid,
72
- });
73
- }
74
- this.logger = logger;
75
- this.#invocationHandles = new Map();
76
- this.#resources = new Map();
77
- this.defaultInvocationOptions = {
78
- __resonate: true,
79
- durable: true,
80
- eidFn: utils.randomId,
81
- encoder: encoder,
82
- idempotencyKeyFn: utils.hash,
83
- shouldLock: undefined,
84
- pollFrequency,
85
- retryPolicy,
86
- tags,
87
- timeout,
88
- version: 0,
89
- };
90
- // promises
91
- this.promises = {
92
- create: (id, timeout, opts = {}) => durablePromises.DurablePromise.create(this.promisesStore, encoder, id, timeout, opts),
93
- resolve: (id, value, opts = {}) => durablePromises.DurablePromise.resolve(this.promisesStore, encoder, id, value, opts),
94
- reject: (id, error, opts = {}) => durablePromises.DurablePromise.reject(this.promisesStore, encoder, id, error, opts),
95
- cancel: (id, error, opts = {}) => durablePromises.DurablePromise.cancel(this.promisesStore, encoder, id, error, opts),
96
- get: (id) => durablePromises.DurablePromise.get(this.promisesStore, encoder, id),
97
- search: (id, state, tags, limit) => durablePromises.DurablePromise.search(this.promisesStore, encoder, id, state, tags, limit),
98
- };
99
- // schedules
100
- this.schedules = {
101
- create: (id, cron, promiseId, promiseTimeout, opts = {}) => schedules.Schedule.create(this.store.schedules, encoder, id, cron, promiseId, promiseTimeout, opts),
102
- get: (id) => schedules.Schedule.get(this.store.schedules, encoder, id),
103
- search: (id, tags, limit) => schedules.Schedule.search(this.store.schedules, encoder, id, tags, limit),
104
- };
105
- }
106
- get promisesStore() {
107
- return this.store.promises;
108
- }
109
- get locksStore() {
110
- return this.store.locks;
111
- }
112
- options(opts) {
113
- return (0, options_1.options)(opts);
114
- }
115
- registeredFunction(funcName, version) {
116
- if (!this.#registeredFunctions[funcName]?.[version]) {
117
- throw new Error(`Function ${funcName} version ${version} not registered`);
118
- }
119
- return this.#registeredFunctions[funcName][version];
120
- }
121
- /**
122
- * Sets a global named resource for the Resonate instace. This resource will be available
123
- * in all the children Contexts of the current top level execution.
124
- *
125
- * Caller is responsible of the life cycle of the resource.
126
- *
127
- * @param name - A unique string identifier for the resource.
128
- * @param resource - The resource to be stored. Can be of any type.
129
- * @throws {Error} Throws an error if a resource with the same name already exists in the current Resonate instace.
130
- *
131
- */
132
- setResource(name, resource) {
133
- if (this.#resources.has(name)) {
134
- throw new Error("Resource already set for this instance");
135
- }
136
- this.#resources.set(name, resource);
137
- }
138
- /**
139
- * Retrieves a resource by name from the Resonate instance.
140
- *
141
- * @template R - The expected type of the resource.
142
- * @param name - The unique string identifier of the resource to retrieve.
143
- * @returns The resource of type R if found, or undefined if not found.
144
- *
145
- * @remarks
146
- * The method uses type assertion to cast the resource to type R.
147
- * Ensure that the type parameter R matches the actual type of the stored resource
148
- * to avoid runtime type errors.
149
- */
150
- getResource(name) {
151
- return this.#resources.get(name);
152
- }
153
- register(name, func, opts = {}) {
154
- // set default version
155
- opts.version = opts.version ?? 1;
156
- // set default values for the options options
157
- const options = this.withDefaultOpts(opts);
158
- if (options.version <= 0) {
159
- throw new Error("Version must be greater than 0");
160
- }
161
- if (!this.#registeredFunctions[name]) {
162
- this.#registeredFunctions[name] = {};
163
- }
164
- if (this.#registeredFunctions[name][options.version]) {
165
- throw new Error(`Function ${name} version ${options.version} already registered`);
166
- }
167
- // Get the highest version number of existing functions with this name
168
- const latestVersion = Math.max(...Object.values(this.#registeredFunctions[name]).map((f) => f.opts.version));
169
- // If the new function's version is higher, register it as the latest (index 0)
170
- if (options.version > latestVersion) {
171
- this.#registeredFunctions[name][0] = { func, opts: options };
172
- }
173
- // register specific version
174
- this.#registeredFunctions[name][options.version] = { func, opts: options };
175
- }
176
- registerModule(module, opts = {}) {
177
- for (const key in module) {
178
- this.register(key, module[key], opts);
179
- }
180
- }
181
- /**
182
- * Start the resonate service which continually checks for pending promises
183
- * every `delay` ms.
184
- *
185
- * @param delay Frequency in ms to check for pending promises.
186
- */
187
- async start(delay = 5000) {
188
- clearInterval(this.#interval);
189
- // await the first run of the recovery path to avoid races with the normal flow of the program
190
- await this.#_start();
191
- this.#interval = setInterval(this.#_start.bind(this), delay);
192
- }
193
- /**
194
- * Stop the resonate service.
195
- */
196
- async stop() {
197
- clearInterval(this.#interval);
198
- }
199
- async #_start() {
200
- try {
201
- for await (const promises of this.promisesStore.search("*", "pending", { "resonate:invocation": "true" })) {
202
- for (const promiseRecord of promises) {
203
- const param = this.defaultInvocationOptions.encoder.decode(promiseRecord.param.data);
204
- if (param &&
205
- typeof param === "object" &&
206
- "func" in param &&
207
- typeof param.func === "string" &&
208
- "version" in param &&
209
- typeof param.version === "number" &&
210
- "args" in param &&
211
- Array.isArray(param.args) &&
212
- "retryPolicy" in param &&
213
- retryPolicies.isRetryPolicy(param.retryPolicy)) {
214
- // Since the promise is already created on the server, we should use that idempotencyKey.
215
- // If for whatever reason it is not, we should recalculate it using our defaults.
216
- const idempotencyKeyFn = (_) => {
217
- return (promiseRecord.idempotencyKeyForCreate ??
218
- this.defaultInvocationOptions.idempotencyKeyFn(promiseRecord.id));
219
- };
220
- await this.invokeLocal(param.func, promiseRecord.id, ...param.args, (0, options_1.options)({
221
- retryPolicy: param.retryPolicy,
222
- version: param.version,
223
- idempotencyKeyFn,
224
- }));
225
- }
226
- }
227
- }
228
- }
229
- catch (e) {
230
- // squash all errors and log,
231
- // transient errors will be ironed out in the next interval
232
- this.logger.error(e);
233
- }
234
- }
235
- async run(name, id, ...argsWithOverrides) {
236
- const handle = await this.invokeLocal(name, id, ...argsWithOverrides);
237
- return await handle.result();
238
- }
239
- async invokeLocal(name, id, ...argsWithOverrides) {
240
- if (this.#invocationHandles.has(id)) {
241
- return this.#invocationHandles.get(id);
242
- }
243
- const { args, opts: optionOverrides } = utils.split(argsWithOverrides);
244
- // version 0 means the latest registered version
245
- const givenVersion = optionOverrides?.version ?? 0;
246
- // guarantees we only use the overrides in case the user pass an object with more properties
247
- const { eidFn, idempotencyKeyFn, retryPolicy, tags, timeout, version } = optionOverrides;
248
- const { func, opts: registeredOpts } = this.registeredFunction(name, givenVersion);
249
- const opts = utils.mergeObjects({
250
- eidFn,
251
- idempotencyKeyFn,
252
- retryPolicy,
253
- tags,
254
- timeout,
255
- version,
256
- }, registeredOpts);
257
- // We want to preserve the registered version.
258
- opts.version = registeredOpts.version;
259
- // For tags we need to merge the objects themselves
260
- // giving priority to the passed tags and add the
261
- // resonate:invocation tag to identify a top level invocation
262
- opts.tags = { ...registeredOpts.tags, ...tags, "resonate:invocation": "true" };
263
- // locking is false by default
264
- opts.shouldLock = opts.shouldLock ?? false;
265
- const param = {
266
- func: name,
267
- version: opts.version,
268
- retryPolicy: opts.retryPolicy,
269
- args,
270
- };
271
- const idempotencyKey = opts.idempotencyKeyFn(id);
272
- const storedPromise = await this.promisesStore.create(id, idempotencyKey, false, undefined, opts.encoder.encode(param), Date.now() + opts.timeout, opts.tags);
273
- const ctx = Context.createRootContext(this, { id, name, opts, eid: opts.eidFn(id) });
274
- const resultPromise = _runFunc(func, ctx, args, idempotencyKey, storedPromise, this.store.locks, this.store.promises);
275
- const handle = new InvocationHandle(id, resultPromise);
276
- this.#invocationHandles.set(id, handle);
277
- return handle;
278
- }
279
- async schedule(name, cron, func, ...argsWithOpts) {
280
- const { args, opts: givenOpts } = utils.split(argsWithOpts);
281
- const opts = this.withDefaultOpts(givenOpts);
282
- if (typeof func === "function") {
283
- // if function is provided, the default version is 1
284
- // as opposed to 0 (alias for latest version)
285
- opts.version = opts.version || 1;
286
- this.register(name, func, opts);
287
- }
288
- const funcName = typeof func === "string" ? func : name;
289
- const { opts: { retryPolicy: retry, version, timeout, tags: promiseTags }, } = this.registeredFunction(funcName, opts.version);
290
- const idempotencyKey = opts.idempotencyKeyFn(funcName);
291
- const promiseParam = {
292
- func: funcName,
293
- version,
294
- retryPolicy: retry,
295
- args,
296
- };
297
- return await this.schedules.create(name, cron, "{{.id}}.{{.timestamp}}", timeout, {
298
- idempotencyKey,
299
- promiseParam,
300
- promiseTags,
301
- });
302
- }
303
- withDefaultOpts(givenOpts = {}) {
304
- // merge tags
305
- const tags = { ...this.defaultInvocationOptions.tags, ...givenOpts.tags };
306
- return {
307
- ...this.defaultInvocationOptions,
308
- ...givenOpts,
309
- tags,
310
- };
311
- }
312
- }
313
- exports.Resonate = Resonate;
314
- class Context {
315
- #resonate;
316
- #stopAllPolling = false;
317
- #invocationHandles;
318
- #aborted;
319
- #abortCause;
320
- #resources;
321
- #finalizers;
322
- childrenCount;
323
- invocationData;
324
- parent;
325
- root;
326
- constructor(resonate, invocationData, parent) {
327
- this.#resonate = resonate;
328
- this.#invocationHandles = new Map();
329
- this.#resources = new Map();
330
- this.#finalizers = [];
331
- this.#aborted = false;
332
- this.parent = parent;
333
- this.root = !parent ? this : parent.root;
334
- this.invocationData = invocationData;
335
- this.childrenCount = 0;
336
- }
337
- static createRootContext(resonate, invocationData) {
338
- return new Context(resonate, invocationData, undefined);
339
- }
340
- static createChildrenContext(parentCtx, invocationData) {
341
- return new Context(parentCtx.#resonate, invocationData, parentCtx);
342
- }
343
- async onRetry() {
344
- this.childrenCount = 0;
345
- await this.finalize();
346
- }
347
- async finalize() {
348
- // It is important to await all promises before finalizing the resources
349
- // doing it the other way around could cause problems
350
- await Promise.allSettled(Array.from(this.#invocationHandles, ([_, handle]) => handle.result()));
351
- // We need to run the finalizers in reverse insertion order since later set finalizers might have
352
- // a dependency in early set resources
353
- for (const finalizer of this.#finalizers.reverse()) {
354
- await finalizer();
355
- }
356
- this.#resources.clear();
357
- this.#finalizers = [];
358
- }
359
- abort(cause) {
360
- this.#aborted = true;
361
- this.#abortCause = cause;
362
- this.root.#aborted = true;
363
- this.root.#abortCause = cause;
364
- }
365
- get aborted() {
366
- return this.#aborted;
367
- }
368
- get abortCause() {
369
- return this.#abortCause;
370
- }
371
- /**
372
- * Adds a finalizer function to be executed at the end of the current context.
373
- * Finalizers are run in reverse order of their definition (last-in, first-out).
374
- *
375
- * @param fn - An asynchronous function to be executed as a finalizer.
376
- * It should return a Promise that resolves to void.
377
- *
378
- * @remarks
379
- * Finalizer functions must be non fallible.
380
- */
381
- addFinalizer(fn) {
382
- this.#finalizers.push(fn);
383
- }
384
- /**
385
- * Sets a named resource for the current context and optionally adds a finalizer.
386
- *
387
- * @param name - A unique string identifier for the resource.
388
- * @param resource - The resource to be stored. Can be of any type.
389
- * @param finalizer - Optional. An asynchronous function to be executed when the context ends.
390
- * Finalizers are run in reverse order of their addition to the context and
391
- * must not fail.
392
- * @throws {Error} Throws an error if a resource with the same name already exists in the current context.
393
- *
394
- * This method associates a resource with a unique name in the current context.
395
- * If a finalizer is provided, it will be executed when the context ends.
396
- * Finalizers are useful for cleanup operations, such as closing connections or freeing resources.
397
- */
398
- setResource(name, resource, finalizer) {
399
- if (this.#resources.has(name)) {
400
- throw new Error("Resource already set for this context");
401
- }
402
- this.#resources.set(name, resource);
403
- if (finalizer) {
404
- this.#finalizers.push(finalizer);
405
- }
406
- }
407
- /**
408
- * Retrieves a resource by name from the current context or its parent contexts.
409
- *
410
- * @template R - The expected type of the resource.
411
- * @param name - The unique string identifier of the resource to retrieve.
412
- * @returns The resource of type R if found, or undefined if not found.
413
- *
414
- * This method searches for a resource in the following order:
415
- * 1. In the current context.
416
- * 2. If not found, it recursively searches in parent contexts.
417
- * 3. Returns undefined if the resource is not found in any context.
418
- *
419
- * @remarks
420
- * The method uses type assertion to cast the resource to type R.
421
- * Ensure that the type parameter R matches the actual type of the stored resource
422
- * to avoid runtime type errors.
423
- */
424
- getResource(name) {
425
- let resource = this.#resources.get(name);
426
- if (resource) {
427
- return resource;
428
- }
429
- resource = this.parent ? this.parent.getResource(name) : undefined;
430
- if (!resource) {
431
- return this.#resonate.getResource(name);
432
- }
433
- return resource;
434
- }
435
- options(opts) {
436
- return (0, options_1.options)(opts);
437
- }
438
- async run(funcOrId, ...argsWithOpts) {
439
- let handle;
440
- if (typeof funcOrId === "string") {
441
- handle = await this.invokeRemote(funcOrId, ...argsWithOpts);
442
- }
443
- else {
444
- handle = await this.invokeLocal(funcOrId, ...argsWithOpts);
445
- }
446
- return await handle.result();
447
- }
448
- async invokeRemote(funcId, ...argsWithOpts) {
449
- if (this.#invocationHandles.has(funcId)) {
450
- return this.#invocationHandles.get(funcId);
451
- }
452
- const { opts: givenOpts } = utils.split(argsWithOpts);
453
- const { opts: registeredOpts } = this.#resonate.registeredFunction(this.root.invocationData.name, this.root.invocationData.opts.version);
454
- const opts = { ...registeredOpts, ...givenOpts };
455
- // Merge the tags
456
- opts.tags = { ...registeredOpts.tags, ...givenOpts?.tags };
457
- // Default lock is false for children execution
458
- opts.shouldLock = opts.shouldLock ?? false;
459
- // Children execution do not need params since we don't go trough the recovery path with children
460
- const param = {};
461
- const idempotencyKey = opts.idempotencyKeyFn(funcId);
462
- const storedPromise = await this.#resonate.promisesStore.create(funcId, idempotencyKey, false, undefined, opts.encoder.encode(param), Date.now() + opts.timeout, opts.tags);
463
- const runFunc = async () => {
464
- while (!this.#stopAllPolling) {
465
- const durablePromiseRecord = await this.#resonate.promisesStore.get(storedPromise.id);
466
- if (durablePromiseRecord.state !== "PENDING") {
467
- return (0, types_1.handleCompletedPromise)(durablePromiseRecord, opts.encoder);
468
- }
469
- // TODO: Consider using exponential backoff instead.
470
- (0, utils_1.sleep)(opts.pollFrequency);
471
- }
472
- throw new Error(`Polling of remote invocation with ${funcId} was stopped`);
473
- };
474
- const resultPromise = runFunc();
475
- const invocationHandle = new InvocationHandle(funcId, resultPromise);
476
- this.#invocationHandles.set(funcId, invocationHandle);
477
- return invocationHandle;
478
- }
479
- async invokeLocal(func, ...argsWithOpts) {
480
- const { args, opts: givenOpts } = utils.split(argsWithOpts);
481
- const { opts: registeredOpts } = this.#resonate.registeredFunction(this.root.invocationData.name, this.root.invocationData.opts.version);
482
- const opts = { ...registeredOpts, ...givenOpts };
483
- // Merge the tags
484
- opts.tags = { ...registeredOpts.tags, ...givenOpts.tags };
485
- // Default lock is false for children execution
486
- opts.shouldLock = opts.shouldLock ?? false;
487
- this.childrenCount++;
488
- // If it is an anonymous function give at anon name nested within the current invocation name
489
- const name = func.name ? func.name : `${this.invocationData.name}__anon${this.childrenCount}`;
490
- const id = `${this.invocationData.id}.${this.childrenCount}.${name}`;
491
- if (this.#invocationHandles.has(id)) {
492
- return this.#invocationHandles.get(id);
493
- }
494
- const ctx = Context.createChildrenContext(this, { name, id, eid: opts.eidFn(id), opts });
495
- if (!opts.durable) {
496
- const runFunc = async () => {
497
- const timeout = Date.now() + opts.timeout;
498
- return (await (0, retry_1.runWithRetry)(async () => await func(ctx, ...args), async () => await ctx.onRetry(), opts.retryPolicy, timeout));
499
- };
500
- const resultPromise = runFunc();
501
- const handle = new InvocationHandle(id, resultPromise);
502
- this.#invocationHandles.set(id, handle);
503
- return handle;
504
- }
505
- // Children execution do not need params since we don't go trough the recovery path with children
506
- const param = {};
507
- const idempotencyKey = opts.idempotencyKeyFn(id);
508
- const storedPromise = await this.#resonate.promisesStore.create(id, idempotencyKey, false, undefined, opts.encoder.encode(param), Date.now() + opts.timeout, opts.tags);
509
- const resultPromise = _runFunc(func, ctx, args, idempotencyKey, storedPromise, this.#resonate.store.locks, this.#resonate.store.promises);
510
- const invocationHandle = new InvocationHandle(id, resultPromise);
511
- this.#invocationHandles.set(id, invocationHandle);
512
- return invocationHandle;
513
- }
514
- /**
515
- * Durable version of sleep.
516
- * Sleep for the specified time (ms).
517
- *
518
- * @param ms Amount of time to sleep in milliseconds.
519
- * @returns A Promise that resolves after the specified time has elapsed.
520
- */
521
- async sleep(ms) {
522
- const id = `${this.invocationData.id}.${this.childrenCount++}`;
523
- const handle = await this.invokeRemote(id, (0, options_1.options)({ timeout: ms, pollFrequency: ms, tags: { "resonate:timeout": "true" }, durable: true }));
524
- await handle.result();
525
- }
526
- /**
527
- * Creates a Promise that is resolved with an array of results when all of the provided Promises
528
- * resolve, or rejected when any Promise is rejected.
529
- *
530
- * @param values An array of Promises.
531
- * @param opts Optional {@link options}.
532
- * @returns A new ResonatePromise.
533
- */
534
- all(values, opts = {}) {
535
- // catch all promises to prevent unhandled promise rejections,
536
- // since Promise.all will not be called in the case where the
537
- // durable promise already completed
538
- for (const v of values) {
539
- if (v instanceof Promise)
540
- v.catch(() => { });
541
- }
542
- // prettier-ignore
543
- return this.run(() => Promise.all(values), (0, options_1.options)({
544
- retryPolicy: retryPolicies.never(),
545
- ...opts,
546
- }));
547
- }
548
- /**
549
- * Creates a Promise that is fulfilled by the first given promise to be fulfilled, or rejected
550
- * with an AggregateError.
551
- *
552
- * @param values An array of Promises.
553
- * @param opts Optional {@link options}.
554
- * @returns A new ResonatePromise.
555
- */
556
- any(values, opts = {}) {
557
- // catch all promises to prevent unhandled promise rejections,
558
- // since Promise.any will not be called in the case where the
559
- // durable promise already completed
560
- for (const v of values) {
561
- if (v instanceof Promise)
562
- v.catch(() => { });
563
- }
564
- // prettier-ignore
565
- return this.run(() => Promise.any(values), (0, options_1.options)({
566
- retryPolicy: retryPolicies.never(),
567
- ...opts,
568
- }));
569
- }
570
- /**
571
- * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
572
- * or rejected.
573
- *
574
- * @param values An array of Promises.
575
- * @param opts Optional {@link options}.
576
- * @returns A new ResonatePromise.
577
- */
578
- race(values, opts = {}) {
579
- // catch all promises to prevent unhandled promise rejections,
580
- // since Promise.race will not be called in the case where the
581
- // durable promise already completed
582
- for (const v of values) {
583
- if (v instanceof Promise)
584
- v.catch(() => { });
585
- }
586
- // prettier-ignore
587
- return this.run(() => Promise.race(values), (0, options_1.options)({
588
- retryPolicy: retryPolicies.never(),
589
- ...opts,
590
- }));
591
- }
592
- /**
593
- * Creates a Promise that is resolved with an array of results when all of the provided Promises
594
- * resolve or reject.
595
- *
596
- * @param values An array of Promises.
597
- * @param opts Optional {@link options}.
598
- * @returns A new Promise.
599
- */
600
- allSettled(values, opts = {}) {
601
- // catch all promises to prevent unhandled promise rejections,
602
- // since Promise.allSettled will not be called in the case where the
603
- // durable promise already completed
604
- for (const v of values) {
605
- if (v instanceof Promise)
606
- v.catch(() => { });
607
- }
608
- // prettier-ignore
609
- return this.run(() => Promise.allSettled(values), (0, options_1.options)({
610
- retryPolicy: retryPolicies.never(),
611
- ...opts,
612
- }));
613
- }
614
- /**
615
- * Invoke a Resonate function in detached mode. Functions must first be registered with Resonate.
616
- * a detached invocation will not be implecitly awaited at the end of the current context, instead
617
- * it will be "supervised" as a top level invocation.
618
- *
619
- * @template R The return type of the function.
620
- * @param id A unique id for the function invocation.
621
- * @param name The function name.
622
- * @param argsWithOverrides The function arguments and options overrides.
623
- * @returns A Res.
624
- */
625
- async detached(name, id, ...argsWithOverrides) {
626
- return await this.#resonate.invokeLocal(name, id, ...argsWithOverrides);
627
- }
628
- }
629
- exports.Context = Context;
630
- class InvocationHandle {
631
- invocationId;
632
- resultPromise;
633
- constructor(invocationId, resultPromise) {
634
- this.invocationId = invocationId;
635
- this.resultPromise = resultPromise;
636
- }
637
- /**
638
- * get the current state of the resultPromise.
639
- *
640
- */
641
- async state() {
642
- return await utils.promiseState(this.resultPromise);
643
- }
644
- async result() {
645
- return this.resultPromise;
646
- }
647
- }
648
- exports.InvocationHandle = InvocationHandle;
649
- const acquireLock = async (id, eid, locksStore) => {
650
- try {
651
- return await locksStore.tryAcquire(id, eid);
652
- }
653
- catch (e) {
654
- // if lock is already acquired, return false so we can poll
655
- if (e instanceof errors_1.ResonateError && e.code === errors_1.ErrorCodes.STORE_FORBIDDEN) {
656
- return false;
657
- }
658
- throw e;
659
- }
660
- };
661
- const _runFunc = async (func, ctx, args, idempotencyKey, storedPromise, locksStore, promisesStore) => {
662
- const { id, eid, opts } = ctx.invocationData;
663
- // If the promise that comes back from the server is already completed, resolve or reject right away.
664
- if (storedPromise.state !== "PENDING") {
665
- return (0, types_1.handleCompletedPromise)(storedPromise, opts.encoder);
666
- }
667
- // storedPromise.state === "PENDING"
668
- try {
669
- // Acquire the lock if necessary
670
- if (opts.shouldLock) {
671
- while (!(await acquireLock(id, eid, locksStore))) {
672
- await (0, utils_1.sleep)(opts.pollFrequency);
673
- }
674
- }
675
- let error;
676
- let value;
677
- // we need to hold on to a boolean to determine if the function was successful,
678
- // we cannot rely on the value or error as these values could be undefined
679
- let success = true;
680
- try {
681
- value = await (0, retry_1.runWithRetry)(async () => await func(ctx, ...args), async () => await ctx.onRetry(), opts.retryPolicy, storedPromise.timeout);
682
- }
683
- catch (e) {
684
- // We need to capture the error to be able to reject the durable promise,
685
- // after that we will then propagate this error by rejecting the result promise
686
- error = e;
687
- success = false;
688
- }
689
- finally {
690
- // Resonate will implicitly await all the invocationHandles as the last
691
- // thing it does with the context before it goes out of scope
692
- await ctx.finalize();
693
- }
694
- if (ctx.root.aborted) {
695
- throw new errors_1.ResonateError("Unrecoverable Error: Aborting", errors_1.ErrorCodes.ABORT, ctx.root.abortCause);
696
- }
697
- let completedPromiseRecord;
698
- if (success) {
699
- completedPromiseRecord = await promisesStore.resolve(id, idempotencyKey, false, storedPromise.value.headers, opts.encoder.encode(value));
700
- }
701
- else {
702
- completedPromiseRecord = await promisesStore.reject(id, idempotencyKey, false, storedPromise.value.headers, opts.encoder.encode(error));
703
- }
704
- // Because of eventual consistency and recovery paths it is possible that we get a
705
- // rejected promise even if we did call `resolve` on it or the other way around.
706
- // What should never happen is that we get a "PENDING" promise
707
- return (0, types_1.handleCompletedPromise)(completedPromiseRecord, opts.encoder);
708
- }
709
- catch (err) {
710
- if (err instanceof errors_1.ResonateError && (err.code === errors_1.ErrorCodes.CANCELED || err.code === errors_1.ErrorCodes.TIMEDOUT)) {
711
- // Cancel and timeout errors, just forward them
712
- throw err;
713
- }
714
- else if (err instanceof errors_1.ResonateError && err.code !== errors_1.ErrorCodes.ABORT) {
715
- // Any other instance of ResonateError we must abort the current execution.
716
- ctx.abort(err);
717
- throw new errors_1.ResonateError("Unrecoverable Error: Aborting", errors_1.ErrorCodes.ABORT, err);
718
- }
719
- else {
720
- throw err;
721
- }
722
- }
723
- finally {
724
- // release lock if necessary
725
- if (opts.shouldLock) {
726
- await locksStore.release(id, eid);
727
- }
728
- }
729
- };
730
- //# sourceMappingURL=resonate.js.map