@uru-intelligence/app 2.2.1 → 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.
@@ -0,0 +1,343 @@
1
+ const REQUEST_TIMEOUT_MS = 25_000;
2
+ const requestKey = (sourceId, requestId) => {
3
+ const key = `collector:${sourceId}:${requestId}`;
4
+ if (sourceId.trim() === "" ||
5
+ sourceId.length > 40 ||
6
+ requestId.trim() === "" ||
7
+ key.length > 128) {
8
+ throw new Error("Collector source and request ids must form a short stable key.");
9
+ }
10
+ return key;
11
+ };
12
+ export const scheduledCollectorRequest = (input) => ({
13
+ capabilityName: "collect_orders",
14
+ idempotencyKey: requestKey(input.sourceId, input.requestId),
15
+ input: { sourceId: input.sourceId },
16
+ deadlineAt: input.deadlineAt,
17
+ timeoutMs: REQUEST_TIMEOUT_MS,
18
+ });
19
+ export const startScheduledCollector = (coordinator, input, options) => coordinator.start(scheduledCollectorRequest(input), options);
20
+ export const resumeScheduledCollector = (coordinator, input, options) => coordinator.resume(requestKey(input.sourceId, input.requestId), options);
21
+ export const observeScheduledCollector = (coordinator, input, options) => coordinator.observe(requestKey(input.sourceId, input.requestId), options);
22
+ export const waitScheduledCollector = (coordinator, input, options) => coordinator.wait(requestKey(input.sourceId, input.requestId), options);
23
+ export const cancelScheduledCollector = (coordinator, input, options) => coordinator.cancel(requestKey(input.sourceId, input.requestId), options);
24
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
26
+ const decodeCollectorState = (expectedSourceId) => (value) => {
27
+ if (!isObject(value) || !isObject(value["fields"])) {
28
+ throw new Error("Collector state is invalid.");
29
+ }
30
+ const rowId = value["id"];
31
+ const fields = value["fields"];
32
+ const sourceId = fields["sourceId"];
33
+ const nextCursor = fields["nextCursor"];
34
+ if (typeof rowId !== "string" ||
35
+ !UUID_RE.test(rowId) ||
36
+ typeof sourceId !== "string" ||
37
+ sourceId !== expectedSourceId ||
38
+ (nextCursor !== null && typeof nextCursor !== "string")) {
39
+ throw new Error("Collector state is invalid.");
40
+ }
41
+ return { rowId, sourceId, nextCursor };
42
+ };
43
+ const readSavedState = async (context, sourceId) => {
44
+ const result = await context.datasets.queryRows("collector_state", {
45
+ limit: 2,
46
+ where: [{ field: "sourceId", op: "eq", value: sourceId }],
47
+ }, decodeCollectorState(sourceId));
48
+ if (result.rows.length !== 1) {
49
+ throw new Error("Collector state must have one existing row per source.");
50
+ }
51
+ return result.rows[0];
52
+ };
53
+ const checkpointStateRowId = (checkpoint) => {
54
+ if (checkpoint === null)
55
+ return undefined;
56
+ const rowId = checkpoint["stateRowId"];
57
+ if (rowId === undefined)
58
+ return undefined;
59
+ if (typeof rowId !== "string" || !UUID_RE.test(rowId)) {
60
+ throw new Error("Collector checkpoint state row id is invalid.");
61
+ }
62
+ return rowId;
63
+ };
64
+ const collectedOrderInserts = (sourceId, rows) => {
65
+ if (rows.length === 0)
66
+ return [];
67
+ if (rows.length > 1_000) {
68
+ throw new Error("A collector page can contain at most 1000 rows.");
69
+ }
70
+ const sourceRowIds = rows.map(row => row.sourceRowId.trim());
71
+ if (sourceRowIds.some(id => id === "" || id.length > 128) ||
72
+ new Set(sourceRowIds).size !== sourceRowIds.length) {
73
+ throw new Error("Collector source row ids must be unique and stable.");
74
+ }
75
+ return rows.map((row, index) => {
76
+ const sourceRowId = sourceRowIds[index];
77
+ return {
78
+ rowId: null,
79
+ expectedRowVersion: null,
80
+ fields: {
81
+ ...row.fields,
82
+ sourceId,
83
+ sourceRowId,
84
+ },
85
+ };
86
+ });
87
+ };
88
+ const checkpointCursor = (checkpoint, sourceId) => {
89
+ if (checkpoint === null)
90
+ return undefined;
91
+ const savedSourceId = checkpoint["sourceId"];
92
+ const cursor = checkpoint["nextCursor"];
93
+ if (savedSourceId === undefined && cursor === undefined)
94
+ return undefined;
95
+ if (typeof savedSourceId !== "string" ||
96
+ savedSourceId !== sourceId ||
97
+ (cursor !== null && typeof cursor !== "string")) {
98
+ throw new Error("Collector checkpoint does not match this source.");
99
+ }
100
+ return cursor;
101
+ };
102
+ const checkpointPageCount = (checkpoint) => {
103
+ if (checkpoint === null)
104
+ return 0;
105
+ const pagesWritten = checkpoint["pagesWritten"];
106
+ if (pagesWritten === undefined)
107
+ return 0;
108
+ if (typeof pagesWritten !== "number" ||
109
+ !Number.isSafeInteger(pagesWritten) ||
110
+ pagesWritten < 0) {
111
+ throw new Error("Collector checkpoint page count is invalid.");
112
+ }
113
+ return pagesWritten;
114
+ };
115
+ const checkpointPageSequence = (checkpoint) => {
116
+ if (checkpoint === null)
117
+ return 0;
118
+ const pageSequence = checkpoint["pageSequence"];
119
+ if (pageSequence === undefined)
120
+ return 0;
121
+ if (typeof pageSequence !== "number" ||
122
+ !Number.isSafeInteger(pageSequence) ||
123
+ pageSequence < 0) {
124
+ throw new Error("Collector checkpoint page sequence is invalid.");
125
+ }
126
+ return pageSequence;
127
+ };
128
+ const collectorStepName = (sequence) => `collect page ${sequence}`;
129
+ const decodeCollectorStepResult = (value) => {
130
+ if (!isObject(value)) {
131
+ throw new Error("Saved collector step is invalid.");
132
+ }
133
+ const kind = value["kind"];
134
+ const cursor = value["cursor"];
135
+ const nextCursor = value["nextCursor"];
136
+ const hasMore = value["hasMore"];
137
+ const sequence = value["sequence"];
138
+ const pagesWritten = value["pagesWritten"];
139
+ const stateRowId = value["stateRowId"];
140
+ if ((cursor !== null && typeof cursor !== "string") ||
141
+ (typeof cursor === "string" && cursor.length > 64) ||
142
+ (nextCursor !== null && typeof nextCursor !== "string") ||
143
+ (typeof nextCursor === "string" && nextCursor.length > 64) ||
144
+ typeof sequence !== "number" ||
145
+ !Number.isSafeInteger(sequence) ||
146
+ sequence < 1 ||
147
+ typeof pagesWritten !== "number" ||
148
+ !Number.isSafeInteger(pagesWritten) ||
149
+ pagesWritten < 0 ||
150
+ typeof stateRowId !== "string" ||
151
+ !UUID_RE.test(stateRowId)) {
152
+ throw new Error("Saved collector step is invalid.");
153
+ }
154
+ if (kind === "complete" &&
155
+ typeof hasMore === "boolean") {
156
+ return {
157
+ kind,
158
+ cursor,
159
+ nextCursor,
160
+ hasMore,
161
+ sequence,
162
+ pagesWritten,
163
+ stateRowId,
164
+ };
165
+ }
166
+ if (kind === "canceled" && hasMore === false) {
167
+ return {
168
+ kind,
169
+ cursor,
170
+ nextCursor,
171
+ hasMore,
172
+ sequence,
173
+ pagesWritten,
174
+ stateRowId,
175
+ };
176
+ }
177
+ throw new Error("Saved collector step is invalid.");
178
+ };
179
+ const completedCollectorSteps = (checkpoint) => {
180
+ if (checkpoint === null)
181
+ return [];
182
+ const rawSteps = checkpoint["$uruSteps"];
183
+ if (rawSteps === undefined)
184
+ return [];
185
+ if (!isObject(rawSteps)) {
186
+ throw new Error("Saved collector steps are invalid.");
187
+ }
188
+ const steps = Object.entries(rawSteps).map(([name, saved]) => {
189
+ if (!isObject(saved) || !Object.hasOwn(saved, "value")) {
190
+ throw new Error("Saved collector steps are invalid.");
191
+ }
192
+ const result = decodeCollectorStepResult(saved["value"]);
193
+ if (name !== collectorStepName(result.sequence)) {
194
+ throw new Error("Saved collector step does not match its sequence.");
195
+ }
196
+ return result;
197
+ });
198
+ steps.sort((left, right) => left.sequence - right.sequence);
199
+ if (steps.length > 0 && steps[0]?.sequence !== 1) {
200
+ throw new Error("Saved collector step sequence must start at page 1.");
201
+ }
202
+ steps.forEach((step, index) => {
203
+ const previous = steps[index - 1];
204
+ if (previous !== undefined) {
205
+ if (step.sequence !== previous.sequence + 1) {
206
+ throw new Error("Saved collector step sequence is invalid.");
207
+ }
208
+ if (step.cursor !== previous.nextCursor) {
209
+ throw new Error("Saved collector step cursor sequence is invalid.");
210
+ }
211
+ if (step.stateRowId !== null &&
212
+ previous.stateRowId !== null &&
213
+ step.stateRowId !== previous.stateRowId) {
214
+ throw new Error("Saved collector state row changed between pages.");
215
+ }
216
+ if (step.pagesWritten < previous.pagesWritten ||
217
+ step.pagesWritten > previous.pagesWritten + 1) {
218
+ throw new Error("Saved collector step page count is invalid.");
219
+ }
220
+ }
221
+ });
222
+ return steps;
223
+ };
224
+ /** Run one scheduled collection. Every page write belongs to one named step. */
225
+ export const collectScheduledOrders = async (context, input, checkpoint, signal, readPage) => {
226
+ if (input.sourceId.trim() === "" || input.sourceId.length > 40) {
227
+ throw new Error("Collector source id must be short and stable.");
228
+ }
229
+ const resumedCursor = checkpointCursor(checkpoint, input.sourceId);
230
+ const resumedStateRowId = checkpointStateRowId(checkpoint);
231
+ const savedSteps = completedCollectorSteps(checkpoint);
232
+ const lastSavedStep = savedSteps.at(-1);
233
+ const savedState = await readSavedState(context, input.sourceId);
234
+ let cursor;
235
+ let stateRowId = savedState.rowId;
236
+ let pagesWritten = checkpointPageCount(checkpoint);
237
+ let pageSequence = checkpointPageSequence(checkpoint);
238
+ if (resumedStateRowId !== undefined &&
239
+ resumedStateRowId !== savedState.rowId) {
240
+ throw new Error("Collector checkpoint names the wrong state row.");
241
+ }
242
+ if (lastSavedStep !== undefined && lastSavedStep.sequence >= pageSequence) {
243
+ const lastStep = lastSavedStep;
244
+ if (lastStep.stateRowId !== savedState.rowId) {
245
+ throw new Error("Saved collector step names the wrong state row.");
246
+ }
247
+ cursor = lastStep.nextCursor;
248
+ stateRowId = lastStep.stateRowId;
249
+ pagesWritten = lastStep.pagesWritten;
250
+ pageSequence = lastStep.sequence;
251
+ if (lastStep.kind === "canceled") {
252
+ return { pagesWritten, nextCursor: cursor };
253
+ }
254
+ if (!lastStep.hasMore) {
255
+ await context.jobs.checkpoint({
256
+ sourceId: input.sourceId,
257
+ nextCursor: cursor,
258
+ pagesWritten,
259
+ pageSequence,
260
+ stateRowId,
261
+ });
262
+ return { pagesWritten, nextCursor: cursor };
263
+ }
264
+ }
265
+ else if (resumedCursor !== undefined) {
266
+ cursor = resumedCursor;
267
+ }
268
+ else {
269
+ cursor = savedState.nextCursor;
270
+ }
271
+ if (cursor !== null && cursor.length > 64) {
272
+ throw new Error("Saved collector cursor is too long for a stable write key.");
273
+ }
274
+ for (;;) {
275
+ if (signal.aborted)
276
+ return { pagesWritten, nextCursor: cursor };
277
+ const sequence = pageSequence + 1;
278
+ const stepResult = await context.jobs.step(collectorStepName(sequence), async () => {
279
+ const page = await readPage(input.sourceId, cursor, signal);
280
+ if (signal.aborted) {
281
+ return {
282
+ kind: "canceled",
283
+ cursor,
284
+ nextCursor: cursor,
285
+ hasMore: false,
286
+ sequence,
287
+ pagesWritten,
288
+ stateRowId,
289
+ };
290
+ }
291
+ if (page.nextCursor !== null && page.nextCursor.length > 64) {
292
+ throw new Error("Collector cursor is too long for a stable write key.");
293
+ }
294
+ if (page.hasMore && page.nextCursor === null) {
295
+ throw new Error("Collector page needs a next cursor while more data remains.");
296
+ }
297
+ if ((page.rows.length > 0 || page.hasMore) &&
298
+ page.nextCursor === cursor) {
299
+ throw new Error("Collector page did not advance its cursor.");
300
+ }
301
+ if (page.rows.length > 0) {
302
+ const writes = collectedOrderInserts(input.sourceId, page.rows);
303
+ await context.datasets.upsertRowViews("collected_orders", writes);
304
+ }
305
+ await context.datasets.upsertRows("collector_state", [
306
+ {
307
+ id: stateRowId,
308
+ sourceId: input.sourceId,
309
+ nextCursor: page.nextCursor,
310
+ },
311
+ ]);
312
+ await context.jobs.progress({
313
+ completed: pagesWritten + (page.rows.length > 0 ? 1 : 0),
314
+ message: "Order pages saved",
315
+ });
316
+ return {
317
+ kind: "complete",
318
+ cursor,
319
+ nextCursor: page.nextCursor,
320
+ hasMore: page.hasMore,
321
+ sequence,
322
+ pagesWritten: pagesWritten + (page.rows.length > 0 ? 1 : 0),
323
+ stateRowId,
324
+ };
325
+ });
326
+ if (stepResult.kind === "canceled") {
327
+ return { pagesWritten, nextCursor: stepResult.nextCursor };
328
+ }
329
+ cursor = stepResult.nextCursor;
330
+ stateRowId = stepResult.stateRowId;
331
+ pagesWritten = stepResult.pagesWritten;
332
+ pageSequence = stepResult.sequence;
333
+ await context.jobs.checkpoint({
334
+ sourceId: input.sourceId,
335
+ nextCursor: cursor,
336
+ pagesWritten,
337
+ pageSequence,
338
+ stateRowId,
339
+ });
340
+ if (!stepResult.hasMore)
341
+ return { pagesWritten, nextCursor: cursor };
342
+ }
343
+ };
package/dist/index.d.ts CHANGED
@@ -16,7 +16,7 @@ export { UruAppRuntimeError } from "./errors.js";
16
16
  export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
