@uru-intelligence/app 2.1.6 → 2.2.4

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 (43) hide show
  1. package/README.md +463 -14
  2. package/dist/background-jobs.d.ts +11 -0
  3. package/dist/background-jobs.js +571 -0
  4. package/dist/dampers.d.ts +24 -1
  5. package/dist/dampers.js +3 -0
  6. package/dist/dataset-boundary.js +38 -1
  7. package/dist/dataset-row.d.ts +9 -0
  8. package/dist/dataset-row.js +11 -0
  9. package/dist/datasets.d.ts +2 -1
  10. package/dist/datasets.js +82 -28
  11. package/dist/errors.js +5 -4
  12. package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
  13. package/dist/examples/customer-workflows/approved-external-write.js +162 -0
  14. package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
  15. package/dist/examples/customer-workflows/file-processor.js +53 -0
  16. package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
  17. package/dist/examples/customer-workflows/job-coordinator.js +1 -0
  18. package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
  19. package/dist/examples/customer-workflows/review-only-draft.js +48 -0
  20. package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
  21. package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
  22. package/dist/files.js +4 -1
  23. package/dist/index.d.ts +6 -3
  24. package/dist/index.js +20 -7
  25. package/dist/invocations.d.ts +11 -1
  26. package/dist/invocations.js +72 -4
  27. package/dist/job-run.d.ts +90 -0
  28. package/dist/job-run.js +229 -0
  29. package/dist/jobs.d.ts +3 -3
  30. package/dist/jobs.js +39 -11
  31. package/dist/runtime.d.ts +8 -4
  32. package/dist/runtime.js +27 -7
  33. package/dist/transport-deadline.d.ts +0 -1
  34. package/dist/transport-deadline.js +0 -27
  35. package/dist/transport-invocation.d.ts +23 -4
  36. package/dist/transport-invocation.js +114 -29
  37. package/dist/transport-retry.d.ts +68 -0
  38. package/dist/transport-retry.js +245 -0
  39. package/dist/transport.d.ts +5 -20
  40. package/dist/transport.js +54 -33
  41. package/dist/types.d.ts +203 -4
  42. package/dist/uploads.js +158 -19
  43. package/package.json +34 -9
