@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,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one program-job attempt keeps so that a lost attempt can run again.
|
|
3
|
+
*
|
|
4
|
+
* Uru runs a lost attempt again from its start, under the same job run id
|
|
5
|
+
* (`URU_JOB_RUN_ID`) and with the last saved checkpoint. Two things make that
|
|
6
|
+
* second run safe:
|
|
7
|
+
*
|
|
8
|
+
* 1. **Saved steps.** `jobs.step(name, run)` saves each step's result in the
|
|
9
|
+
* job checkpoint. The next attempt returns the saved result and does not
|
|
10
|
+
* run the step again. A step that was cut short runs again from its start.
|
|
11
|
+
* 2. **Keys the run owns.** Inside a step, every call that takes a default
|
|
12
|
+
* key gets `uru-job:<run id>:<digest>`. The digest names the step, the
|
|
13
|
+
* kind of call, the capability or Dataset, and the call's place in that
|
|
14
|
+
* order. It never names the attempt. So a step that runs again sends the
|
|
15
|
+
* same keys in the same order, and the server answers each call from its
|
|
16
|
+
* first run instead of running it twice. The server trusts only keys that
|
|
17
|
+
* carry the run id: those calls do not end the job's automatic retry.
|
|
18
|
+
*
|
|
19
|
+
* Outside a step, a call takes a random key. The next attempt may not make
|
|
20
|
+
* the same calls there: a job that resumes from its own checkpoint skips the
|
|
21
|
+
* calls before it, so a place in order would name another call's write. A
|
|
22
|
+
* random key ends the job's automatic retry before the write is sent.
|
|
23
|
+
*
|
|
24
|
+
* INTERNAL. Nothing here is re-exported by `index.ts`.
|
|
25
|
+
*/
|
|
26
|
+
import type { RuntimeJsonObject } from "./transport-json.js";
|
|
27
|
+
import type { UruAppRuntimeCapabilityType, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment } from "./types.js";
|
|
28
|
+
/** The calls that take a default idempotency key. */
|
|
29
|
+
export type KeyedCall = Exclude<UruAppRuntimeCapabilityType, "query"> | "dataset" | "dataset-sql";
|
|
30
|
+
/** Where a call's default idempotency key comes from. */
|
|
31
|
+
export interface CallKeys {
|
|
32
|
+
/**
|
|
33
|
+
* The key for one call. The caller asks once, synchronously, as the call
|
|
34
|
+
* starts, so concurrent calls take their places in the order the code made
|
|
35
|
+
* them.
|
|
36
|
+
*/
|
|
37
|
+
next(call: KeyedCall, name: string): string;
|
|
38
|
+
}
|
|
39
|
+
/** Outside a job: each call is its own operation, under a random key. */
|
|
40
|
+
export declare const RANDOM_CALL_KEYS: CallKeys;
|
|
41
|
+
/** The checkpoint key that holds saved step results. Gem data may not use it. */
|
|
42
|
+
export declare const JOB_STEPS_CHECKPOINT_KEY = "$uruSteps";
|
|
43
|
+
/** One saved step: `{}` when it returned nothing, else `{ value }`. */
|
|
44
|
+
type SavedStep = RuntimeJsonObject;
|
|
45
|
+
/** The state one job attempt shares across every server context it builds. */
|
|
46
|
+
export interface JobAttempt {
|
|
47
|
+
readonly runId: string;
|
|
48
|
+
/** How many keys each (step, call, name) has handed out in this attempt. */
|
|
49
|
+
readonly places: Map<string, number>;
|
|
50
|
+
/** Checkpoint data the Gem saved itself, without the step results. */
|
|
51
|
+
checkpoint: RuntimeJsonObject;
|
|
52
|
+
steps: Record<string, SavedStep>;
|
|
53
|
+
/** The step that is running. Calls made meanwhile take places in it. */
|
|
54
|
+
activeStep: string | null;
|
|
55
|
+
/** Step names this attempt used. A name runs once per job run. */
|
|
56
|
+
readonly usedSteps: Set<string>;
|
|
57
|
+
/** Each checkpoint send waits for the one before, so the newest lands last. */
|
|
58
|
+
lastSave: Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The keys a job attempt derives from its run id: a run-owned key inside a
|
|
62
|
+
* step, a random key outside one (see the module comment).
|
|
63
|
+
*/
|
|
64
|
+
export declare const jobCallKeys: (attempt: JobAttempt) => CallKeys;
|
|
65
|
+
/** The job attempt this environment runs, or null outside a program job. */
|
|
66
|
+
export declare const jobAttemptFor: (env: UruProviderRuntimeEnvironment) => JobAttempt | null;
|
|
67
|
+
/**
|
|
68
|
+
* Send the newest checkpoint after any send still in flight, so an older body
|
|
69
|
+
* never lands last. A failed send does not stop the next one.
|
|
70
|
+
*/
|
|
71
|
+
export declare const saveJobCheckpoint: (attempt: JobAttempt, send: (body: string) => Promise<void>) => Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* Replace the Gem's own checkpoint data. Saved steps stay.
|
|
74
|
+
*
|
|
75
|
+
* The handler's `checkpoint` argument holds the saved steps under
|
|
76
|
+
* {@link JOB_STEPS_CHECKPOINT_KEY}, so a Gem that saves a changed copy of it
|
|
77
|
+
* passes them back. Those are this job's own steps, so the steps the attempt
|
|
78
|
+
* holds replace them. A checkpoint is saved between steps: a step that runs
|
|
79
|
+
* again starts from its beginning, so resume data saved inside it would skip
|
|
80
|
+
* calls whose keys the step's first run already used.
|
|
81
|
+
*/
|
|
82
|
+
export declare const setJobCheckpoint: (attempt: JobAttempt, value: RuntimeJsonObject) => void;
|
|
83
|
+
/**
|
|
84
|
+
* Run one named step once per job run, and save its result.
|
|
85
|
+
*
|
|
86
|
+
* A step saved by an earlier attempt returns its saved result without
|
|
87
|
+
* running. Steps run one at a time; each name runs once per job run.
|
|
88
|
+
*/
|
|
89
|
+
export declare const runJobStep: <T extends UruJobStepResult>(attempt: JobAttempt, rawName: string, run: (step: UruJobStep) => Promise<T> | T, save: () => Promise<void>) => Promise<T>;
|
|
90
|
+
export {};
|
package/dist/job-run.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one program-job attempt keeps so that a lost attempt can run again.
|
|
3
|
+
*
|
|
4
|
+
* Uru runs a lost attempt again from its start, under the same job run id
|
|
5
|
+
* (`URU_JOB_RUN_ID`) and with the last saved checkpoint. Two things make that
|
|
6
|
+
* second run safe:
|
|
7
|
+
*
|
|
8
|
+
* 1. **Saved steps.** `jobs.step(name, run)` saves each step's result in the
|
|
9
|
+
* job checkpoint. The next attempt returns the saved result and does not
|
|
10
|
+
* run the step again. A step that was cut short runs again from its start.
|
|
11
|
+
* 2. **Keys the run owns.** Inside a step, every call that takes a default
|
|
12
|
+
* key gets `uru-job:<run id>:<digest>`. The digest names the step, the
|
|
13
|
+
* kind of call, the capability or Dataset, and the call's place in that
|
|
14
|
+
* order. It never names the attempt. So a step that runs again sends the
|
|
15
|
+
* same keys in the same order, and the server answers each call from its
|
|
16
|
+
* first run instead of running it twice. The server trusts only keys that
|
|
17
|
+
* carry the run id: those calls do not end the job's automatic retry.
|
|
18
|
+
*
|
|
19
|
+
* Outside a step, a call takes a random key. The next attempt may not make
|
|
20
|
+
* the same calls there: a job that resumes from its own checkpoint skips the
|
|
21
|
+
* calls before it, so a place in order would name another call's write. A
|
|
22
|
+
* random key ends the job's automatic retry before the write is sent.
|
|
23
|
+
*
|
|
24
|
+
* INTERNAL. Nothing here is re-exported by `index.ts`.
|
|
25
|
+
*/
|
|
26
|
+
import { UruAppRuntimeError } from "./errors.js";
|
|
27
|
+
import { isRuntimeJsonObject } from "./transport-json.js";
|
|
28
|
+
const RANDOM_KEY_PREFIX = {
|
|
29
|
+
action: "uru-app:",
|
|
30
|
+
"dataset-sql": "uru-dataset-sql:",
|
|
31
|
+
dataset: "uru-dataset:",
|
|
32
|
+
endpoint: "uru-app:",
|
|
33
|
+
job: "uru-app:",
|
|
34
|
+
server_function: "uru-app:",
|
|
35
|
+
};
|
|
36
|
+
/** Outside a job: each call is its own operation, under a random key. */
|
|
37
|
+
export const RANDOM_CALL_KEYS = {
|
|
38
|
+
next: call => `${RANDOM_KEY_PREFIX[call]}${crypto.randomUUID()}`,
|
|
39
|
+
};
|
|
40
|
+
/** The checkpoint key that holds saved step results. Gem data may not use it. */
|
|
41
|
+
export const JOB_STEPS_CHECKPOINT_KEY = "$uruSteps";
|
|
42
|
+
/** A progress or checkpoint callback body larger than this is refused. */
|
|
43
|
+
const MAX_JOB_CALLBACK_BODY_BYTES = 65_536;
|
|
44
|
+
const FNV_128_OFFSET = 0x6c62272e07bb014262b821756295c58dn;
|
|
45
|
+
const FNV_128_PRIME = 0x0000000001000000000000000000013bn;
|
|
46
|
+
const MASK_128 = (1n << 128n) - 1n;
|
|
47
|
+
/**
|
|
48
|
+
* FNV-1a, 128 bits, as 32 hex digits. A compact, stable name for a call, the
|
|
49
|
+
* same in every runtime and without an await: not a secret and not a proof.
|
|
50
|
+
* The run id in front of it is what binds the key to the run.
|
|
51
|
+
*/
|
|
52
|
+
const digest128 = (text) => {
|
|
53
|
+
let hash = FNV_128_OFFSET;
|
|
54
|
+
for (const byte of new TextEncoder().encode(text)) {
|
|
55
|
+
hash = ((hash ^ BigInt(byte)) * FNV_128_PRIME) & MASK_128;
|
|
56
|
+
}
|
|
57
|
+
return hash.toString(16).padStart(32, "0");
|
|
58
|
+
};
|
|
59
|
+
/** Length-prefix each part, so no two different calls share one text. */
|
|
60
|
+
const runKey = (runId, parts) => `uru-job:${runId}:${digest128(parts.map(part => `${part.length}:${part}`).join("|"))}`;
|
|
61
|
+
/** The key of one step itself, for the step's own external write. */
|
|
62
|
+
const stepKey = (runId, step) => runKey(runId, ["step", step]);
|
|
63
|
+
const ownValue = (env, key) => {
|
|
64
|
+
if (!Object.hasOwn(env, key)) {
|
|
65
|
+
return "";
|
|
66
|
+
}
|
|
67
|
+
const value = env[key];
|
|
68
|
+
return typeof value === "string" ? value.trim() : "";
|
|
69
|
+
};
|
|
70
|
+
/** Read saved step results. A malformed record is left out: that step runs again. */
|
|
71
|
+
const savedSteps = (value) => isRuntimeJsonObject(value)
|
|
72
|
+
? Object.fromEntries(Object.entries(value).filter((entry) => isRuntimeJsonObject(entry[1])))
|
|
73
|
+
: {};
|
|
74
|
+
/**
|
|
75
|
+
* The checkpoint a new attempt starts from. The runner already refused a
|
|
76
|
+
* malformed one before it loaded the Gem, so anything else starts empty.
|
|
77
|
+
*/
|
|
78
|
+
const savedCheckpoint = (raw) => {
|
|
79
|
+
let parsed = null;
|
|
80
|
+
try {
|
|
81
|
+
parsed = raw === "" ? null : JSON.parse(raw);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
parsed = null;
|
|
85
|
+
}
|
|
86
|
+
if (!isRuntimeJsonObject(parsed)) {
|
|
87
|
+
return { checkpoint: {}, steps: {} };
|
|
88
|
+
}
|
|
89
|
+
// `fromEntries` defines each key as data, so a saved `__proto__` stays data.
|
|
90
|
+
const checkpoint = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== JOB_STEPS_CHECKPOINT_KEY));
|
|
91
|
+
return { checkpoint, steps: savedSteps(parsed[JOB_STEPS_CHECKPOINT_KEY]) };
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The keys a job attempt derives from its run id: a run-owned key inside a
|
|
95
|
+
* step, a random key outside one (see the module comment).
|
|
96
|
+
*/
|
|
97
|
+
export const jobCallKeys = (attempt) => ({
|
|
98
|
+
next: (call, name) => {
|
|
99
|
+
const step = attempt.activeStep;
|
|
100
|
+
if (step === null) {
|
|
101
|
+
return RANDOM_CALL_KEYS.next(call, name);
|
|
102
|
+
}
|
|
103
|
+
const counter = `${step.length}:${step}|${call}|${name}`;
|
|
104
|
+
const place = attempt.places.get(counter) ?? 0;
|
|
105
|
+
attempt.places.set(counter, place + 1);
|
|
106
|
+
return runKey(attempt.runId, ["call", step, call, name, String(place)]);
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
/**
|
|
110
|
+
* One state per attempt, shared by every server context the attempt builds,
|
|
111
|
+
* so a second context never reuses a key of the first.
|
|
112
|
+
*/
|
|
113
|
+
const attempts = new Map();
|
|
114
|
+
/** The job attempt this environment runs, or null outside a program job. */
|
|
115
|
+
export const jobAttemptFor = (env) => {
|
|
116
|
+
const runId = ownValue(env, "URU_JOB_RUN_ID");
|
|
117
|
+
const attemptId = ownValue(env, "URU_JOB_ATTEMPT_ID");
|
|
118
|
+
if (runId === "" || attemptId === "") {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
const id = `${runId}\n${attemptId}`;
|
|
122
|
+
const existing = attempts.get(id);
|
|
123
|
+
if (existing !== undefined) {
|
|
124
|
+
return existing;
|
|
125
|
+
}
|
|
126
|
+
const saved = savedCheckpoint(ownValue(env, "URU_JOB_CHECKPOINT"));
|
|
127
|
+
const attempt = {
|
|
128
|
+
activeStep: null,
|
|
129
|
+
checkpoint: saved.checkpoint,
|
|
130
|
+
lastSave: Promise.resolve(),
|
|
131
|
+
places: new Map(),
|
|
132
|
+
runId,
|
|
133
|
+
steps: saved.steps,
|
|
134
|
+
usedSteps: new Set(),
|
|
135
|
+
};
|
|
136
|
+
attempts.set(id, attempt);
|
|
137
|
+
return attempt;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* The checkpoint body to send: the Gem's own data plus the saved steps. It
|
|
141
|
+
* throws when the body is too large, so callers check a new value here before
|
|
142
|
+
* they keep it: a value that can never be sent must not block later saves.
|
|
143
|
+
*/
|
|
144
|
+
const checkpointBodyOf = (checkpoint, steps) => {
|
|
145
|
+
const value = Object.keys(steps).length === 0
|
|
146
|
+
? checkpoint
|
|
147
|
+
: { ...checkpoint, [JOB_STEPS_CHECKPOINT_KEY]: steps };
|
|
148
|
+
const body = JSON.stringify({ value });
|
|
149
|
+
if (new TextEncoder().encode(body).byteLength > MAX_JOB_CALLBACK_BODY_BYTES) {
|
|
150
|
+
throw new UruAppRuntimeError("A job checkpoint, with its saved step results, must stay under 64 KB. " +
|
|
151
|
+
"Return ids and counts from a step, not rows or files.", { body: null, status: 0 });
|
|
152
|
+
}
|
|
153
|
+
return body;
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Send the newest checkpoint after any send still in flight, so an older body
|
|
157
|
+
* never lands last. A failed send does not stop the next one.
|
|
158
|
+
*/
|
|
159
|
+
export const saveJobCheckpoint = (attempt, send) => {
|
|
160
|
+
const save = async () => {
|
|
161
|
+
await send(checkpointBodyOf(attempt.checkpoint, attempt.steps));
|
|
162
|
+
};
|
|
163
|
+
const saved = attempt.lastSave.then(save, save);
|
|
164
|
+
attempt.lastSave = saved.then(() => undefined, () => undefined);
|
|
165
|
+
return saved;
|
|
166
|
+
};
|
|
167
|
+
const stepError = (message) => new UruAppRuntimeError(message, { body: null, status: 0 });
|
|
168
|
+
/**
|
|
169
|
+
* Replace the Gem's own checkpoint data. Saved steps stay.
|
|
170
|
+
*
|
|
171
|
+
* The handler's `checkpoint` argument holds the saved steps under
|
|
172
|
+
* {@link JOB_STEPS_CHECKPOINT_KEY}, so a Gem that saves a changed copy of it
|
|
173
|
+
* passes them back. Those are this job's own steps, so the steps the attempt
|
|
174
|
+
* holds replace them. A checkpoint is saved between steps: a step that runs
|
|
175
|
+
* again starts from its beginning, so resume data saved inside it would skip
|
|
176
|
+
* calls whose keys the step's first run already used.
|
|
177
|
+
*/
|
|
178
|
+
export const setJobCheckpoint = (attempt, value) => {
|
|
179
|
+
if (attempt.activeStep !== null) {
|
|
180
|
+
throw stepError(`Save a job checkpoint between steps, not inside "${attempt.activeStep}": ` +
|
|
181
|
+
"a step that runs again starts from its beginning.");
|
|
182
|
+
}
|
|
183
|
+
// `fromEntries` defines each key as data, so a saved `__proto__` stays data.
|
|
184
|
+
const checkpoint = Object.fromEntries(Object.entries(value).filter(([key]) => key !== JOB_STEPS_CHECKPOINT_KEY));
|
|
185
|
+
checkpointBodyOf(checkpoint, attempt.steps);
|
|
186
|
+
attempt.checkpoint = checkpoint;
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* Run one named step once per job run, and save its result.
|
|
190
|
+
*
|
|
191
|
+
* A step saved by an earlier attempt returns its saved result without
|
|
192
|
+
* running. Steps run one at a time; each name runs once per job run.
|
|
193
|
+
*/
|
|
194
|
+
export const runJobStep = async (attempt, rawName, run, save) => {
|
|
195
|
+
const name = typeof rawName === "string" ? rawName.trim() : "";
|
|
196
|
+
if (name === "" || name.length > 200) {
|
|
197
|
+
throw stepError("A job step needs a name of 1 to 200 characters.");
|
|
198
|
+
}
|
|
199
|
+
if (attempt.activeStep !== null) {
|
|
200
|
+
throw stepError(`Job steps run one at a time: "${name}" started while "${attempt.activeStep}" runs.`);
|
|
201
|
+
}
|
|
202
|
+
if (attempt.usedSteps.has(name)) {
|
|
203
|
+
throw stepError(`Each job step needs its own name: "${name}" already ran.`);
|
|
204
|
+
}
|
|
205
|
+
attempt.usedSteps.add(name);
|
|
206
|
+
const saved = attempt.steps[name];
|
|
207
|
+
if (saved !== undefined) {
|
|
208
|
+
// The value this step returned in an earlier attempt of the same run,
|
|
209
|
+
// read back from JSON. The same code returned it, so it has type T.
|
|
210
|
+
return saved["value"];
|
|
211
|
+
}
|
|
212
|
+
attempt.activeStep = name;
|
|
213
|
+
let value;
|
|
214
|
+
try {
|
|
215
|
+
value = await run({ idempotencyKey: stepKey(attempt.runId, name), name });
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
attempt.activeStep = null;
|
|
219
|
+
}
|
|
220
|
+
const record = value === undefined ? {} : { value };
|
|
221
|
+
if (!isRuntimeJsonObject(record)) {
|
|
222
|
+
throw stepError(`Job step "${name}" must return JSON data or nothing.`);
|
|
223
|
+
}
|
|
224
|
+
const steps = { ...attempt.steps, [name]: record };
|
|
225
|
+
checkpointBodyOf(attempt.checkpoint, steps);
|
|
226
|
+
attempt.steps = steps;
|
|
227
|
+
await save();
|
|
228
|
+
return value;
|
|
229
|
+
};
|
package/dist/jobs.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment } from './types.js';
|
|
1
|
+
import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment, UruServerContext } from './types.js';
|
|
3
2
|
export declare const createJobProgress: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (progress: UruJobProgress) => Promise<void>;
|
|
4
|
-
export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) =>
|
|
3
|
+
export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => UruServerContext['jobs']['checkpoint'];
|
|
4
|
+
export declare const createJobStep: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => UruServerContext['jobs']['step'];
|
package/dist/jobs.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { resolveDamperConfig } from './dampers.js';
|
|
1
2
|
import { UruAppRuntimeError } from './errors.js';
|
|
3
|
+
import { jobAttemptFor, runJobStep, saveJobCheckpoint, setJobCheckpoint } from './job-run.js';
|
|
2
4
|
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash } from './runtime.js';
|
|
5
|
+
import { postWithResends } from './transport-retry.js';
|
|
3
6
|
import { isRuntimeJsonObject } from './transport-json.js';
|
|
4
|
-
const postJobUpdate = async (options, env, operation,
|
|
7
|
+
const postJobUpdate = async (options, env, operation, body) => {
|
|
5
8
|
const runId = Object.hasOwn(env, 'URU_JOB_RUN_ID') ? env['URU_JOB_RUN_ID']?.trim() : undefined;
|
|
6
9
|
const attemptId = Object.hasOwn(env, 'URU_JOB_ATTEMPT_ID') ? env['URU_JOB_ATTEMPT_ID']?.trim() : undefined;
|
|
7
10
|
if (!runId || !attemptId) {
|
|
@@ -10,26 +13,51 @@ const postJobUpdate = async (options, env, operation, payload) => {
|
|
|
10
13
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
11
14
|
headers.set('content-type', 'application/json');
|
|
12
15
|
const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
|
|
13
|
-
|
|
14
|
-
|
|
16
|
+
// Progress and a checkpoint replace the attempt's saved value, so the same
|
|
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 { response } = await postWithResends({
|
|
22
|
+
body,
|
|
23
|
+
config: resolveDamperConfig(options.dampers),
|
|
24
|
+
headers,
|
|
25
|
+
repeatable: true,
|
|
26
|
+
runtimeFetch: resolveRuntimeFetch(options),
|
|
27
|
+
sendTimeoutMs: 30_000,
|
|
28
|
+
url,
|
|
15
29
|
});
|
|
16
30
|
if (!response.ok) {
|
|
17
|
-
await response.body?.cancel();
|
|
18
31
|
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
|
|
19
32
|
}
|
|
20
|
-
await response.body?.cancel();
|
|
21
33
|
};
|
|
34
|
+
const noJobAttempt = () => new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
|
|
22
35
|
export const createJobProgress = (options, env) => async (progress) => {
|
|
23
36
|
if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
|
|
24
37
|
(progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
|
|
25
38
|
(progress.message !== undefined && typeof progress.message !== 'string')) {
|
|
26
39
|
throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
|
|
27
40
|
}
|
|
28
|
-
await postJobUpdate(options, env, 'progress', progress);
|
|
41
|
+
await postJobUpdate(options, env, 'progress', JSON.stringify(progress));
|
|
29
42
|
};
|
|
30
|
-
export const createJobCheckpoint = (options, env) =>
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
43
|
+
export const createJobCheckpoint = (options, env) => {
|
|
44
|
+
const attempt = jobAttemptFor(env);
|
|
45
|
+
return async (value) => {
|
|
46
|
+
if (!isRuntimeJsonObject(value)) {
|
|
47
|
+
throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
|
|
48
|
+
}
|
|
49
|
+
if (attempt === null)
|
|
50
|
+
throw noJobAttempt();
|
|
51
|
+
setJobCheckpoint(attempt, value);
|
|
52
|
+
await saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body));
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
export const createJobStep = (options, env) => {
|
|
56
|
+
const attempt = jobAttemptFor(env);
|
|
57
|
+
return async (name, run) => {
|
|
58
|
+
if (attempt === null) {
|
|
59
|
+
throw new UruAppRuntimeError('Job steps require an active job attempt.', { status: 0, body: null });
|
|
60
|
+
}
|
|
61
|
+
return await runJobStep(attempt, name, run, () => saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body)));
|
|
62
|
+
};
|
|
35
63
|
};
|
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
|
*
|
|
@@ -5,4 +5,3 @@ export declare const withRuntimeRequestSignal: <T>(options: UruAppRuntimeInvocat
|
|
|
5
5
|
export declare const abortReason: (signal: AbortSignal) => unknown;
|
|
6
6
|
/** Race a fetch, body read, or retry wait against the same request signal. */
|
|
7
7
|
export declare const awaitWithAbort: <T>(promise: Promise<T>, signal: AbortSignal | undefined) => Promise<T>;
|
|
8
|
-
export declare const readRuntimeResponseBody: (response: Response, signal?: AbortSignal) => Promise<unknown>;
|
|
@@ -22,7 +22,6 @@ export const validateRuntimeInvocationOptions = (options) => {
|
|
|
22
22
|
assertRuntimeTimeout(options.timeoutMs);
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
const runtimeSignalIsAborted = (signal) => signal?.aborted === true;
|
|
26
25
|
/**
|
|
27
26
|
* Make one deadline for the whole network operation. The regular timer keeps
|
|
28
27
|
* the deadline live even when the caller has no other active event-loop work.
|
|
@@ -79,29 +78,3 @@ export const awaitWithAbort = async (promise, signal) => {
|
|
|
79
78
|
});
|
|
80
79
|
});
|
|
81
80
|
};
|
|
82
|
-
export const readRuntimeResponseBody = async (response, signal) => {
|
|
83
|
-
if (runtimeSignalIsAborted(signal)) {
|
|
84
|
-
void response.body?.cancel().catch(() => undefined);
|
|
85
|
-
throw abortReason(signal);
|
|
86
|
-
}
|
|
87
|
-
const parsed = Promise.resolve()
|
|
88
|
-
.then(() => {
|
|
89
|
-
if (runtimeSignalIsAborted(signal))
|
|
90
|
-
throw abortReason(signal);
|
|
91
|
-
return response.json();
|
|
92
|
-
})
|
|
93
|
-
.catch(() => {
|
|
94
|
-
if (runtimeSignalIsAborted(signal))
|
|
95
|
-
throw abortReason(signal);
|
|
96
|
-
return null;
|
|
97
|
-
});
|
|
98
|
-
try {
|
|
99
|
-
return await awaitWithAbort(parsed, signal);
|
|
100
|
-
}
|
|
101
|
-
catch (error) {
|
|
102
|
-
if (runtimeSignalIsAborted(signal)) {
|
|
103
|
-
void response.body?.cancel().catch(() => undefined);
|
|
104
|
-
}
|
|
105
|
-
throw error;
|
|
106
|
-
}
|
|
107
|
-
};
|
|
@@ -8,8 +8,11 @@ export interface InvocationFetchArguments {
|
|
|
8
8
|
deploymentId: string;
|
|
9
9
|
emit: (event: UruAppRuntimeEvent) => void;
|
|
10
10
|
headers: Headers;
|
|
11
|
-
|
|
11
|
+
/** The body for one send; `resend` counts the sends before it. */
|
|
12
|
+
requestBody: (resend: number) => string;
|
|
12
13
|
requestId: string;
|
|
14
|
+
/** Whether a lost response may be sent again. */
|
|
15
|
+
resendLost: boolean;
|
|
13
16
|
runtimeFetch: RuntimeFetch;
|
|
14
17
|
signal?: AbortSignal;
|
|
15
18
|
url: string;
|
|
@@ -18,7 +21,12 @@ export interface RuntimeFetchResult {
|
|
|
18
21
|
body: unknown;
|
|
19
22
|
response: Response;
|
|
20
23
|
}
|
|
21
|
-
|
|
24
|
+
interface SendCounts {
|
|
25
|
+
readonly rateLimited: number;
|
|
26
|
+
readonly resent: number;
|
|
27
|
+
}
|
|
28
|
+
export declare const fetchInvocation: (args: InvocationFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
|
|
29
|
+
/** One job execution call: a status read or a cancel. */
|
|
22
30
|
export interface JobStatusFetchArguments {
|
|
23
31
|
damper: DamperRuntime;
|
|
24
32
|
deploymentId: string;
|
|
@@ -30,5 +38,16 @@ export interface JobStatusFetchArguments {
|
|
|
30
38
|
signal?: AbortSignal;
|
|
31
39
|
url: string;
|
|
32
40
|
}
|
|
33
|
-
/**
|
|
34
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Fetch one accepted execution's status with bounded, same-identity retries.
|
|
43
|
+
* A status read changes nothing, so a lost response is always read again.
|
|
44
|
+
*/
|
|
45
|
+
export declare const fetchJobStatus: (args: JobStatusFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
|
|
46
|
+
/**
|
|
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. The route
|
|
49
|
+
* takes no body, but the job gateway accepts only a JSON POST, so the cancel
|
|
50
|
+
* sends an empty JSON object.
|
|
51
|
+
*/
|
|
52
|
+
export declare const fetchJobCancel: (args: JobStatusFetchArguments, resent?: number) => Promise<RuntimeFetchResult>;
|
|
53
|
+
export {};
|