17
17
  export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
18
18
  export type { UruRunawayDamperOptions } from "./dampers.js";
19
- export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadsContext, } from "./types.js";
19
+ export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadStatus, UruUploadsContext, } from "./types.js";
20
20
  /**
21
21
  * Build a capability-invocation client against a Uru app runtime.
22
22
  *
@@ -4,4 +4,14 @@ import type { CreateUruAppRuntimeClientOptions, UruActionInvoker, UruAppRuntimeC
4
4
  export declare const createCapabilityInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType) => UruCapabilityInvoker;
5
5
  export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime) => UruJobStatusInvoker;
6
6
  export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime) => UruCancelJobInvoker;
7
+ /**
8
+ * Run an action and return its result once it has ended.
9
+ *
10
+ * An action that takes longer than the server's synchronous wait answers
11
+ * pending with its execution id. The action goes on, so the run reads its
12
+ * status until it ends, after the server's retry hint, and returns or throws
13
+ * its final answer. The caller's `signal` and `timeoutMs` bound the whole run,
14
+ * the status reads included; `timeoutMs` also goes to the server with the
15
+ * action, as before.
16
+ */
7
17
  export declare const createActionInvoker: (app: UruAppRuntimeClient) => UruActionInvoker;
@@ -1,4 +1,5 @@
1
- import { requireCompletedRuntimeResponse } from "./runtime.js";
1
+ import { isFinalExecutionStatus, requireCompletedRuntimeResponse, requireSucceededExecutionStatus, } from "./runtime.js";
2
+ import { awaitWithAbort, withRuntimeRequestSignal, } from "./transport-deadline.js";
2
3
  import { cancelAppRuntimeJob, getAppRuntimeJobStatus, invokeAppRuntime, } from "./transport.js";
