@uru-intelligence/app 2.2.1 → 2.2.5
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.
- package/README.md +319 -16
- package/dist/background-jobs.d.ts +4 -0
- package/dist/background-jobs.js +17 -22
- package/dist/dampers.d.ts +11 -4
- package/dist/datasets.js +9 -8
- package/dist/errors.js +4 -4
- package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
- package/dist/examples/customer-workflows/approved-external-write.js +162 -0
- package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
- package/dist/examples/customer-workflows/file-processor.js +53 -0
- package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
- package/dist/examples/customer-workflows/job-coordinator.js +1 -0
- package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
- package/dist/examples/customer-workflows/review-only-draft.js +48 -0
- package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
- package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
- package/dist/files.js +10 -4
- package/dist/index.d.ts +1 -1
- package/dist/invocations.d.ts +10 -0
- package/dist/invocations.js +70 -2
- package/dist/jobs.js +10 -5
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +27 -7
- package/dist/transport-invocation.d.ts +3 -1
- package/dist/transport-invocation.js +19 -4
- package/dist/transport-retry.d.ts +37 -10
- package/dist/transport-retry.js +172 -28
- package/dist/transport.d.ts +1 -19
- package/dist/transport.js +3 -2
- package/dist/types.d.ts +20 -1
- package/dist/uploads.js +167 -23
- package/package.json +32 -7
|
@@ -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/files.js
CHANGED
|
@@ -4,6 +4,8 @@ import { isRuntimeJsonObject } from './transport-json.js';
|
|
|
4
4
|
const LIBRARY_READ_BYTES = 5 * 1024 * 1024;
|
|
5
5
|
const OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
6
6
|
const RESPONSE_BYTES = Math.ceil(OUTPUT_BYTES / 3) * 4 + 8192;
|
|
7
|
+
// Uru's error envelope and an edge's error page are far smaller than this.
|
|
8
|
+
const ERROR_BODY_BYTES = 64 * 1024;
|
|
7
9
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8
10
|
const HASH = /^[0-9a-f]{64}$/;
|
|
9
11
|
function invalid() {
|
|
@@ -57,7 +59,7 @@ function base64(bytes) {
|
|
|
57
59
|
}
|
|
58
60
|
return btoa(binary);
|
|
59
61
|
}
|
|
60
|
-
async function readJson(response) {
|
|
62
|
+
async function readJson(response, maxBytes = RESPONSE_BYTES) {
|
|
61
63
|
const reader = response.body?.getReader();
|
|
62
64
|
if (reader === undefined)
|
|
63
65
|
invalid();
|
|
@@ -70,7 +72,7 @@ async function readJson(response) {
|
|
|
70
72
|
if (chunk.done)
|
|
71
73
|
break;
|
|
72
74
|
size += chunk.value.byteLength;
|
|
73
|
-
if (size >
|
|
75
|
+
if (size > maxBytes) {
|
|
74
76
|
await reader.cancel();
|
|
75
77
|
invalid();
|
|
76
78
|
}
|
|
@@ -100,8 +102,12 @@ export function createFilesContext(options) {
|
|
|
100
102
|
signal: signal === undefined ? AbortSignal.timeout(30_000) : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
101
103
|
});
|
|
102
104
|
if (!response.ok) {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
+
// The answer's body goes with the error, null when it is not JSON. The
|
|
106
|
+
// job runner reads its error code: a 500 with Uru's code ends the job,
|
|
107
|
+
// and a 500 with none came from an edge, so a retry-safe job gets its
|
|
108
|
+
// next attempt.
|
|
109
|
+
const body = await readJson(response, ERROR_BODY_BYTES).catch(() => null);
|
|
110
|
+
throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body });
|
|
105
111
|
}
|
|
106
112
|
return readJson(response);
|
|
107
113
|
};
|
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
|
*
|
package/dist/invocations.d.ts
CHANGED
|
@@ -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;
|
package/dist/invocations.js
CHANGED
|
@@ -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
|
|
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,19 +14,24 @@ 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
|
|
18
|
-
//
|
|
19
|
-
|
|
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.
|
|
21
|
+
const { body: answer, response } = await postWithResends({
|
|
20
22
|
body,
|
|
21
23
|
config: resolveDamperConfig(options.dampers),
|
|
22
24
|
headers,
|
|
23
|
-
|
|
25
|
+
repeatable: true,
|
|
24
26
|
runtimeFetch: resolveRuntimeFetch(options),
|
|
25
27
|
sendTimeoutMs: 30_000,
|
|
26
28
|
url,
|
|
27
29
|
});
|
|
30
|
+
// The answer's body goes with the error. The job runner reads its error
|
|
31
|
+
// code: a 500 with Uru's code ends the job, and a 500 with none came from
|
|
32
|
+
// an edge, so a retry-safe job gets its next attempt.
|
|
28
33
|
if (!response.ok) {
|
|
29
|
-
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body:
|
|
34
|
+
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: answer });
|
|
30
35
|
}
|
|
31
36
|
};
|
|
32
37
|
const noJobAttempt = () => new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
|
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 `
|
|
30
|
-
* the caller wants the value and a pending
|
|
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 `
|
|
60
|
-
* the caller wants the value and a pending
|
|
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
|
|
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 {};
|