@uru-intelligence/app 2.1.5 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -12
- package/dist/background-jobs.d.ts +7 -0
- package/dist/background-jobs.js +576 -0
- package/dist/dampers.d.ts +30 -1
- package/dist/dampers.js +118 -17
- 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 +81 -28
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +191 -0
- package/dist/files.js +4 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +21 -8
- package/dist/invocations.d.ts +2 -2
- package/dist/invocations.js +4 -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 +37 -11
- package/dist/transport-deadline.d.ts +0 -1
- package/dist/transport-deadline.js +0 -27
- package/dist/transport-invocation.d.ts +32 -2
- package/dist/transport-invocation.js +143 -17
- package/dist/transport-retry.d.ts +57 -0
- package/dist/transport-retry.js +154 -0
- package/dist/transport.d.ts +5 -2
- package/dist/transport.js +80 -156
- package/dist/types.d.ts +183 -3
- package/package.json +3 -3
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, 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,19 +78,22 @@ 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
|
-
jobStatus: createJobStatusInvoker(options),
|
|
96
|
+
jobStatus: createJobStatusInvoker(options, damper),
|
|
90
97
|
query: createCapabilityInvoker(options, damper, "query"),
|
|
91
98
|
serverFunction: createCapabilityInvoker(options, damper, "server_function"),
|
|
92
99
|
};
|
|
@@ -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
|
@@ -2,6 +2,6 @@ import type { DamperRuntime } from "./transport.js";
|
|
|
2
2
|
import type { CreateUruAppRuntimeClientOptions, UruActionInvoker, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruCapabilityInvoker, UruCancelJobInvoker, UruJobStatusInvoker } from "./types.js";
|
|
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
|
-
export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions) => UruJobStatusInvoker;
|
|
6
|
-
export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions) => UruCancelJobInvoker;
|
|
5
|
+
export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime) => UruJobStatusInvoker;
|
|
6
|
+
export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime) => UruCancelJobInvoker;
|
|
7
7
|
export declare const createActionInvoker: (app: UruAppRuntimeClient) => UruActionInvoker;
|
package/dist/invocations.js
CHANGED
|
@@ -7,15 +7,15 @@ export const createCapabilityInvoker = (options, damper, capabilityType) => {
|
|
|
7
7
|
}
|
|
8
8
|
return invoke;
|
|
9
9
|
};
|
|
10
|
-
export const createJobStatusInvoker = (options) => {
|
|
10
|
+
export const createJobStatusInvoker = (options, damper) => {
|
|
11
11
|
async function status(executionId, invocationOptions) {
|
|
12
|
-
return await getAppRuntimeJobStatus(options, executionId, invocationOptions);
|
|
12
|
+
return await getAppRuntimeJobStatus(options, executionId, invocationOptions, damper);
|
|
13
13
|
}
|
|
14
14
|
return status;
|
|
15
15
|
};
|
|
16
|
-
export const createCancelJobInvoker = (options) => {
|
|
16
|
+
export const createCancelJobInvoker = (options, damper) => {
|
|
17
17
|
async function cancel(executionId, invocationOptions) {
|
|
18
|
-
return await cancelAppRuntimeJob(options, executionId, invocationOptions);
|
|
18
|
+
return await cancelAppRuntimeJob(options, executionId, invocationOptions, damper);
|
|
19
19
|
}
|
|
20
20
|
return cancel;
|
|
21
21
|
};
|
|
@@ -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,49 @@ 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 always safe to send again after a restarting server. Each one also
|
|
18
|
+
// keeps the attempt's lease: it proves the job is alive.
|
|
19
|
+
const { response } = await postWithResends({
|
|
20
|
+
body,
|
|
21
|
+
config: resolveDamperConfig(options.dampers),
|
|
22
|
+
headers,
|
|
23
|
+
resendLost: true,
|
|
24
|
+
runtimeFetch: resolveRuntimeFetch(options),
|
|
25
|
+
sendTimeoutMs: 30_000,
|
|
26
|
+
url,
|
|
15
27
|
});
|
|
16
28
|
if (!response.ok) {
|
|
17
|
-
await response.body?.cancel();
|
|
18
29
|
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
|
|
19
30
|
}
|
|
20
|
-
await response.body?.cancel();
|
|
21
31
|
};
|
|
32
|
+
const noJobAttempt = () => new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
|
|
22
33
|
export const createJobProgress = (options, env) => async (progress) => {
|
|
23
34
|
if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
|
|
24
35
|
(progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
|
|
25
36
|
(progress.message !== undefined && typeof progress.message !== 'string')) {
|
|
26
37
|
throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
|
|
27
38
|
}
|
|
28
|
-
await postJobUpdate(options, env, 'progress', progress);
|
|
39
|
+
await postJobUpdate(options, env, 'progress', JSON.stringify(progress));
|
|
29
40
|
};
|
|
30
|
-
export const createJobCheckpoint = (options, env) =>
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
41
|
+
export const createJobCheckpoint = (options, env) => {
|
|
42
|
+
const attempt = jobAttemptFor(env);
|
|
43
|
+
return async (value) => {
|
|
44
|
+
if (!isRuntimeJsonObject(value)) {
|
|
45
|
+
throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
|
|
46
|
+
}
|
|
47
|
+
if (attempt === null)
|
|
48
|
+
throw noJobAttempt();
|
|
49
|
+
setJobCheckpoint(attempt, value);
|
|
50
|
+
await saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body));
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
export const createJobStep = (options, env) => {
|
|
54
|
+
const attempt = jobAttemptFor(env);
|
|
55
|
+
return async (name, run) => {
|
|
56
|
+
if (attempt === null) {
|
|
57
|
+
throw new UruAppRuntimeError('Job steps require an active job attempt.', { status: 0, body: null });
|
|
58
|
+
}
|
|
59
|
+
return await runJobStep(attempt, name, run, () => saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body)));
|
|
60
|
+
};
|
|
35
61
|
};
|
|
@@ -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,4 +21,31 @@ 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. */
|
|
30
|
+
export interface JobStatusFetchArguments {
|
|
31
|
+
damper: DamperRuntime;
|
|
32
|
+
deploymentId: string;
|
|
33
|
+
emit: (event: UruAppRuntimeEvent) => void;
|
|
34
|
+
executionId: string;
|
|
35
|
+
headers: Headers;
|
|
36
|
+
requestId: string;
|
|
37
|
+
runtimeFetch: RuntimeFetch;
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
url: string;
|
|
40
|
+
}
|
|
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.
|
|
49
|
+
*/
|
|
50
|
+
export declare const fetchJobCancel: (args: JobStatusFetchArguments, resent?: number) => Promise<RuntimeFetchResult>;
|
|
51
|
+
export {};
|