3
4
  /** Overloads expose a typed result only when the transport runs its decoder. */
4
5
  export const createCapabilityInvoker = (options, damper, capabilityType) => {
@@ -19,9 +20,76 @@ export const createCancelJobInvoker = (options, damper) => {
19
20
  }
20
21
  return cancel;
21
22
  };
23
+ /** The wait between two status reads when the server gives no hint. */
24
+ const ACTION_POLL_DEFAULT_MS = 1000;
25
+ const ACTION_POLL_MIN_MS = 250;
26
+ const ACTION_POLL_MAX_MS = 5000;
27
+ /** The server's retry hint for a pending status, kept between the bounds. */
28
+ const actionPollDelayMs = (status) => {
29
+ const seconds = status.retryAfterSeconds;
30
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
31
+ return ACTION_POLL_DEFAULT_MS;
32
+ }
33
+ return Math.min(Math.max(Math.round(seconds * 1000), ACTION_POLL_MIN_MS), ACTION_POLL_MAX_MS);
34
+ };
35
+ /** Wait between status reads. The run's signal ends the wait. */
36
+ const pause = async (milliseconds, signal) => {
37
+ let timer;
38
+ try {
39
+ await awaitWithAbort(new Promise((resolve) => {
40
+ timer = setTimeout(resolve, milliseconds);
41
+ }), signal);
42
+ }
43
+ finally {
44
+ if (timer !== undefined)
45
+ clearTimeout(timer);
46
+ }
47
+ };
48
+ /** The status-read options of one run: its signal, decoder and callbacks. */
49
+ const statusReadOptions = (invocationOptions, signal) => ({
50
+ ...(signal === undefined ? {} : { signal }),
51
+ ...(invocationOptions?.decodeResult === undefined
52
+ ? {}
53
+ : { decodeResult: invocationOptions.decodeResult }),
54
+ ...(invocationOptions?.onEvent === undefined
55
+ ? {}
56
+ : { onEvent: invocationOptions.onEvent }),
57
+ ...(invocationOptions?.onStatus === undefined
58
+ ? {}
59
+ : { onStatus: invocationOptions.onStatus }),
60
+ ...(invocationOptions?.requestId === undefined
61
+ ? {}
62
+ : { requestId: invocationOptions.requestId }),
63
+ });
64
+ /**
65
+ * Run an action and return its result once it has ended.
66
+ *
67
+ * An action that takes longer than the server's synchronous wait answers
68
+ * pending with its execution id. The action goes on, so the run reads its
69
+ * status until it ends, after the server's retry hint, and returns or throws
70
+ * its final answer. The caller's `signal` and `timeoutMs` bound the whole run,
71
+ * the status reads included; `timeoutMs` also goes to the server with the
72
+ * action, as before.
73
+ */
22
74
  export const createActionInvoker = (app) => {
23
75
  async function run(name, input, invocationOptions) {
24
- return await requireCompletedRuntimeResponse(app.action(name, input, invocationOptions));
76
+ return await withRuntimeRequestSignal(invocationOptions, async (signal) => {
77
+ const started = await app.action(name, input, {
78
+ ...invocationOptions,
79
+ ...(signal === undefined ? {} : { signal }),
80
+ });
81
+ const executionId = started.executionId?.trim() ?? "";
82
+ if (!started.pending || executionId === "") {
83
+ return await requireCompletedRuntimeResponse(Promise.resolve(started));
84
+ }
85
+ const readOptions = statusReadOptions(invocationOptions, signal);
86
+ let status = await app.jobStatus(executionId, readOptions);
87
+ while (!isFinalExecutionStatus(status)) {
88
+ await pause(actionPollDelayMs(status), signal);
89
+ status = await app.jobStatus(executionId, readOptions);
90
+ }
91
+ return requireSucceededExecutionStatus(status, started);
92
+ });
25
93
  }
26
94
  return run;
27
95
  };
