@uru-intelligence/app 2.1.6 → 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 +17 -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 +81 -28
- package/dist/errors.js +1 -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 +1 -1
- package/dist/invocations.js +2 -2
- 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 +21 -4
- package/dist/transport-invocation.js +110 -29
- package/dist/transport-retry.d.ts +57 -0
- package/dist/transport-retry.js +154 -0
- package/dist/transport.d.ts +4 -1
- package/dist/transport.js +53 -32
- package/dist/types.d.ts +183 -3
- package/package.json +3 -3
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert a native Dataset row view into a lossless row update.
|
|
3
|
+
*
|
|
4
|
+
* Keep row identity separate from customer fields. A flat row cannot represent
|
|
5
|
+
* a customer field named `id` because that key names the row in an upsert.
|
|
6
|
+
*/
|
|
7
|
+
export const datasetRowForMutation = (row) => ({
|
|
8
|
+
expectedRowVersion: row.rowVersion ?? null,
|
|
9
|
+
fields: { ...row.fields },
|
|
10
|
+
rowId: row.id,
|
|
11
|
+
});
|
package/dist/datasets.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* The HTTP boundary lives in `dataset-boundary.ts` so this module only assembles
|
|
7
7
|
* the current Dataset request paths and overloads.
|
|
8
8
|
*/
|
|
9
|
+
import type { CallKeys } from "./job-run.js";
|
|
9
10
|
import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeClient, UruDatasetsContext } from "./types.js";
|
|
10
11
|
/** Build the Dataset surface hung off a server context. */
|
|
11
|
-
export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions) => UruDatasetsContext;
|
|
12
|
+
export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions, keys?: CallKeys) => UruDatasetsContext;
|
package/dist/datasets.js
CHANGED
|
@@ -7,9 +7,12 @@
|
|
|
7
7
|
* the current Dataset request paths and overloads.
|
|
8
8
|
*/
|
|
9
9
|
import { datasetIdsForRequest, datasetRowIdsForRequest, datasetRowsForRequest, decodeDatasetMutationResult, decodeDatasetRowsResult, decodeDefaultDatasetMutationResult, decodeDefaultDatasetRowsResult, datasetWriteErrorMessage, serializeDatasetRequest, } from "./dataset-boundary.js";
|
|
10
|
+
import { resolveDamperConfig } from "./dampers.js";
|
|
10
11
|
import { UruAppRuntimeError } from "./errors.js";
|
|
12
|
+
import { RANDOM_CALL_KEYS } from "./job-run.js";
|
|
11
13
|
import { requireCompletedRuntimeResponse, resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
12
|
-
|
|
14
|
+
import { postWithResends } from "./transport-retry.js";
|
|
15
|
+
const fetchDatasetWrite = async (options, subpath, body, send) => {
|
|
13
16
|
const runtimeFetch = resolveRuntimeFetch(options);
|
|
14
17
|
const deploymentId = typeof options.deploymentId === "string" ? options.deploymentId.trim() : "";
|
|
15
18
|
if (!deploymentId) {
|
|
@@ -25,13 +28,15 @@ const fetchDatasetWrite = async (options, subpath, body) => {
|
|
|
25
28
|
const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${subpath}`;
|
|
26
29
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
27
30
|
headers.set("content-type", "application/json");
|
|
28
|
-
const response = await
|
|
31
|
+
const { body: parsed, response } = await postWithResends({
|
|
29
32
|
body: serializedBody,
|
|
33
|
+
config: send.config,
|
|
30
34
|
headers,
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
resendLost: send.resendLost,
|
|
36
|
+
runtimeFetch,
|
|
37
|
+
sendTimeoutMs: 30_000,
|
|
38
|
+
url,
|
|
33
39
|
});
|
|
34
|
-
const parsed = await response.json().catch(() => null);
|
|
35
40
|
if (!response.ok) {
|
|
36
41
|
const message = datasetWriteErrorMessage(parsed, response.status);
|
|
37
42
|
throw new UruAppRuntimeError(message, {
|
|
@@ -41,8 +46,29 @@ const fetchDatasetWrite = async (options, subpath, body) => {
|
|
|
41
46
|
}
|
|
42
47
|
return parsed;
|
|
43
48
|
};
|
|
44
|
-
const postProviderDatasetWrite = async (options, subpath, body) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body));
|
|
45
|
-
const postProviderDatasetWriteDecoded = async (options, subpath, body, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body), decodeResult);
|
|
49
|
+
const postProviderDatasetWrite = async (options, subpath, body, send) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send));
|
|
50
|
+
const postProviderDatasetWriteDecoded = async (options, subpath, body, send, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send), decodeResult);
|
|
51
|
+
/**
|
|
52
|
+
* One row write's body with its key. Each call gets its own key, and every
|
|
53
|
+
* send of that call carries it, so a resend after a lost response is a replay
|
|
54
|
+
* of the stored command rather than a second write.
|
|
55
|
+
*/
|
|
56
|
+
const keyedMutationBody = (body, mutationOptions, config, keys, datasetRef) => {
|
|
57
|
+
const callerKey = mutationOptions?.idempotencyKey;
|
|
58
|
+
const idempotencyKey = callerKey !== undefined && callerKey !== ""
|
|
59
|
+
? callerKey
|
|
60
|
+
: config.defaultIdempotencyKeys
|
|
61
|
+
? keys.next("dataset", datasetRef.trim())
|
|
62
|
+
: undefined;
|
|
63
|
+
return {
|
|
64
|
+
body: {
|
|
65
|
+
...body,
|
|
66
|
+
...mutationOptions,
|
|
67
|
+
...(idempotencyKey === undefined ? {} : { idempotencyKey }),
|
|
68
|
+
},
|
|
69
|
+
send: { config, resendLost: idempotencyKey !== undefined },
|
|
70
|
+
};
|
|
71
|
+
};
|
|
46
72
|
const datasetMutationPath = (datasetRef) => {
|
|
47
73
|
const slug = datasetRef.trim();
|
|
48
74
|
if (!slug) {
|
|
@@ -61,7 +87,7 @@ const idMutationBody = (operation, rowIds) => ({
|
|
|
61
87
|
operation,
|
|
62
88
|
row_ids: datasetRowIdsForRequest(rowIds),
|
|
63
89
|
});
|
|
64
|
-
const sqlBody = (sql, options) => {
|
|
90
|
+
const sqlBody = (sql, options, config, keys) => {
|
|
65
91
|
if (typeof sql !== "string" || sql.trim() === "") {
|
|
66
92
|
throw new UruAppRuntimeError("SQL statement is required.", {
|
|
67
93
|
body: sql,
|
|
@@ -89,6 +115,14 @@ const sqlBody = (sql, options) => {
|
|
|
89
115
|
if (options.timeoutMs !== undefined) {
|
|
90
116
|
body.timeout_ms = options.timeoutMs;
|
|
91
117
|
}
|
|
118
|
+
const idempotencyKey = options.idempotencyKey !== undefined && options.idempotencyKey !== ""
|
|
119
|
+
? options.idempotencyKey
|
|
120
|
+
: config.defaultIdempotencyKeys
|
|
121
|
+
? keys.next("dataset-sql", "")
|
|
122
|
+
: undefined;
|
|
123
|
+
if (idempotencyKey !== undefined) {
|
|
124
|
+
body.idempotency_key = idempotencyKey;
|
|
125
|
+
}
|
|
92
126
|
return body;
|
|
93
127
|
};
|
|
94
128
|
const createQueryRowsInvoker = (app) => {
|
|
@@ -101,44 +135,63 @@ const createQueryRowsInvoker = (app) => {
|
|
|
101
135
|
}
|
|
102
136
|
return queryRows;
|
|
103
137
|
};
|
|
104
|
-
const createRowMutationInvoker = (options) => {
|
|
138
|
+
const createRowMutationInvoker = (options, config, keys) => {
|
|
105
139
|
async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
|
|
106
|
-
const body = { ...upsertBody(rows), ...mutationOptions };
|
|
107
140
|
const path = datasetMutationPath(datasetRef);
|
|
141
|
+
const { body, send } = keyedMutationBody(upsertBody(rows), mutationOptions, config, keys, datasetRef);
|
|
108
142
|
if (decodeResult === undefined) {
|
|
109
|
-
return await postProviderDatasetWrite(options, path, body);
|
|
143
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
110
144
|
}
|
|
111
|
-
return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
|
|
145
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
112
146
|
}
|
|
113
147
|
return mutate;
|
|
114
148
|
};
|
|
115
|
-
const
|
|
149
|
+
const createRowViewMutationInvoker = (options, config, keys) => {
|
|
150
|
+
async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
|
|
151
|
+
const path = datasetMutationPath(datasetRef);
|
|
152
|
+
const { body, send } = keyedMutationBody({ operation: "upsertFields", rows: datasetRowsForRequest(rows) }, mutationOptions, config, keys, datasetRef);
|
|
153
|
+
if (decodeResult === undefined) {
|
|
154
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
155
|
+
}
|
|
156
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
157
|
+
}
|
|
158
|
+
return mutate;
|
|
159
|
+
};
|
|
160
|
+
const createIdMutationInvoker = (options, config, keys, operation) => {
|
|
116
161
|
async function mutate(datasetRef, rowIds, decodeResult, mutationOptions) {
|
|
117
|
-
const body = { ...idMutationBody(operation, rowIds), ...mutationOptions };
|
|
118
162
|
const path = datasetMutationPath(datasetRef);
|
|
163
|
+
const { body, send } = keyedMutationBody(idMutationBody(operation, rowIds), mutationOptions, config, keys, datasetRef);
|
|
119
164
|
if (decodeResult === undefined) {
|
|
120
|
-
return await postProviderDatasetWrite(options, path, body);
|
|
165
|
+
return await postProviderDatasetWrite(options, path, body, send);
|
|
121
166
|
}
|
|
122
|
-
return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
|
|
167
|
+
return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
|
|
123
168
|
}
|
|
124
169
|
return mutate;
|
|
125
170
|
};
|
|
126
|
-
const createSqlWriteInvoker = (options) => {
|
|
171
|
+
const createSqlWriteInvoker = (options, config, keys) => {
|
|
172
|
+
// A SQL statement has no stored command to replay, so it is never sent
|
|
173
|
+
// again here. Its key lets the server answer a caller's own second send of
|
|
174
|
+
// the same call with the first result instead of running it twice.
|
|
175
|
+
const send = { config, resendLost: false };
|
|
127
176
|
async function write(sql, writeOptions, decodeResult) {
|
|
128
|
-
const body = sqlBody(sql, writeOptions);
|
|
177
|
+
const body = sqlBody(sql, writeOptions, config, keys);
|
|
129
178
|
if (decodeResult === undefined) {
|
|
130
|
-
return await postProviderDatasetWrite(options, "dataset-sql", body);
|
|
179
|
+
return await postProviderDatasetWrite(options, "dataset-sql", body, send);
|
|
131
180
|
}
|
|
132
|
-
return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, decodeResult);
|
|
181
|
+
return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, send, decodeResult);
|
|
133
182
|
}
|
|
134
183
|
return write;
|
|
135
184
|
};
|
|
136
185
|
/** Build the Dataset surface hung off a server context. */
|
|
137
|
-
export const createDatasetsContext = (app, clientOptions) =>
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
186
|
+
export const createDatasetsContext = (app, clientOptions, keys = RANDOM_CALL_KEYS) => {
|
|
187
|
+
const config = resolveDamperConfig(clientOptions.dampers);
|
|
188
|
+
return {
|
|
189
|
+
deleteRows: createIdMutationInvoker(clientOptions, config, keys, "delete"),
|
|
190
|
+
insertRows: createRowMutationInvoker(clientOptions, config, keys),
|
|
191
|
+
queryRows: createQueryRowsInvoker(app),
|
|
192
|
+
restoreRows: createIdMutationInvoker(clientOptions, config, keys, "restore"),
|
|
193
|
+
sqlWrite: createSqlWriteInvoker(clientOptions, config, keys),
|
|
194
|
+
upsertRows: createRowMutationInvoker(clientOptions, config, keys),
|
|
195
|
+
upsertRowViews: createRowViewMutationInvoker(clientOptions, config, keys),
|
|
196
|
+
};
|
|
197
|
+
};
|
package/dist/errors.js
CHANGED
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,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,5 @@ 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
7
|
export declare const createActionInvoker: (app: UruAppRuntimeClient) => UruActionInvoker;
|
package/dist/invocations.js
CHANGED
|
@@ -13,9 +13,9 @@ export const createJobStatusInvoker = (options, 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
|
+
};
|