@uru-intelligence/app 2.1.6 → 2.2.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.
@@ -0,0 +1,576 @@
1
+ import { UruAppRuntimeError } from "./errors.js";
2
+ import { awaitWithAbort, abortReason } from "./transport-deadline.js";
3
+ import { isRuntimeJsonObject } from "./transport-json.js";
4
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
5
+ const TERMINAL_STATES = new Set(["succeeded", "failed", "canceled", "cancelled"]);
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
+ const sameRequest = (left, right) => left.idempotencyKey === right.idempotencyKey &&
133
+ left.deploymentId === right.deploymentId &&
134
+ left.capabilityName === right.capabilityName &&
135
+ left.deadlineAt === right.deadlineAt &&
136
+ left.timeoutMs === right.timeoutMs &&
137
+ canonicalInput(left.input) === canonicalInput(right.input);
138
+ const terminalStatus = (status) => {
139
+ if (status.pending === true)
140
+ return false;
141
+ return (status.pending === false ||
142
+ status.success === true ||
143
+ TERMINAL_STATES.has(status.state ?? "") ||
144
+ TERMINAL_STATES.has(status.status ?? ""));
145
+ };
146
+ const defaultSleep = async (milliseconds, signal) => {
147
+ let remaining = Math.max(0, milliseconds);
148
+ await new Promise((resolve, reject) => {
149
+ let timer;
150
+ const cleanup = () => {
151
+ if (timer !== undefined)
152
+ clearTimeout(timer);
153
+ signal.removeEventListener("abort", abort);
154
+ };
155
+ const abort = () => {
156
+ cleanup();
157
+ reject(abortReason(signal));
158
+ };
159
+ const schedule = () => {
160
+ if (signal.aborted) {
161
+ abort();
162
+ return;
163
+ }
164
+ if (remaining <= 0) {
165
+ cleanup();
166
+ resolve();
167
+ return;
168
+ }
169
+ const chunk = Math.min(remaining, MAX_TIMER_DELAY_MS);
170
+ timer = setTimeout(() => {
171
+ remaining -= chunk;
172
+ schedule();
173
+ }, chunk);
174
+ };
175
+ signal.addEventListener("abort", abort, { once: true });
176
+ schedule();
177
+ });
178
+ };
179
+ const createDeadlineSignal = (deadlineAt, now, callerSignal) => {
180
+ const controller = new AbortController();
181
+ let timer;
182
+ let disposed = false;
183
+ const expireWhenDue = () => {
184
+ if (disposed)
185
+ return;
186
+ const remaining = deadlineAt - now();
187
+ if (remaining <= 0) {
188
+ controller.abort(new JobDeadlineExceeded());
189
+ return;
190
+ }
191
+ timer = setTimeout(expireWhenDue, Math.min(remaining, MAX_TIMER_DELAY_MS));
192
+ };
193
+ expireWhenDue();
194
+ const signal = callerSignal === undefined
195
+ ? controller.signal
196
+ : AbortSignal.any([callerSignal, controller.signal]);
197
+ return {
198
+ signal,
199
+ expired: () => controller.signal.aborted || now() >= deadlineAt,
200
+ dispose: () => {
201
+ disposed = true;
202
+ if (timer !== undefined)
203
+ clearTimeout(timer);
204
+ },
205
+ };
206
+ };
207
+ const withDeadline = async (args) => {
208
+ const deadline = createDeadlineSignal(args.deadlineAt, args.now, args.signal);
209
+ try {
210
+ deadline.signal.throwIfAborted();
211
+ const result = await args.action(deadline.signal);
212
+ if (deadline.expired())
213
+ throw new JobDeadlineExceeded();
214
+ return result;
215
+ }
216
+ catch (error) {
217
+ if (deadline.expired())
218
+ throw new JobDeadlineExceeded();
219
+ throw error;
220
+ }
221
+ finally {
222
+ deadline.dispose();
223
+ }
224
+ };
225
+ const copyCallOptions = (options, signal = options?.signal) => ({
226
+ ...(signal === undefined ? {} : { signal }),
227
+ ...(options?.onEvent === undefined ? {} : { onEvent: options.onEvent }),
228
+ ...(options?.onStatus === undefined ? {} : { onStatus: options.onStatus }),
229
+ });
230
+ const invocationOptionsForRecord = (record, options, signal = options?.signal) => ({
231
+ ...copyCallOptions(options, signal),
232
+ idempotencyKey: record.idempotencyKey,
233
+ ...(record.timeoutMs === undefined ? {} : { timeoutMs: record.timeoutMs }),
234
+ });
235
+ const retryDelay = (status, pollIntervalMs) => {
236
+ const retryAfterSeconds = status.retryAfterSeconds;
237
+ if (typeof retryAfterSeconds !== "number" ||
238
+ !Number.isFinite(retryAfterSeconds) ||
239
+ retryAfterSeconds <= 0) {
240
+ return pollIntervalMs;
241
+ }
242
+ return Math.max(pollIntervalMs, Math.ceil(retryAfterSeconds * 1000));
243
+ };
244
+ /**
245
+ * Coordinate the released `job`, `jobStatus`, and `cancelJob` operations.
246
+ * The store saves request identity and control intent only; the server remains
247
+ * authoritative for execution state and results.
248
+ */
249
+ export const createUruBackgroundJobCoordinator = (options) => {
250
+ const deploymentId = options.deploymentId.trim();
251
+ if (deploymentId === "") {
252
+ throw runtimeError("A background job deployment id is required.");
253
+ }
254
+ if (deploymentId !== options.app.deploymentId.trim()) {
255
+ throw runtimeError("The background job deployment id must match the app runtime client.");
256
+ }
257
+ const pollIntervalMs = options.pollIntervalMs ?? 1000;
258
+ if (!Number.isInteger(pollIntervalMs) ||
259
+ pollIntervalMs < 50 ||
260
+ pollIntervalMs > 60_000) {
261
+ throw runtimeError("Invalid background job poll interval.");
262
+ }
263
+ const now = options.now ?? Date.now;
264
+ const sleep = options.sleep ?? defaultSleep;
265
+ const callStore = async (action) => {
266
+ try {
267
+ return await action();
268
+ }
269
+ catch {
270
+ throw storageError();
271
+ }
272
+ };
273
+ const readRecord = async (idempotencyKey) => {
274
+ const key = idempotencyKey.trim();
275
+ if (key === "" || key.length > 128) {
276
+ throw runtimeError("A background job idempotency key is required.");
277
+ }
278
+ const value = await callStore(() => options.store.load(key));
279
+ if (value === null)
280
+ return null;
281
+ const record = recordFromUnknown(value);
282
+ if (record === null ||
283
+ record.idempotencyKey !== key ||
284
+ record.deploymentId !== deploymentId) {
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 ||
299
+ actual.idempotencyKey !== expected.idempotencyKey ||
300
+ actual.deploymentId !== deploymentId ||
301
+ !sameRequest(actual, expected)) {
302
+ throw invalidRecordError();
303
+ }
304
+ return actual;
305
+ };
306
+ const setExecutionId = async (record, executionId) => {
307
+ const saved = await callStore(() => options.store.setExecutionId(record.idempotencyKey, executionId));
308
+ const updated = validateUpdatedRecord(record, saved);
309
+ if (updated.executionId !== executionId)
310
+ throw invalidRecordError();
311
+ return updated;
312
+ };
313
+ const setCancelRequested = async (record) => {
314
+ const saved = await callStore(() => options.store.requestCancel(record.idempotencyKey));
315
+ const updated = validateUpdatedRecord(record, saved);
316
+ if (!updated.cancelRequested)
317
+ throw invalidRecordError();
318
+ return updated;
319
+ };
320
+ const setCancelAcknowledged = async (record) => {
321
+ const saved = await callStore(() => options.store.acknowledgeCancel(record.idempotencyKey));
322
+ const updated = validateUpdatedRecord(record, saved);
323
+ if (!updated.cancelRequested || !updated.cancelAcknowledged) {
324
+ throw invalidRecordError();
325
+ }
326
+ return updated;
327
+ };
328
+ const observeRecord = async (record, callOptions) => {
329
+ if (record.executionId === null) {
330
+ return { kind: "unknown", reason: "execution_id_missing", record };
331
+ }
332
+ const status = await options.app.jobStatus(record.executionId, copyCallOptions(callOptions));
333
+ const common = { record, executionId: record.executionId, status };
334
+ return terminalStatus(status)
335
+ ? { kind: "complete", ...common }
336
+ : { kind: "pending", ...common };
337
+ };
338
+ const resumeRecord = async (initialRecord, callOptions) => {
339
+ let record = initialRecord;
340
+ let startResponse;
341
+ if (record.executionId === null) {
342
+ if (now() >= record.deadlineAt) {
343
+ return { kind: "unknown", reason: "deadline_expired", record };
344
+ }
345
+ try {
346
+ startResponse = await withDeadline({
347
+ deadlineAt: record.deadlineAt,
348
+ now,
349
+ ...(callOptions?.signal === undefined
350
+ ? {}
351
+ : { signal: callOptions.signal }),
352
+ action: async (signal) => await options.app.job(record.capabilityName, jsonObjectSnapshot(record.input), invocationOptionsForRecord(record, callOptions, signal)),
353
+ });
354
+ }
355
+ catch (error) {
356
+ if (error instanceof JobDeadlineExceeded) {
357
+ return { kind: "unknown", reason: "deadline_expired", record };
358
+ }
359
+ throw error;
360
+ }
361
+ const executionId = startResponse.executionId?.trim() ?? "";
362
+ if (executionId === "") {
363
+ return {
364
+ kind: "unknown",
365
+ reason: "execution_id_missing",
366
+ record,
367
+ startResponse,
368
+ };
369
+ }
370
+ record = await setExecutionId(record, executionId);
371
+ }
372
+ const executionId = record.executionId;
373
+ if (executionId === null) {
374
+ return {
375
+ kind: "unknown",
376
+ reason: "execution_id_missing",
377
+ record,
378
+ ...(startResponse === undefined ? {} : { startResponse }),
379
+ };
380
+ }
381
+ let cancelResponse;
382
+ if (record.cancelRequested && !record.cancelAcknowledged) {
383
+ let beforeCancel;
384
+ try {
385
+ beforeCancel = await observeRecord(record, callOptions);
386
+ }
387
+ catch (error) {
388
+ if (callOptions?.signal?.aborted === true) {
389
+ throw abortReason(callOptions.signal);
390
+ }
391
+ }
392
+ if (beforeCancel?.kind === "complete") {
393
+ return {
394
+ ...beforeCancel,
395
+ ...(startResponse === undefined ? {} : { startResponse }),
396
+ };
397
+ }
398
+ cancelResponse = await options.app.cancelJob(executionId, copyCallOptions(callOptions));
399
+ if (cancelResponse.ok) {
400
+ record = await setCancelAcknowledged(record);
401
+ }
402
+ }
403
+ const observation = await observeRecord(record, callOptions);
404
+ if (observation.kind === "unknown") {
405
+ return observation;
406
+ }
407
+ return {
408
+ ...observation,
409
+ ...(startResponse === undefined ? {} : { startResponse }),
410
+ ...(cancelResponse === undefined ? {} : { cancelResponse }),
411
+ };
412
+ };
413
+ const start = async (request, callOptions) => {
414
+ callOptions?.signal?.throwIfAborted();
415
+ const key = request.idempotencyKey.trim();
416
+ const name = request.capabilityName.trim();
417
+ if (key === "" || key.length > 128 || name === "") {
418
+ throw runtimeError("A background job name and idempotency key are required.");
419
+ }
420
+ if (!Number.isSafeInteger(request.deadlineAt) ||
421
+ request.deadlineAt <= now()) {
422
+ throw runtimeError("A future background job deadline is required.");
423
+ }
424
+ if (request.timeoutMs !== undefined &&
425
+ (!Number.isInteger(request.timeoutMs) ||
426
+ request.timeoutMs < 1000 ||
427
+ request.timeoutMs > 60_000)) {
428
+ throw runtimeError("Invalid background job request timeout.");
429
+ }
430
+ const record = {
431
+ version: 1,
432
+ idempotencyKey: key,
433
+ deploymentId,
434
+ capabilityName: name,
435
+ input: jsonObjectSnapshot(request.input ?? {}),
436
+ deadlineAt: request.deadlineAt,
437
+ ...(request.timeoutMs === undefined
438
+ ? {}
439
+ : { timeoutMs: request.timeoutMs }),
440
+ executionId: null,
441
+ cancelRequested: false,
442
+ cancelAcknowledged: false,
443
+ };
444
+ const created = await callStore(() => options.store.create(recordForStore(record)));
445
+ if (typeof created.created !== "boolean")
446
+ throw invalidRecordError();
447
+ const savedRecord = recordFromUnknown(created.record);
448
+ if (savedRecord === null ||
449
+ savedRecord.idempotencyKey !== key ||
450
+ savedRecord.deploymentId !== deploymentId) {
451
+ throw invalidRecordError();
452
+ }
453
+ if (!created.created) {
454
+ if (!sameRequest(savedRecord, record)) {
455
+ throw runtimeError("This idempotency key belongs to another job request.");
456
+ }
457
+ throw runtimeError("This background job already exists. Use resume.");
458
+ }
459
+ if (!sameRequest(savedRecord, record))
460
+ throw invalidRecordError();
461
+ const response = await withDeadline({
462
+ deadlineAt: record.deadlineAt,
463
+ now,
464
+ ...(callOptions?.signal === undefined
465
+ ? {}
466
+ : { signal: callOptions.signal }),
467
+ action: async (signal) => await options.app.job(record.capabilityName, jsonObjectSnapshot(record.input), invocationOptionsForRecord(record, callOptions, signal)),
468
+ });
469
+ const executionId = response.executionId?.trim() ?? "";
470
+ const persistedRecord = executionId === ""
471
+ ? await requireRecord(key)
472
+ : await setExecutionId(record, executionId);
473
+ return { record: persistedRecord, response };
474
+ };
475
+ const resume = async (idempotencyKey, callOptions) => {
476
+ const record = await requireRecord(idempotencyKey);
477
+ return await resumeRecord(record, callOptions);
478
+ };
479
+ const observe = async (idempotencyKey, callOptions) => {
480
+ const record = await requireRecord(idempotencyKey);
481
+ return await observeRecord(record, callOptions);
482
+ };
483
+ const cancel = async (idempotencyKey, callOptions) => {
484
+ callOptions?.signal?.throwIfAborted();
485
+ let record = await requireRecord(idempotencyKey);
486
+ if (!record.cancelRequested) {
487
+ record = await setCancelRequested(record);
488
+ }
489
+ return await resumeRecord(record, callOptions);
490
+ };
491
+ const wait = async (idempotencyKey, callOptions) => {
492
+ let record = await requireRecord(idempotencyKey);
493
+ if (now() >= record.deadlineAt) {
494
+ return {
495
+ kind: "deadline_exceeded",
496
+ record,
497
+ ...(record.executionId === null
498
+ ? {}
499
+ : { executionId: record.executionId }),
500
+ };
501
+ }
502
+ let lastStatus;
503
+ let lastExecutionId = record.executionId ?? undefined;
504
+ try {
505
+ return await withDeadline({
506
+ deadlineAt: record.deadlineAt,
507
+ now,
508
+ ...(callOptions?.signal === undefined
509
+ ? {}
510
+ : { signal: callOptions.signal }),
511
+ action: async (signal) => {
512
+ const boundedOptions = copyCallOptions(callOptions, signal);
513
+ let result = await resumeRecord(record, boundedOptions);
514
+ record = result.record;
515
+ if (result.kind === "unknown") {
516
+ return result.reason === "deadline_expired"
517
+ ? {
518
+ kind: "deadline_exceeded",
519
+ record,
520
+ ...(lastExecutionId === undefined
521
+ ? {}
522
+ : { executionId: lastExecutionId }),
523
+ }
524
+ : result;
525
+ }
526
+ lastExecutionId = result.executionId;
527
+ lastStatus = result.status;
528
+ if (result.kind === "complete")
529
+ return result;
530
+ while (true) {
531
+ const delay = retryDelay(result.status, pollIntervalMs);
532
+ const remaining = record.deadlineAt - now();
533
+ if (remaining <= 0)
534
+ throw new JobDeadlineExceeded();
535
+ await awaitWithAbort(sleep(Math.min(delay, remaining), signal), signal);
536
+ if (now() >= record.deadlineAt)
537
+ throw new JobDeadlineExceeded();
538
+ const observation = await observeRecord(record, boundedOptions);
539
+ record = observation.record;
540
+ if (observation.kind === "unknown")
541
+ return observation;
542
+ lastExecutionId = observation.executionId;
543
+ lastStatus = observation.status;
544
+ if (observation.kind === "complete")
545
+ return observation;
546
+ result = {
547
+ ...observation,
548
+ ...(result.startResponse === undefined
549
+ ? {}
550
+ : { startResponse: result.startResponse }),
551
+ ...(result.cancelResponse === undefined
552
+ ? {}
553
+ : { cancelResponse: result.cancelResponse }),
554
+ };
555
+ }
556
+ },
557
+ });
558
+ }
559
+ catch (error) {
560
+ if (!(error instanceof JobDeadlineExceeded))
561
+ throw error;
562
+ const latest = await readRecord(idempotencyKey);
563
+ if (latest !== null)
564
+ record = latest;
565
+ return {
566
+ kind: "deadline_exceeded",
567
+ record,
568
+ ...(lastExecutionId === undefined
569
+ ? {}
570
+ : { executionId: lastExecutionId }),
571
+ ...(lastStatus === undefined ? {} : { status: lastStatus }),
572
+ };
573
+ }
574
+ };
575
+ return { cancel, observe, resume, start, wait };
576
+ };
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,24 @@ 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 reply cut off after its headers, a 502, a 504, or a 503
27
+ * without a platform error code. The waits are about 0.5, 1, 2, 4, 8, 8 and
28
+ * 8 seconds, each stretched by up to twice for jitter (default 7; `<= 0`
29
+ * disables resends).
30
+ */
31
+ maxTransportRetries?: number;
32
+ /** Jitter source in [0, 1); injectable for tests. Defaults to `Math.random`. */
33
+ random?: () => number;
18
34
  /** Base backoff delay (ms) for the first 429 retry (default 500). */
19
35
  rateLimitBaseDelayMs?: number;
20
36
  /** 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>;