package/dist/jobs.js CHANGED
@@ -14,13 +14,15 @@ const postJobUpdate = async (options, env, operation, body) => {
14
14
  headers.set('content-type', 'application/json');
15
15
  const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
16
16
  // Progress and a checkpoint replace the attempt's saved value, so the same
17
- // body is always safe to send again after a restarting server. Each one also
18
- // keeps the attempt's lease: it proves the job is alive.
17
+ // body is safe to send again after a restarting server, and after a
18
+ // temporary answer such as the job token's 503 during a short database
19
+ // stall. A temporary answer comes before the route saves anything. Each one
20
+ // also keeps the attempt's lease: it proves the job is alive.
19
21
  const { response } = await postWithResends({
20
22
  body,
21
23
  config: resolveDamperConfig(options.dampers),
22
24
  headers,
23
- resendLost: true,
25
+ repeatable: true,
24
26
  runtimeFetch: resolveRuntimeFetch(options),
25
27
  sendTimeoutMs: 30_000,
26
28
  url,
package/dist/runtime.d.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * Imports `./errors.js` and `./types.js`, both of which import nothing back.
14
14
  */
15
- import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeInvocationResponse } from "./types.js";
15
+ import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationResponse } from "./types.js";
16
16
  /** Drop one trailing `/` so a base URL concatenates cleanly with a rooted path. */
17
17
  export declare const trimTrailingSlash: (value: string) => string;
18
18
  /**
@@ -26,11 +26,15 @@ export declare const resolveHeaders: (headers: CreateUruAppRuntimeClientOptions[
26
26
  /**
27
27
  * Narrow an invocation response to its result, or throw.
28
28
  *
29
- * The unwrapping used by `context.actions.run` and `datasets.queryRows`, where
30
- * the caller wants the value and a pending or failed call is an error rather
31
- * than a state to render.
29
+ * The unwrapping used by `datasets.queryRows` and by `context.actions.run`
30
+ * once its action has ended, where the caller wants the value and a pending
31
+ * or failed call is an error rather than a state to render.
32
32
  */
33
33
  export declare const requireCompletedRuntimeResponse: (responsePromise: Promise<UruAppRuntimeInvocationResponse>) => Promise<unknown>;
34
+ /** Whether a job-status answer is the execution's final state. */
35
+ export declare const isFinalExecutionStatus: (status: UruAppRuntimeExecutionStatus) => boolean;
36
+ /** Narrow the final status of an execution to its result, or throw. */
37
+ export declare const requireSucceededExecutionStatus: (status: UruAppRuntimeExecutionStatus, started: UruAppRuntimeInvocationResponse) => unknown;
34
38
  /** The `fetch` shape the transport calls. Exactly the caller-supplied option. */
35
39
  export type RuntimeFetch = NonNullable<CreateUruAppRuntimeClientOptions["fetch"]>;
36
40
  /**
package/dist/runtime.js CHANGED
@@ -53,23 +53,43 @@ export const resolveHeaders = async (headers) => {
53
53
  }
54
54
  return headers;
55
55
  };
56
+ const notCompleted = (capabilityType, capabilityName, body) => new UruAppRuntimeError(`Uru app runtime ${capabilityType} '${capabilityName}' did not complete successfully.`, { body, status: 0 });
56
57
  /**
57
58
  * Narrow an invocation response to its result, or throw.
58
59
  *
59
- * The unwrapping used by `context.actions.run` and `datasets.queryRows`, where
60
- * the caller wants the value and a pending or failed call is an error rather
61
- * than a state to render.
60
+ * The unwrapping used by `datasets.queryRows` and by `context.actions.run`
61
+ * once its action has ended, where the caller wants the value and a pending
62
+ * or failed call is an error rather than a state to render.
62
63
  */
63
64
  export const requireCompletedRuntimeResponse = async (responsePromise) => {
64
65
  const response = await responsePromise;
65
66
  if (!response.ok || response.pending) {
66
- throw new UruAppRuntimeError(`Uru app runtime ${response.capabilityType} '${response.capabilityName}' did not complete successfully.`, {
67
- body: response,
68
- status: 0,
69
- });
67
+ throw notCompleted(response.capabilityType, response.capabilityName, response);
70
68
  }
71
69
  return response.result;
72
70
  };
71
+ const FINAL_EXECUTION_STATES = new Set([
72
+ "succeeded",
73
+ "failed",
74
+ "canceled",
75
+ "cancelled",
76
+ ]);
77
+ /** Whether a job-status answer is the execution's final state. */
78
+ export const isFinalExecutionStatus = (status) => {
79
+ if (status.pending === true)
80
+ return false;
81
+ return (status.pending === false ||
82
+ status.success === true ||
83
+ FINAL_EXECUTION_STATES.has(status.state ?? "") ||
84
+ FINAL_EXECUTION_STATES.has(status.status ?? ""));
85
+ };
86
+ /** Narrow the final status of an execution to its result, or throw. */
87
+ export const requireSucceededExecutionStatus = (status, started) => {
88
+ if (status.success !== true) {
89
+ throw notCompleted(started.capabilityType, started.capabilityName, status);
90
+ }
91
+ return status.result;
92
+ };
73
93
  /**
74
94
  * The one `fetch` every runtime call in this package goes through.
75
95
  *
@@ -45,7 +45,9 @@ export interface JobStatusFetchArguments {
45
45
  export declare const fetchJobStatus: (args: JobStatusFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
46
46
  /**
47
47
  * Ask for one execution to stop. A cancel names its execution and asks for
48
- * the same end state every time, so a lost response is sent again.
48
+ * the same end state every time, so a lost response is sent again. The route
49
+ * takes no body, but the job gateway accepts only a JSON POST, so the cancel
50
+ * sends an empty JSON object.
49
51
  */
50
52
  export declare const fetchJobCancel: (args: JobStatusFetchArguments, resent?: number) => Promise<RuntimeFetchResult>;
51
53
  export {};
@@ -159,11 +159,15 @@ export const fetchJobStatus = async (args, counts = FIRST_SEND) => {
159
159
  };
160
160
  /**
161
161
  * Ask for one execution to stop. A cancel names its execution and asks for
162
- * the same end state every time, so a lost response is sent again.
162
+ * the same end state every time, so a lost response is sent again. The route
163
+ * takes no body, but the job gateway accepts only a JSON POST, so the cancel
164
+ * sends an empty JSON object.
163
165
  */
164
166
  export const fetchJobCancel = async (args, resent = 0) => {
165
167
  const { runtimeFetch } = args;
166
- const outcome = await sendOnce(runtimeFetch, args.url, { headers: args.headers, method: "POST" }, args.signal);
168
+ const headers = new Headers(args.headers);
169
+ headers.set("content-type", "application/json");
170
+ const outcome = await sendOnce(runtimeFetch, args.url, { body: "{}", headers, method: "POST" }, args.signal);
167
171
  if (isLost(outcome) && canResend(args.damper.config, resent)) {
168
172
  await reconnect(args.damper, resent, args.signal, retryAfterSeconds => args.emit(jobReconnectingEvent(args, retryAfterSeconds)));
169
173
  return await fetchJobCancel(args, resent + 1);
@@ -1,13 +1,15 @@
1
1
  /**
2
- * Resends for a response the platform never gave.
2
+ * Resends for a response the platform never gave, and for a temporary answer.
3
3
  *
4
4
  * A deploy, a crash or a memory kill of one API replica shows up here as a
5
5
  * failed or reset connection, a reply cut off after its headers, a 502 or 504
6
6
  * from the edge, or a 503 from an edge with no healthy replica. None of them
7
7
  * is an answer from Uru: the call may not have arrived, or it arrived and its
8
- * reply was lost. Each caller decides whether its request is safe to send
9
- * again (a keyed action is, a Dataset SQL statement is not); this module owns
10
- * what counts as lost and how long to wait.
8
+ * reply was lost. A short database stall shows up as a temporary answer from
9
+ * Uru: a 408, a 429 or a 503. Each caller decides whether its request is safe
10
+ * to send again (a keyed Dataset write is, a Dataset SQL statement is not);
11
+ * this module owns what counts as lost, what counts as temporary, and how
12
+ * long to wait.
11
13
  */
12
14
  import type { ResolvedDamperConfig } from "./dampers.js";
13
15
  import type { RuntimeFetch } from "./runtime.js";
@@ -38,8 +40,14 @@ export interface PostWithResendsArguments {
38
40
  readonly body: string;
39
41
  readonly config: ResolvedDamperConfig;
40
42
  readonly headers: Headers;
41
- /** Whether a lost response may be sent again with the same body. */
42
- readonly resendLost: boolean;
43
+ /**
44
+ * Whether the same body is safe to send again: the server answers a keyed
45
+ * command from its first run, or the call replaces saved state. Such a call
46
+ * is sent again after a lost response and after a temporary answer
47
+ * ({@link isTemporaryAnswer}), and carries {@link SDK_RESENDS_HEADER}. Any
48
+ * other call is sent once.
49
+ */
50
+ readonly repeatable: boolean;
43
51
  readonly runtimeFetch: RuntimeFetch;
44
52
  /** The limit for one send. A send that reaches it counts as lost. */
45
53
  readonly sendTimeoutMs: number;
@@ -51,7 +59,10 @@ export interface PostWithResendsResult {
51
59
  readonly response: Response;
52
60
  }
53
61
  /**
54
- * POST one prepared body. When the platform gave no answer and the caller
55
- * allows it, send the same bytes again after the jittered wait.
62
+ * POST one prepared body. When the platform gave no answer or a temporary
63
+ * answer, and the call is repeatable, send the same bytes again after
64
+ * {@link resendWaitMs}. The resends stop at `maxTransportRetries` or when the
65
+ * wait budget is spent, and the last answer then goes to the caller. A final
66
+ * answer is never sent again.
56
67
  */
57
- export declare const postWithResends: (args: PostWithResendsArguments, resent?: number) => Promise<PostWithResendsResult>;
68
+ export declare const postWithResends: (args: PostWithResendsArguments, resent?: number, waitedMs?: number) => Promise<PostWithResendsResult>;