@@ -0,0 +1,571 @@
1
+ import { UruAppRuntimeError } from "./errors.js";
2
+ import { isFinalExecutionStatus } from "./runtime.js";
3
+ import { awaitWithAbort, abortReason } from "./transport-deadline.js";
4
+ import { isRuntimeJsonObject } from "./transport-json.js";
5
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
6
+ class JobDeadlineExceeded extends Error {
7
+ constructor() {
8
+ super("The background job deadline expired.");
9
+ this.name = "JobDeadlineExceeded";
10
+ }
11
+ }
12
+ const runtimeError = (message) => new UruAppRuntimeError(message, { body: null, status: 0 });
13
+ const storageError = () => runtimeError("Background job storage is unavailable.");
14
+ const invalidRecordError = () => runtimeError("The saved background job request is invalid.");
15
+ const jsonObjectSnapshot = (value) => {
16
+ if (!isRuntimeJsonObject(value)) {
17
+ throw runtimeError("A background job input must be a JSON object.");
18
+ }
19
+ try {
20
+ const serialized = JSON.stringify(value);
21
+ if (serialized === undefined) {
22
+ throw new TypeError("JSON input could not be serialized.");
23
+ }
24
+ const copy = JSON.parse(serialized);
25
+ if (!isRuntimeJsonObject(copy)) {
26
+ throw new TypeError("JSON input could not be copied.");
27
+ }
28
+ return copy;
29
+ }
30
+ catch {
31
+ throw runtimeError("A background job input must be a JSON object.");
32
+ }
33
+ };
34
+ const canonicalJson = (value) => {
35
+ if (Array.isArray(value)) {
36
+ return `[${value.map(item => canonicalJson(item)).join(",")}]`;
37
+ }
38
+ if (value !== null && typeof value === "object") {
39
+ return `{${Object.keys(value)
40
+ .toSorted()
41
+ .map(key => `${JSON.stringify(key)}:${canonicalJson(value[key] ?? null)}`)
42
+ .join(",")}}`;
43
+ }
44
+ return JSON.stringify(value);
45
+ };
46
+ const canonicalInput = (value) => {
47
+ if (!isRuntimeJsonObject(value)) {
48
+ throw invalidRecordError();
49
+ }
50
+ return canonicalJson(value);
51
+ };
52
+ const hasOnlyRecordKeys = (value) => {
53
+ const allowed = new Set([
54
+ "version",
55
+ "idempotencyKey",
56
+ "deploymentId",
57
+ "capabilityName",
58
+ "input",
59
+ "deadlineAt",
60
+ "timeoutMs",
61
+ "executionId",
62
+ "cancelRequested",
63
+ "cancelAcknowledged",
64
+ ]);
65
+ return Object.keys(value).every(key => allowed.has(key));
66
+ };
67
+ const recordFromUnknown = (value) => {
68
+ if (!isRuntimeJsonObject(value) || !hasOnlyRecordKeys(value))
69
+ return null;
70
+ const version = value["version"];
71
+ const idempotencyKey = value["idempotencyKey"];
72
+ const deploymentId = value["deploymentId"];
73
+ const capabilityName = value["capabilityName"];
74
+ const input = value["input"];
75
+ const deadlineAt = value["deadlineAt"];
76
+ const executionId = value["executionId"];
77
+ const cancelRequested = value["cancelRequested"];
78
+ const cancelAcknowledged = value["cancelAcknowledged"];
79
+ const timeoutMs = value["timeoutMs"];
80
+ if (version !== 1 ||
81
+ typeof idempotencyKey !== "string" ||
82
+ idempotencyKey.trim() === "" ||
83
+ idempotencyKey.length > 128 ||
84
+ typeof deploymentId !== "string" ||
85
+ deploymentId.trim() === "" ||
86
+ typeof capabilityName !== "string" ||
87
+ capabilityName.trim() === "" ||
88
+ !isRuntimeJsonObject(input) ||
89
+ typeof deadlineAt !== "number" ||
90
+ !Number.isSafeInteger(deadlineAt) ||
91
+ (executionId !== null &&
92
+ (typeof executionId !== "string" ||
93
+ executionId.trim() === "" ||
94
+ executionId.length > 128)) ||
95
+ typeof cancelRequested !== "boolean" ||
96
+ typeof cancelAcknowledged !== "boolean" ||
97
+ (cancelAcknowledged && !cancelRequested) ||
98
+ (Object.hasOwn(value, "timeoutMs") &&
99
+ (typeof timeoutMs !== "number" ||
100
+ !Number.isInteger(timeoutMs) ||
101
+ timeoutMs < 1000 ||
102
+ timeoutMs > 60_000))) {
103
+ return null;
104
+ }
105
+ const copiedInput = jsonObjectSnapshot(input);
106
+ const savedTimeoutMs = typeof timeoutMs === "number" ? timeoutMs : undefined;
107
+ return {
108
+ version: 1,
109
+ idempotencyKey,
110
+ deploymentId,
111
+ capabilityName,
112
+ input: copiedInput,
113
+ deadlineAt,
114
+ ...(savedTimeoutMs === undefined ? {} : { timeoutMs: savedTimeoutMs }),
115
+ executionId,
116
+ cancelRequested,
117
+ cancelAcknowledged,
118
+ };
119
+ };
120
+ const recordForStore = (record) => ({
121
+ version: 1,
122
+ idempotencyKey: record.idempotencyKey,
123
+ deploymentId: record.deploymentId,
124
+ capabilityName: record.capabilityName,
125
+ input: jsonObjectSnapshot(record.input),
126
+ deadlineAt: record.deadlineAt,
127
+ ...(record.timeoutMs === undefined ? {} : { timeoutMs: record.timeoutMs }),
128
+ executionId: record.executionId,
129
+ cancelRequested: record.cancelRequested,
130
+ cancelAcknowledged: record.cancelAcknowledged,
131
+ });
132
+ /**
133
+ * Whether two records hold the same logical request. The deployment that saved
134
+ * a record is not part of it: every release of the same Gem resumes the
135
+ * request, and the server answers its key and its execution across releases.
136
+ */
137
+ const sameRequest = (left, right) => left.idempotencyKey === right.idempotencyKey &&
138
+ left.capabilityName === right.capabilityName &&
139
+ left.deadlineAt === right.deadlineAt &&
140
+ left.timeoutMs === right.timeoutMs &&
141
+ canonicalInput(left.input) === canonicalInput(right.input);
142
+ /** Whether the store kept every saved field of a record it wrote. */
143
+ const sameSavedRecord = (actual, expected) => sameRequest(actual, expected) && actual.deploymentId === expected.deploymentId;
144
+ const defaultSleep = async (milliseconds, signal) => {
145
+ let remaining = Math.max(0, milliseconds);
146
+ await new Promise((resolve, reject) => {
147
+ let timer;
148
+ const cleanup = () => {
149
+ if (timer !== undefined)
150
+ clearTimeout(timer);
151
+ signal.removeEventListener("abort", abort);
152
+ };
153
+ const abort = () => {
154
+ cleanup();
155
+ reject(abortReason(signal));
156
+ };
157
+ const schedule = () => {
158
+ if (signal.aborted) {
159
+ abort();
160
+ return;
161
+ }
162
+ if (remaining <= 0) {
163
+ cleanup();
164
+ resolve();
165
+ return;
166
+ }
167
+ const chunk = Math.min(remaining, MAX_TIMER_DELAY_MS);
168
+ timer = setTimeout(() => {
169
+ remaining -= chunk;
170
+ schedule();
171
+ }, chunk);
172
+ };
173
+ signal.addEventListener("abort", abort, { once: true });
174
+ schedule();
175
+ });
176
+ };
177
+ const createDeadlineSignal = (deadlineAt, now, callerSignal) => {
178
+ const controller = new AbortController();
179
+ let timer;
180
+ let disposed = false;
181
+ const expireWhenDue = () => {
182
+ if (disposed)
183
+ return;
184
+ const remaining = deadlineAt - now();
185
+ if (remaining <= 0) {
186
+ controller.abort(new JobDeadlineExceeded());
187
+ return;
188
+ }
189
+ timer = setTimeout(expireWhenDue, Math.min(remaining, MAX_TIMER_DELAY_MS));
190
+ };
191
+ expireWhenDue();
192
+ const signal = callerSignal === undefined
193
+ ? controller.signal
194
+ : AbortSignal.any([callerSignal, controller.signal]);
195
+ return {
196
+ signal,
197
+ expired: () => controller.signal.aborted || now() >= deadlineAt,
198
+ dispose: () => {
199
+ disposed = true;
200
+ if (timer !== undefined)
201
+ clearTimeout(timer);
202
+ },
203
+ };
204
+ };
205
+ const withDeadline = async (args) => {
206
+ const deadline = createDeadlineSignal(args.deadlineAt, args.now, args.signal);
207
+ try {
208
+ deadline.signal.throwIfAborted();
209
+ const result = await args.action(deadline.signal);
210
+ if (deadline.expired())
211
+ throw new JobDeadlineExceeded();
212
+ return result;
213
+ }
214
+ catch (error) {
215
+ if (deadline.expired())
216
+ throw new JobDeadlineExceeded();
217
+ throw error;
218
+ }
219
+ finally {
220
+ deadline.dispose();
221
+ }
222
+ };
223
+ const copyCallOptions = (options, signal = options?.signal) => ({
224
+ ...(signal === undefined ? {} : { signal }),
225
+ ...(options?.onEvent === undefined ? {} : { onEvent: options.onEvent }),
226
+ ...(options?.onStatus === undefined ? {} : { onStatus: options.onStatus }),
227
+ });
228
+ const invocationOptionsForRecord = (record, options, signal = options?.signal) => ({
229
+ ...copyCallOptions(options, signal),
230
+ idempotencyKey: record.idempotencyKey,
231
+ ...(record.timeoutMs === undefined ? {} : { timeoutMs: record.timeoutMs }),
232
+ });
233
+ const retryDelay = (status, pollIntervalMs) => {
234
+ const retryAfterSeconds = status.retryAfterSeconds;
235
+ if (typeof retryAfterSeconds !== "number" ||
236
+ !Number.isFinite(retryAfterSeconds) ||
237
+ retryAfterSeconds <= 0) {
238
+ return pollIntervalMs;
239
+ }
240
+ return Math.max(pollIntervalMs, Math.ceil(retryAfterSeconds * 1000));
241
+ };
242
+ /**
243
+ * Coordinate the released `job`, `jobStatus`, and `cancelJob` operations.
244
+ * The store saves request identity and control intent only; the server remains
245
+ * authoritative for execution state and results.
246
+ *
247
+ * A record keeps the deployment that saved it, for the caller's audit only.
248
+ * The coordinator of a later release of the same Gem observes, waits on,
249
+ * cancels and resumes it through its own client.
250
+ */
251
+ export const createUruBackgroundJobCoordinator = (options) => {
252
+ const deploymentId = options.deploymentId.trim();
253
+ if (deploymentId === "") {
254
+ throw runtimeError("A background job deployment id is required.");
255
+ }
256
+ if (deploymentId !== options.app.deploymentId.trim()) {
257
+ throw runtimeError("The background job deployment id must match the app runtime client.");
258
+ }
259
+ const pollIntervalMs = options.pollIntervalMs ?? 1000;
260
+ if (!Number.isInteger(pollIntervalMs) ||
261
+ pollIntervalMs < 50 ||
262
+ pollIntervalMs > 60_000) {
263
+ throw runtimeError("Invalid background job poll interval.");
264
+ }
265
+ const now = options.now ?? Date.now;
266
+ const sleep = options.sleep ?? defaultSleep;
267
+ const callStore = async (action) => {
268
+ try {
269
+ return await action();
270
+ }
271
+ catch {
272
+ throw storageError();
273
+ }
274
+ };
275
+ const readRecord = async (idempotencyKey) => {
276
+ const key = idempotencyKey.trim();
277
+ if (key === "" || key.length > 128) {
278
+ throw runtimeError("A background job idempotency key is required.");
279
+ }
280
+ const value = await callStore(() => options.store.load(key));
281
+ if (value === null)
282
+ return null;
283
+ const record = recordFromUnknown(value);
284
+ if (record === null || record.idempotencyKey !== key) {
285
+ throw invalidRecordError();
286
+ }
287
+ return record;
288
+ };
289
+ const requireRecord = async (idempotencyKey) => {
290
+ const record = await readRecord(idempotencyKey);
291
+ if (record === null) {
292
+ throw runtimeError("The background job request was not saved.");
293
+ }
294
+ return record;
295
+ };
296
+ const validateUpdatedRecord = (expected, value) => {
297
+ const actual = recordFromUnknown(value);
298
+ if (actual === null || !sameSavedRecord(actual, expected)) {
299
+ throw invalidRecordError();
300
+ }
301
+ return actual;
302
+ };
303
+ const setExecutionId = async (record, executionId) => {
304
+ const saved = await callStore(() => options.store.setExecutionId(record.idempotencyKey, executionId));
305
+ const updated = validateUpdatedRecord(record, saved);
306
+ if (updated.executionId !== executionId)
307
+ throw invalidRecordError();
308
+ return updated;
309
+ };
310
+ const setCancelRequested = async (record) => {
311
+ const saved = await callStore(() => options.store.requestCancel(record.idempotencyKey));
312
+ const updated = validateUpdatedRecord(record, saved);
313
+ if (!updated.cancelRequested)
314
+ throw invalidRecordError();
315
+ return updated;
316
+ };
317
+ const setCancelAcknowledged = async (record) => {
318
+ const saved = await callStore(() => options.store.acknowledgeCancel(record.idempotencyKey));
319
+ const updated = validateUpdatedRecord(record, saved);
320
+ if (!updated.cancelRequested || !updated.cancelAcknowledged) {
321
+ throw invalidRecordError();
322
+ }
323
+ return updated;
324
+ };
325
+ const observeRecord = async (record, callOptions) => {
326
+ if (record.executionId === null) {
327
+ return { kind: "unknown", reason: "execution_id_missing", record };
328
+ }
329
+ const status = await options.app.jobStatus(record.executionId, copyCallOptions(callOptions));
330
+ const common = { record, executionId: record.executionId, status };
331
+ return isFinalExecutionStatus(status)
332
+ ? { kind: "complete", ...common }
333
+ : { kind: "pending", ...common };
334
+ };
335
+ const resumeRecord = async (initialRecord, callOptions) => {
336
+ let record = initialRecord;
337
+ let startResponse;
338
+ if (record.executionId === null) {
339
+ if (now() >= record.deadlineAt) {
340
+ return { kind: "unknown", reason: "deadline_expired", record };
341
+ }
342
+ try {
343
+ startResponse = await withDeadline({
344
+ deadlineAt: record.deadlineAt,
345
+ now,
346
+ ...(callOptions?.signal === undefined
347
+ ? {}
348
+ : { signal: callOptions.signal }),
349
+ action: async (signal) => await options.app.job(record.capabilityName, jsonObjectSnapshot(record.input), invocationOptionsForRecord(record, callOptions, signal)),
350
+ });
351
+ }
352
+ catch (error) {
353
+ if (error instanceof JobDeadlineExceeded) {
354
+ return { kind: "unknown", reason: "deadline_expired", record };
355
+ }
356
+ throw error;
357
+ }
358
+ const executionId = startResponse.executionId?.trim() ?? "";
359
+ if (executionId === "") {
360
+ return {
361
+ kind: "unknown",
362
+ reason: "execution_id_missing",
363
+ record,
364
+ startResponse,
365
+ };
366
+ }
367
+ record = await setExecutionId(record, executionId);
368
+ }
369
+ const executionId = record.executionId;
370
+ if (executionId === null) {
371
+ return {
372
+ kind: "unknown",
373
+ reason: "execution_id_missing",
374
+ record,
375
+ ...(startResponse === undefined ? {} : { startResponse }),
376
+ };
377
+ }
378
+ let cancelResponse;
379
+ if (record.cancelRequested && !record.cancelAcknowledged) {
380
+ let beforeCancel;
381
+ try {
382
+ beforeCancel = await observeRecord(record, callOptions);
383
+ }
384
+ catch (error) {
385
+ if (callOptions?.signal?.aborted === true) {
386
+ throw abortReason(callOptions.signal);
387
+ }
388
+ }
389
+ if (beforeCancel?.kind === "complete") {
390
+ return {
391
+ ...beforeCancel,
392
+ ...(startResponse === undefined ? {} : { startResponse }),
393
+ };
394
+ }
395
+ cancelResponse = await options.app.cancelJob(executionId, copyCallOptions(callOptions));
396
+ if (cancelResponse.ok) {
397
+ record = await setCancelAcknowledged(record);
398
+ }
399
+ }
400
+ const observation = await observeRecord(record, callOptions);
401
+ if (observation.kind === "unknown") {
402
+ return observation;
403
+ }
404
+ return {
405
+ ...observation,
406
+ ...(startResponse === undefined ? {} : { startResponse }),
407
+ ...(cancelResponse === undefined ? {} : { cancelResponse }),
408
+ };
409
+ };
410
+ const start = async (request, callOptions) => {
411
+ callOptions?.signal?.throwIfAborted();
412
+ const key = request.idempotencyKey.trim();
413
+ const name = request.capabilityName.trim();
414
+ if (key === "" || key.length > 128 || name === "") {
415
+ throw runtimeError("A background job name and idempotency key are required.");
416
+ }
417
+ if (!Number.isSafeInteger(request.deadlineAt) ||
418
+ request.deadlineAt <= now()) {
419
+ throw runtimeError("A future background job deadline is required.");
420
+ }
421
+ if (request.timeoutMs !== undefined &&
422
+ (!Number.isInteger(request.timeoutMs) ||
423
+ request.timeoutMs < 1000 ||
424
+ request.timeoutMs > 60_000)) {
425
+ throw runtimeError("Invalid background job request timeout.");
426
+ }
427
+ const record = {
428
+ version: 1,
429
+ idempotencyKey: key,
430
+ deploymentId,
431
+ capabilityName: name,
432
+ input: jsonObjectSnapshot(request.input ?? {}),
433
+ deadlineAt: request.deadlineAt,
434
+ ...(request.timeoutMs === undefined
435
+ ? {}
436
+ : { timeoutMs: request.timeoutMs }),
437
+ executionId: null,
438
+ cancelRequested: false,
439
+ cancelAcknowledged: false,
440
+ };
441
+ const created = await callStore(() => options.store.create(recordForStore(record)));
442
+ if (typeof created.created !== "boolean")
443
+ throw invalidRecordError();
444
+ const savedRecord = recordFromUnknown(created.record);
445
+ if (savedRecord === null || savedRecord.idempotencyKey !== key) {
446
+ throw invalidRecordError();
447
+ }
448
+ if (!created.created) {
449
+ if (!sameRequest(savedRecord, record)) {
450
+ throw runtimeError("This idempotency key belongs to another job request.");
451
+ }
452
+ throw runtimeError("This background job already exists. Use resume.");
453
+ }
454
+ if (!sameSavedRecord(savedRecord, record))
455
+ throw invalidRecordError();
456
+ const response = await withDeadline({
457
+ deadlineAt: record.deadlineAt,
458
+ now,
459
+ ...(callOptions?.signal === undefined
460
+ ? {}
461
+ : { signal: callOptions.signal }),
462
+ action: async (signal) => await options.app.job(record.capabilityName, jsonObjectSnapshot(record.input), invocationOptionsForRecord(record, callOptions, signal)),
463
+ });
464
+ const executionId = response.executionId?.trim() ?? "";
465
+ const persistedRecord = executionId === ""
466
+ ? await requireRecord(key)
467
+ : await setExecutionId(record, executionId);
468
+ return { record: persistedRecord, response };
469
+ };
470
+ const resume = async (idempotencyKey, callOptions) => {
471
+ const record = await requireRecord(idempotencyKey);
472
+ return await resumeRecord(record, callOptions);
473
+ };
474
+ const observe = async (idempotencyKey, callOptions) => {
475
+ const record = await requireRecord(idempotencyKey);
476
+ return await observeRecord(record, callOptions);
477
+ };
478
+ const cancel = async (idempotencyKey, callOptions) => {
479
+ callOptions?.signal?.throwIfAborted();
480
+ let record = await requireRecord(idempotencyKey);
481
+ if (!record.cancelRequested) {
482
+ record = await setCancelRequested(record);
483
+ }
484
+ return await resumeRecord(record, callOptions);
485
+ };
486
+ const wait = async (idempotencyKey, callOptions) => {
487
+ let record = await requireRecord(idempotencyKey);
488
+ if (now() >= record.deadlineAt) {
489
+ return {
490
+ kind: "deadline_exceeded",
491
+ record,
492
+ ...(record.executionId === null
493
+ ? {}
494
+ : { executionId: record.executionId }),
495
+ };
496
+ }
497
+ let lastStatus;
498
+ let lastExecutionId = record.executionId ?? undefined;
499
+ try {
500
+ return await withDeadline({
501
+ deadlineAt: record.deadlineAt,
502
+ now,
503
+ ...(callOptions?.signal === undefined
504
+ ? {}
505
+ : { signal: callOptions.signal }),
506
+ action: async (signal) => {
507
+ const boundedOptions = copyCallOptions(callOptions, signal);
508
+ let result = await resumeRecord(record, boundedOptions);
509
+ record = result.record;
510
+ if (result.kind === "unknown") {
511
+ return result.reason === "deadline_expired"
512
+ ? {
513
+ kind: "deadline_exceeded",
514
+ record,
515
+ ...(lastExecutionId === undefined
516
+ ? {}
517
+ : { executionId: lastExecutionId }),
518
+ }
519
+ : result;
520
+ }
521
+ lastExecutionId = result.executionId;
522
+ lastStatus = result.status;
523
+ if (result.kind === "complete")
524
+ return result;
525
+ while (true) {
526
+ const delay = retryDelay(result.status, pollIntervalMs);
527
+ const remaining = record.deadlineAt - now();
528
+ if (remaining <= 0)
529
+ throw new JobDeadlineExceeded();
530
+ await awaitWithAbort(sleep(Math.min(delay, remaining), signal), signal);
531
+ if (now() >= record.deadlineAt)
532
+ throw new JobDeadlineExceeded();
533
+ const observation = await observeRecord(record, boundedOptions);
534
+ record = observation.record;
535
+ if (observation.kind === "unknown")
536
+ return observation;
537
+ lastExecutionId = observation.executionId;
538
+ lastStatus = observation.status;
539
+ if (observation.kind === "complete")
540
+ return observation;
541
+ result = {
542
+ ...observation,
543
+ ...(result.startResponse === undefined
544
+ ? {}
545
+ : { startResponse: result.startResponse }),
546
+ ...(result.cancelResponse === undefined
547
+ ? {}
548
+ : { cancelResponse: result.cancelResponse }),
549
+ };
550
+ }
551
+ },
552
+ });
553
+ }
554
+ catch (error) {
555
+ if (!(error instanceof JobDeadlineExceeded))
556
+ throw error;
557
+ const latest = await readRecord(idempotencyKey);
558
+ if (latest !== null)
559
+ record = latest;
560
+ return {
561
+ kind: "deadline_exceeded",
562
+ record,
563
+ ...(lastExecutionId === undefined
564
+ ? {}
565
+ : { executionId: lastExecutionId }),
566
+ ...(lastStatus === undefined ? {} : { status: lastStatus }),
567
+ };
568
+ }
569
+ };
570
+ return { cancel, observe, resume, start, wait };
571
+ };
package/dist/dampers.d.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  export interface ResolvedDamperConfig {
4
4
  readonly defaultIdempotencyKeys: boolean;
5
5
  readonly maxRateLimitRetries: number;
6
+ readonly maxTransportRetries: number;
7
+ readonly random: () => number;
6
8
  readonly rateLimitBaseDelayMs: number;
7
9
  readonly rateLimitMaxDelayMs: number;
8
10
  readonly forceRefreshMinIntervalMs: number;
@@ -11,10 +13,31 @@ export interface ResolvedDamperConfig {
11
13
  }
12
14
  /** Caller-supplied damper overrides; every field defaults (see {@link resolveDamperConfig}). */
13
15
  export interface UruRunawayDamperOptions {
14
- /** Give each invocation a unique key, reused by its retries (default `true`). */
16
+ /**
17
+ * Give each invocation a unique key, reused by its retries (default `true`).
18
+ * Inside a program job's step the key belongs to the job run, so a later
19
+ * attempt that runs the step again sends the same key.
20
+ */
15
21
  defaultIdempotencyKeys?: boolean;
16
22
  /** Max automatic retries on a 429 / rate_limited response (default 3; `<= 0` disables backoff). */
17
23
  maxRateLimitRetries?: number;
24
+ /**
25
+ * Max resends after a response the platform never gave: a failed or reset
26
+ * connection, a send with no answer after 30 seconds, a reply cut off after
27
+ * its headers, a 502, a 504, or a 503 without a platform error code. A keyed
28
+ * Dataset row write, `jobs.progress` and `jobs.checkpoint` are also sent
29
+ * again after a temporary answer: a 408, a 429 or a 503 that does not say
30
+ * `retryable: false`. The waits are about 0.5, 1, 2, 4, 8, 8 and 8 seconds,
31
+ * each stretched by up to twice for jitter; a temporary answer's
32
+ * `Retry-After` can make a wait longer, and one longer than the wait time
33
+ * left ends the resends at once. All the waits of one call add up to
34
+ * at most 63 seconds. Each send can also run 30 seconds before it counts as
35
+ * lost, so in the worst case one call takes about 5 minutes: 8 sends of 30
36
+ * seconds and 63 seconds of waits (default 7; `<= 0` disables resends).
37
+ */
38
+ maxTransportRetries?: number;
39
+ /** Jitter source in [0, 1); injectable for tests. Defaults to `Math.random`. */
40
+ random?: () => number;
18
41
  /** Base backoff delay (ms) for the first 429 retry (default 500). */
19
42
  rateLimitBaseDelayMs?: number;
20
43
  /** Ceiling on any single backoff wait (ms) (default 10000). */
package/dist/dampers.js CHANGED
@@ -13,6 +13,7 @@ const safeRecordValue = (record, field) => {
13
13
  const MAX_RETRY_AFTER_SECONDS = (Number.MAX_SAFE_INTEGER - 1) / 1000;
14
14
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
15
15
  const DEFAULT_MAX_RATE_LIMIT_RETRIES = 3;
16
+ const DEFAULT_MAX_TRANSPORT_RETRIES = 7;
16
17
  const DEFAULT_RATE_LIMIT_BASE_DELAY_MS = 500;
17
18
  const DEFAULT_RATE_LIMIT_MAX_DELAY_MS = 10_000;
18
19
  const DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS = 5000;
@@ -69,7 +70,9 @@ export const resolveDamperConfig = (options) => ({
69
70
  forceRefreshMinIntervalMs: nonNegativeOr(options?.forceRefreshMinIntervalMs, DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS),
70
71
  // `<= 0` disables backoff — clamped to 0 (no retries) rather than negative.
71
72
  maxRateLimitRetries: nonNegativeOr(options?.maxRateLimitRetries, DEFAULT_MAX_RATE_LIMIT_RETRIES),
73
+ maxTransportRetries: nonNegativeOr(options?.maxTransportRetries, DEFAULT_MAX_TRANSPORT_RETRIES),
72
74
  now: options?.now ?? (() => Date.now()),
75
+ random: options?.random ?? (() => Math.random()),
73
76
  rateLimitBaseDelayMs: positiveOr(options?.rateLimitBaseDelayMs, DEFAULT_RATE_LIMIT_BASE_DELAY_MS),
74
77
  rateLimitMaxDelayMs: positiveOr(options?.rateLimitMaxDelayMs, DEFAULT_RATE_LIMIT_MAX_DELAY_MS),
75
78
  sleep: options?.sleep ?? defaultSleep,
@@ -155,7 +155,44 @@ export const decodeDatasetRowsResult = (value, decodeRow) => {
155
155
  export const decodeDefaultDatasetRowsResult = (value) => {
156
156
  const label = "Uru Dataset query";
157
157
  const body = responseObject(value, label);
158
- return rowsResultFields(body, [...requiredRows(body.rows, label)], label);
158
+ const rows = requiredRows(body.rows, label).map((row, index) => {
159
+ if (typeof row.id !== "string" || !isRuntimeJsonObject(row.fields)) {
160
+ return invalidResponse(label, body.rows, `rows[${index}]`);
161
+ }
162
+ const rowVersion = row.rowVersion;
163
+ const createdAt = row.createdAt;
164
+ const updatedAt = row.updatedAt;
165
+ const deleted = row.deleted;
166
+ if (hasOwn(row, "rowVersion")) {
167
+ if (typeof rowVersion !== "string") {
168
+ return invalidResponse(label, body.rows, `rows[${index}].rowVersion`);
169
+ }
170
+ }
171
+ if (hasOwn(row, "createdAt")) {
172
+ if (typeof createdAt !== "string") {
173
+ return invalidResponse(label, body.rows, `rows[${index}].createdAt`);
174
+ }
175
+ }
176
+ if (hasOwn(row, "updatedAt")) {
177
+ if (typeof updatedAt !== "string") {
178
+ return invalidResponse(label, body.rows, `rows[${index}].updatedAt`);
179
+ }
180
+ }
181
+ if (hasOwn(row, "deleted")) {
182
+ if (typeof deleted !== "boolean") {
183
+ return invalidResponse(label, body.rows, `rows[${index}].deleted`);
184
+ }
185
+ }
186
+ return {
187
+ id: row.id,
188
+ fields: row.fields,
189
+ ...(typeof rowVersion === "string" ? { rowVersion } : {}),
190
+ ...(typeof createdAt === "string" ? { createdAt } : {}),
191
+ ...(typeof updatedAt === "string" ? { updatedAt } : {}),
192
+ ...(typeof deleted === "boolean" ? { deleted } : {}),
193
+ };
194
+ });
195
+ return rowsResultFields(body, rows, label);
159
196
  };
160
197
  const requiredBoolean = (body, field, label) => {
161
198
  const value = body[field];
@@ -0,0 +1,9 @@
1
+ import type { UruDatasetRowMutationInput, UruDatasetRowView } from "./types.js";
2
+ import type { RuntimeJsonObject } from "./transport-json.js";
3
+ /**
4
+ * Convert a native Dataset row view into a lossless row update.
5
+ *
6
+ * Keep row identity separate from customer fields. A flat row cannot represent
7
+ * a customer field named `id` because that key names the row in an upsert.
8
+ */
9
+ export declare const datasetRowForMutation: <TFields extends RuntimeJsonObject>(row: UruDatasetRowView<TFields>) => UruDatasetRowMutationInput<TFields>;