@uru-intelligence/app 2.1.6 → 2.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +463 -14
- package/dist/background-jobs.d.ts +11 -0
- package/dist/background-jobs.js +571 -0
- package/dist/dampers.d.ts +24 -1
- package/dist/dampers.js +3 -0
- package/dist/dataset-boundary.js +38 -1
- package/dist/dataset-row.d.ts +9 -0
- package/dist/dataset-row.js +11 -0
- package/dist/datasets.d.ts +2 -1
- package/dist/datasets.js +82 -28
- package/dist/errors.js +5 -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 +4 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +20 -7
- package/dist/invocations.d.ts +11 -1
- package/dist/invocations.js +72 -4
- package/dist/job-run.d.ts +90 -0
- package/dist/job-run.js +229 -0
- package/dist/jobs.d.ts +3 -3
- package/dist/jobs.js +39 -11
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +27 -7
- package/dist/transport-deadline.d.ts +0 -1
- package/dist/transport-deadline.js +0 -27
- package/dist/transport-invocation.d.ts +23 -4
- package/dist/transport-invocation.js +114 -29
- package/dist/transport-retry.d.ts +68 -0
- package/dist/transport-retry.js +245 -0
- package/dist/transport.d.ts +5 -20
- package/dist/transport.js +54 -33
- package/dist/types.d.ts +203 -4
- package/dist/uploads.js +158 -19
- package/package.json +34 -9
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { UruBackgroundJobCallOptions, UruBackgroundJobRequest, UruDatasetRowMutationInput, UruJobCheckpoint, UruServerContext } from "@uru-intelligence/app";
|
|
2
|
+
import type { JobCoordinator } from "./job-coordinator.js";
|
|
3
|
+
export interface ScheduledCollectorStart {
|
|
4
|
+
sourceId: string;
|
|
5
|
+
requestId: string;
|
|
6
|
+
deadlineAt: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ScheduledCollectorInput {
|
|
9
|
+
sourceId: string;
|
|
10
|
+
}
|
|
11
|
+
/** One source order. Its source id is customer data, not a Uru row id. */
|
|
12
|
+
export interface CollectorOrderRow {
|
|
13
|
+
sourceRowId: string;
|
|
14
|
+
fields: UruDatasetRowMutationInput["fields"];
|
|
15
|
+
}
|
|
16
|
+
export interface CollectorPage {
|
|
17
|
+
rows: readonly CollectorOrderRow[];
|
|
18
|
+
nextCursor: string | null;
|
|
19
|
+
hasMore: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface CollectorResult {
|
|
22
|
+
pagesWritten: number;
|
|
23
|
+
nextCursor: string | null;
|
|
24
|
+
}
|
|
25
|
+
type CollectorDatasetContext = {
|
|
26
|
+
queryRows: UruServerContext["datasets"]["queryRows"];
|
|
27
|
+
upsertRows: UruServerContext["datasets"]["upsertRows"];
|
|
28
|
+
upsertRowViews: UruServerContext["datasets"]["upsertRowViews"];
|
|
29
|
+
};
|
|
30
|
+
type CollectorContext = {
|
|
31
|
+
datasets: CollectorDatasetContext;
|
|
32
|
+
jobs: Pick<UruServerContext["jobs"], "checkpoint" | "progress" | "step">;
|
|
33
|
+
};
|
|
34
|
+
export type ReadCollectorPage = (sourceId: string, cursor: string | null, signal: AbortSignal) => Promise<CollectorPage>;
|
|
35
|
+
export declare const scheduledCollectorRequest: (input: ScheduledCollectorStart) => UruBackgroundJobRequest;
|
|
36
|
+
export declare const startScheduledCollector: (coordinator: JobCoordinator, input: ScheduledCollectorStart, options?: UruBackgroundJobCallOptions) => Promise<{
|
|
37
|
+
record: import("@uru-intelligence/app").UruBackgroundJobRecord;
|
|
38
|
+
response: import("@uru-intelligence/app").UruAppRuntimeInvocationResponse;
|
|
39
|
+
}>;
|
|
40
|
+
export declare const resumeScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
|
|
41
|
+
export declare const observeScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobObservation>;
|
|
42
|
+
export declare const waitScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobWaitResult>;
|
|
43
|
+
export declare const cancelScheduledCollector: (coordinator: JobCoordinator, input: Pick<ScheduledCollectorStart, "sourceId" | "requestId">, options?: UruBackgroundJobCallOptions) => Promise<import("@uru-intelligence/app").UruBackgroundJobResumeResult>;
|
|
44
|
+
/** Run one scheduled collection. Every page write belongs to one named step. */
|
|
45
|
+
export declare const collectScheduledOrders: (context: CollectorContext, input: ScheduledCollectorInput, checkpoint: UruJobCheckpoint | null, signal: AbortSignal, readPage: ReadCollectorPage) => Promise<CollectorResult>;
|
|
46
|
+
export {};
|
|
@@ -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
|
@@ -27,7 +27,10 @@ function output(value) {
|
|
|
27
27
|
const createdAt = string(row['createdAt']);
|
|
28
28
|
if (!Number.isFinite(Date.parse(createdAt)))
|
|
29
29
|
invalid();
|
|
30
|
-
|
|
30
|
+
const fileDeleted = row['fileDeleted'];
|
|
31
|
+
if (typeof fileDeleted !== 'boolean')
|
|
32
|
+
invalid();
|
|
33
|
+
return { ...metadata(row, OUTPUT_BYTES), outputId: identifier(string(row['outputId'])), fileDeleted, createdAt };
|
|
31
34
|
}
|
|
32
35
|
function content(value, maxBytes) {
|
|
33
36
|
const row = object(value);
|
package/dist/index.d.ts
CHANGED
|
@@ -3,17 +3,20 @@
|
|
|
3
3
|
*
|
|
4
4
|
* THE PUBLIC SURFACE OF THE PACKAGE IS THIS FILE. Everything exported here is a
|
|
5
5
|
* promise to every project that installs it, so the barrel is deliberately
|
|
6
|
-
* small: one error class,
|
|
6
|
+
* small: one error class, a few factories, and the types a caller needs to name
|
|
7
7
|
* what they get back. Internal helpers live in `./runtime.js`, `./transport.js`,
|
|
8
|
-
* `./dampers.js` and `./error-response.js` and are not
|
|
8
|
+
* `./dampers.js`, `./background-jobs.js` and `./error-response.js` and are not
|
|
9
|
+
* re-exported.
|
|
9
10
|
*
|
|
10
11
|
* Adding an export here is an API decision. Removing one is a breaking change.
|
|
11
12
|
*/
|
|
12
13
|
import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeClient, UruProviderRuntimeEnvironment, UruServerContext } from "./types.js";
|
|
14
|
+
export { datasetRowForMutation } from "./dataset-row.js";
|
|
13
15
|
export { UruAppRuntimeError } from "./errors.js";
|
|
16
|
+
export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
|
|
14
17
|
export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
|
|
15
18
|
export type { UruRunawayDamperOptions } from "./dampers.js";
|
|
16
|
-
export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, 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";
|
|
17
20
|
/**
|
|
18
21
|
* Build a capability-invocation client against a Uru app runtime.
|
|
19
22
|
*
|
package/dist/index.js
CHANGED
|
@@ -3,19 +3,23 @@
|
|
|
3
3
|
*
|
|
4
4
|
* THE PUBLIC SURFACE OF THE PACKAGE IS THIS FILE. Everything exported here is a
|
|
5
5
|
* promise to every project that installs it, so the barrel is deliberately
|
|
6
|
-
* small: one error class,
|
|
6
|
+
* small: one error class, a few factories, and the types a caller needs to name
|
|
7
7
|
* what they get back. Internal helpers live in `./runtime.js`, `./transport.js`,
|
|
8
|
-
* `./dampers.js` and `./error-response.js` and are not
|
|
8
|
+
* `./dampers.js`, `./background-jobs.js` and `./error-response.js` and are not
|
|
9
|
+
* re-exported.
|
|
9
10
|
*
|
|
10
11
|
* Adding an export here is an API decision. Removing one is a breaking change.
|
|
11
12
|
*/
|
|
12
13
|
import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
|
|
13
14
|
import { createDatasetsContext } from "./datasets.js";
|
|
14
15
|
import { createFilesContext } from './files.js';
|
|
15
|
-
import { createJobProgress, createJobCheckpoint } from './jobs.js';
|
|
16
|
+
import { createJobProgress, createJobCheckpoint, createJobStep } from './jobs.js';
|
|
17
|
+
import { RANDOM_CALL_KEYS, jobAttemptFor, jobCallKeys } from './job-run.js';
|
|
16
18
|
import { UruAppRuntimeError } from "./errors.js";
|
|
17
19
|
import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
|
|
20
|
+
export { datasetRowForMutation } from "./dataset-row.js";
|
|
18
21
|
export { UruAppRuntimeError } from "./errors.js";
|
|
22
|
+
export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
|
|
19
23
|
export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
|
|
20
24
|
const ownEnvironmentValue = (env, key) => {
|
|
21
25
|
if (!Object.hasOwn(env, key)) {
|
|
@@ -74,16 +78,19 @@ const normalizedSecretName = (name) => {
|
|
|
74
78
|
* knows its deployment id and how to authenticate — a browser calling a
|
|
75
79
|
* public page's runtime, for example.
|
|
76
80
|
*/
|
|
77
|
-
export const createUruAppRuntimeClient = (options) =>
|
|
81
|
+
export const createUruAppRuntimeClient = (options) => appRuntimeClient(options, RANDOM_CALL_KEYS);
|
|
82
|
+
const appRuntimeClient = (options, keys) => {
|
|
78
83
|
// One damper runtime per client: the resolved config plus the forceRefresh
|
|
79
84
|
// throttle whose per-capability timestamps must persist across calls.
|
|
80
85
|
const damper = {
|
|
81
86
|
config: resolveDamperConfig(options.dampers),
|
|
87
|
+
keys,
|
|
82
88
|
throttle: new ForceRefreshThrottle(),
|
|
83
89
|
};
|
|
84
90
|
return {
|
|
85
91
|
action: createCapabilityInvoker(options, damper, "action"),
|
|
86
|
-
cancelJob: createCancelJobInvoker(options),
|
|
92
|
+
cancelJob: createCancelJobInvoker(options, damper),
|
|
93
|
+
deploymentId: options.deploymentId.trim(),
|
|
87
94
|
endpoint: createCapabilityInvoker(options, damper, "endpoint"),
|
|
88
95
|
job: createCapabilityInvoker(options, damper, "job"),
|
|
89
96
|
jobStatus: createJobStatusInvoker(options, damper),
|
|
@@ -128,16 +135,22 @@ export const createUruServerContext = (env, options = {}) => {
|
|
|
128
135
|
if (options.fetch !== undefined) {
|
|
129
136
|
clientOptions.fetch = options.fetch;
|
|
130
137
|
}
|
|
131
|
-
|
|
138
|
+
// In a program job, a call inside a step takes a key its job run owns, so
|
|
139
|
+
// a step that a lost attempt cut short sends the same keys when it runs
|
|
140
|
+
// again and the server replays each call. Other calls take random keys.
|
|
141
|
+
const attempt = jobAttemptFor(env);
|
|
142
|
+
const keys = attempt === null ? RANDOM_CALL_KEYS : jobCallKeys(attempt);
|
|
143
|
+
const app = appRuntimeClient(clientOptions, keys);
|
|
132
144
|
return {
|
|
133
145
|
actions: { run: createActionInvoker(app) },
|
|
134
146
|
app,
|
|
135
|
-
datasets: createDatasetsContext(app, clientOptions),
|
|
147
|
+
datasets: createDatasetsContext(app, clientOptions, keys),
|
|
136
148
|
files: createFilesContext(clientOptions),
|
|
137
149
|
jobs: {
|
|
138
150
|
start: app.job,
|
|
139
151
|
progress: createJobProgress(clientOptions, env),
|
|
140
152
|
checkpoint: createJobCheckpoint(clientOptions, env),
|
|
153
|
+
step: createJobStep(clientOptions, env),
|
|
141
154
|
},
|
|
142
155
|
secrets: {
|
|
143
156
|
get: (name) => {
|
package/dist/invocations.d.ts
CHANGED
|
@@ -3,5 +3,15 @@ import type { CreateUruAppRuntimeClientOptions, UruActionInvoker, UruAppRuntimeC
|
|
|
3
3
|
/** Overloads expose a typed result only when the transport runs its decoder. */
|
|
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
|
-
export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions) => UruCancelJobInvoker;
|
|
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) => {
|
|
@@ -13,15 +14,82 @@ export const createJobStatusInvoker = (options, damper) => {
|
|
|
13
14
|
}
|
|
14
15
|
return status;
|
|
15
16
|
};
|
|
16
|
-
export const createCancelJobInvoker = (options) => {
|
|
17
|
+
export const createCancelJobInvoker = (options, damper) => {
|
|
17
18
|
async function cancel(executionId, invocationOptions) {
|
|
18
|
-
return await cancelAppRuntimeJob(options, executionId, invocationOptions);
|
|
19
|
+
return await cancelAppRuntimeJob(options, executionId, invocationOptions, 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
|
};
|