@uru-intelligence/app 2.1.1 → 2.1.3
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 +33 -0
- package/dist/dampers.d.ts +3 -3
- package/dist/dampers.js +24 -6
- package/dist/dataset-boundary.js +15 -0
- package/dist/datasets.js +4 -4
- package/dist/transport-deadline.d.ts +8 -0
- package/dist/transport-deadline.js +107 -0
- package/dist/transport-invocation.d.ts +21 -0
- package/dist/transport-invocation.js +48 -0
- package/dist/transport.js +46 -53
- package/dist/types.d.ts +30 -4
- package/dist/uploads.d.ts +8 -0
- package/dist/uploads.js +73 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -155,6 +155,8 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
|
|
|
155
155
|
on HTTP 429 and throttles `forceRefresh` per capability. Override these
|
|
156
156
|
controls through `dampers`; see `UruRunawayDamperOptions`. Supply an explicit
|
|
157
157
|
`idempotencyKey` when your application retries the same logical operation.
|
|
158
|
+
A custom retry wait can accept the optional `AbortSignal` to stop its own
|
|
159
|
+
work. The SDK still bounds the call when that wait ignores the signal.
|
|
158
160
|
|
|
159
161
|
## Transport values
|
|
160
162
|
|
|
@@ -169,6 +171,11 @@ Input that exceeds the JavaScript runtime's serialization limit also fails
|
|
|
169
171
|
before either action. `timeoutMs`, when set, must be an integer from 1,000 to
|
|
170
172
|
60,000, as required by the runtime HTTP contract.
|
|
171
173
|
|
|
174
|
+
Pass an `AbortSignal` as `signal` to cancel a capability call, job status read,
|
|
175
|
+
or job cancel request. The signal is local to the SDK and is never sent in the
|
|
176
|
+
JSON body. When `timeoutMs` is set, it also bounds the network request, response
|
|
177
|
+
body read, and any 429 retry wait.
|
|
178
|
+
|
|
172
179
|
Response diagnostics use the same JSON rules. Invalid diagnostics in a success
|
|
173
180
|
response cause `UruAppRuntimeError`. An HTTP error keeps its original status and
|
|
174
181
|
body. Diagnostic keys remain opaque; the client does not change their casing.
|
|
@@ -298,3 +305,29 @@ Building Gems is documented at
|
|
|
298
305
|
|
|
299
306
|
Proprietary. See [LICENSE](./LICENSE). You may use and redistribute this package
|
|
300
307
|
as part of an application that runs on the Uru platform.
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
### Conditional Dataset saves
|
|
311
|
+
|
|
312
|
+
Native row queries return `revision`. Pass it as `expectedDatasetRevision` with
|
|
313
|
+
an `idempotencyKey` to reject changes made since that read:
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
const page = await uru.datasets.queryRows('contacts', { limit: 1 });
|
|
317
|
+
if (page.revision === undefined) throw new Error('Native revision required');
|
|
318
|
+
await uru.datasets.upsertRows('contacts', [{ id: rowId, name: 'Updated' }],
|
|
319
|
+
undefined, { expectedDatasetRevision: page.revision, idempotencyKey: saveId });
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Keep the key for that save across retries. Hosted Gems scope it to the verified
|
|
323
|
+
Gem and viewer. A repeated request can report a conflict if preparing the row
|
|
324
|
+
would now produce different values. Read the saved record before retrying;
|
|
325
|
+
confirm the intended fields were saved or ask the user to resolve the conflict.
|
|
326
|
+
Never assign a new key merely to bypass a conflict. Browser conditional saves
|
|
327
|
+
require a built Gem runtime, including GitHub previews. External datasets do
|
|
328
|
+
not supply a native revision and remain read-only.
|
|
329
|
+
|
|
330
|
+
The fourth argument is the mutation options object. The optional third argument
|
|
331
|
+
remains the result decoder. Native query responses also include `runtimeContext`
|
|
332
|
+
with the server-verified `artifactId` and `viewerUserId` for local recovery state.
|
|
333
|
+
These returned identifiers do not grant access to other resources.
|
package/dist/dampers.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export interface ResolvedDamperConfig {
|
|
|
7
7
|
readonly rateLimitMaxDelayMs: number;
|
|
8
8
|
readonly forceRefreshMinIntervalMs: number;
|
|
9
9
|
readonly now: () => number;
|
|
10
|
-
readonly sleep: (ms: number) => Promise<void>;
|
|
10
|
+
readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
11
11
|
}
|
|
12
12
|
/** Caller-supplied damper overrides; every field defaults (see {@link resolveDamperConfig}). */
|
|
13
13
|
export interface UruRunawayDamperOptions {
|
|
@@ -23,8 +23,8 @@ export interface UruRunawayDamperOptions {
|
|
|
23
23
|
forceRefreshMinIntervalMs?: number;
|
|
24
24
|
/** Clock (ms); injectable for tests. Defaults to `Date.now`. */
|
|
25
25
|
now?: () => number;
|
|
26
|
-
/** Async delay; injectable for tests. Defaults to `setTimeout`. */
|
|
27
|
-
sleep?: (ms: number) => Promise<void>;
|
|
26
|
+
/** Async delay; injectable for tests. Defaults to an abortable `setTimeout`. */
|
|
27
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
28
28
|
}
|
|
29
29
|
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
30
30
|
export declare const resolveDamperConfig: (options: UruRunawayDamperOptions | undefined) => ResolvedDamperConfig;
|
package/dist/dampers.js
CHANGED
|
@@ -10,13 +10,31 @@ const positiveOr = (value, fallback) => typeof value === "number" && Number.isFi
|
|
|
10
10
|
const nonNegativeOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
11
11
|
? value
|
|
12
12
|
: fallback;
|
|
13
|
-
const defaultSleep =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
13
|
+
const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
14
|
+
let timeout;
|
|
15
|
+
const abort = () => {
|
|
16
|
+
cleanup();
|
|
17
|
+
reject(signal?.reason ??
|
|
18
|
+
new DOMException("The operation was aborted.", "AbortError"));
|
|
19
|
+
};
|
|
20
|
+
const cleanup = () => {
|
|
21
|
+
clearTimeout(timeout);
|
|
22
|
+
signal?.removeEventListener("abort", abort);
|
|
23
|
+
};
|
|
24
|
+
timeout = setTimeout(() => {
|
|
25
|
+
cleanup();
|
|
26
|
+
resolve();
|
|
17
27
|
}, Math.max(0, ms));
|
|
18
|
-
|
|
19
|
-
|
|
28
|
+
if (signal === undefined)
|
|
29
|
+
return;
|
|
30
|
+
if (signal.aborted) {
|
|
31
|
+
abort();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
35
|
+
if (signal.aborted)
|
|
36
|
+
abort();
|
|
37
|
+
});
|
|
20
38
|
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
21
39
|
export const resolveDamperConfig = (options) => ({
|
|
22
40
|
defaultIdempotencyKeys: options?.defaultIdempotencyKeys ?? true,
|
package/dist/dataset-boundary.js
CHANGED
|
@@ -101,6 +101,21 @@ const decodedRows = (value, decodeRow, label) => {
|
|
|
101
101
|
};
|
|
102
102
|
const rowsResultFields = (body, rows, label) => {
|
|
103
103
|
const output = { rows };
|
|
104
|
+
const revision = body.revision;
|
|
105
|
+
if (revision !== undefined) {
|
|
106
|
+
if (typeof revision !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(revision))
|
|
107
|
+
return invalidResponse(label, body, "revision");
|
|
108
|
+
output.revision = revision;
|
|
109
|
+
}
|
|
110
|
+
const runtimeContext = body.runtimeContext;
|
|
111
|
+
if (runtimeContext !== undefined) {
|
|
112
|
+
if (runtimeContext === null || typeof runtimeContext !== "object" || Array.isArray(runtimeContext) ||
|
|
113
|
+
typeof runtimeContext.artifactId !== "string" ||
|
|
114
|
+
(runtimeContext.viewerUserId !== null && typeof runtimeContext.viewerUserId !== "string")) {
|
|
115
|
+
return invalidResponse(label, body, "runtimeContext");
|
|
116
|
+
}
|
|
117
|
+
output.runtimeContext = { artifactId: runtimeContext.artifactId, viewerUserId: runtimeContext.viewerUserId };
|
|
118
|
+
}
|
|
104
119
|
const total = optionalTotal(body, label);
|
|
105
120
|
if (total !== undefined) {
|
|
106
121
|
output.total = total;
|
package/dist/datasets.js
CHANGED
|
@@ -102,8 +102,8 @@ const createQueryRowsInvoker = (app) => {
|
|
|
102
102
|
return queryRows;
|
|
103
103
|
};
|
|
104
104
|
const createRowMutationInvoker = (options) => {
|
|
105
|
-
async function mutate(datasetRef, rows, decodeResult) {
|
|
106
|
-
const body = upsertBody(rows);
|
|
105
|
+
async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
|
|
106
|
+
const body = { ...upsertBody(rows), ...mutationOptions };
|
|
107
107
|
const path = datasetMutationPath(datasetRef);
|
|
108
108
|
if (decodeResult === undefined) {
|
|
109
109
|
return await postProviderDatasetWrite(options, path, body);
|
|
@@ -113,8 +113,8 @@ const createRowMutationInvoker = (options) => {
|
|
|
113
113
|
return mutate;
|
|
114
114
|
};
|
|
115
115
|
const createIdMutationInvoker = (options, operation) => {
|
|
116
|
-
async function mutate(datasetRef, rowIds, decodeResult) {
|
|
117
|
-
const body = idMutationBody(operation, rowIds);
|
|
116
|
+
async function mutate(datasetRef, rowIds, decodeResult, mutationOptions) {
|
|
117
|
+
const body = { ...idMutationBody(operation, rowIds), ...mutationOptions };
|
|
118
118
|
const path = datasetMutationPath(datasetRef);
|
|
119
119
|
if (decodeResult === undefined) {
|
|
120
120
|
return await postProviderDatasetWrite(options, path, body);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { UruAppRuntimeInvocationOptions } from "./types.js";
|
|
2
|
+
export declare const assertRuntimeSignal: (value: unknown) => void;
|
|
3
|
+
export declare const validateRuntimeInvocationOptions: (options?: UruAppRuntimeInvocationOptions) => void;
|
|
4
|
+
export declare const withRuntimeRequestSignal: <T>(options: UruAppRuntimeInvocationOptions | undefined, action: (signal: AbortSignal | undefined) => Promise<T>) => Promise<T>;
|
|
5
|
+
export declare const abortReason: (signal: AbortSignal) => unknown;
|
|
6
|
+
/** Race a fetch, body read, or retry wait against the same request signal. */
|
|
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>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { UruAppRuntimeError } from "./errors.js";
|
|
2
|
+
export const assertRuntimeSignal = (value) => {
|
|
3
|
+
if (value !== undefined &&
|
|
4
|
+
(typeof AbortSignal === "undefined" || !(value instanceof AbortSignal))) {
|
|
5
|
+
throw new UruAppRuntimeError("Invalid app runtime signal.", {
|
|
6
|
+
body: null,
|
|
7
|
+
status: 0,
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const assertRuntimeTimeout = (value) => {
|
|
12
|
+
if (!Number.isInteger(value) || value < 1000 || value > 60_000) {
|
|
13
|
+
throw new UruAppRuntimeError("Invalid app runtime timeoutMs.", {
|
|
14
|
+
body: value,
|
|
15
|
+
status: 0,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
export const validateRuntimeInvocationOptions = (options) => {
|
|
20
|
+
assertRuntimeSignal(options?.signal);
|
|
21
|
+
if (options?.timeoutMs !== undefined) {
|
|
22
|
+
assertRuntimeTimeout(options.timeoutMs);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const runtimeSignalIsAborted = (signal) => signal?.aborted === true;
|
|
26
|
+
/**
|
|
27
|
+
* Make one deadline for the whole network operation. The regular timer keeps
|
|
28
|
+
* the deadline live even when the caller has no other active event-loop work.
|
|
29
|
+
* The owner clears it after the response body or aborted request settles.
|
|
30
|
+
*/
|
|
31
|
+
const runtimeRequestSignal = (options) => {
|
|
32
|
+
validateRuntimeInvocationOptions(options);
|
|
33
|
+
const timeoutMs = options?.timeoutMs;
|
|
34
|
+
const callerSignal = options?.signal;
|
|
35
|
+
if (timeoutMs === undefined) {
|
|
36
|
+
return callerSignal === undefined
|
|
37
|
+
? { dispose: () => undefined }
|
|
38
|
+
: { signal: callerSignal, dispose: () => undefined };
|
|
39
|
+
}
|
|
40
|
+
const timeoutController = new AbortController();
|
|
41
|
+
const timeout = setTimeout(() => {
|
|
42
|
+
timeoutController.abort(new DOMException("The operation timed out.", "TimeoutError"));
|
|
43
|
+
}, timeoutMs);
|
|
44
|
+
return {
|
|
45
|
+
signal: callerSignal === undefined
|
|
46
|
+
? timeoutController.signal
|
|
47
|
+
: AbortSignal.any([callerSignal, timeoutController.signal]),
|
|
48
|
+
dispose: () => clearTimeout(timeout),
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export const withRuntimeRequestSignal = async (options, action) => {
|
|
52
|
+
const request = runtimeRequestSignal(options);
|
|
53
|
+
try {
|
|
54
|
+
return await action(request.signal);
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
request.dispose();
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
export const abortReason = (signal) => signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
61
|
+
/** Race a fetch, body read, or retry wait against the same request signal. */
|
|
62
|
+
export const awaitWithAbort = async (promise, signal) => {
|
|
63
|
+
if (signal === undefined)
|
|
64
|
+
return await promise;
|
|
65
|
+
if (signal.aborted)
|
|
66
|
+
throw abortReason(signal);
|
|
67
|
+
return await new Promise((resolve, reject) => {
|
|
68
|
+
const onAbort = () => {
|
|
69
|
+
signal.removeEventListener("abort", onAbort);
|
|
70
|
+
reject(abortReason(signal));
|
|
71
|
+
};
|
|
72
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
73
|
+
void promise.then(value => {
|
|
74
|
+
signal.removeEventListener("abort", onAbort);
|
|
75
|
+
resolve(value);
|
|
76
|
+
}, error => {
|
|
77
|
+
signal.removeEventListener("abort", onAbort);
|
|
78
|
+
reject(error);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
};
|
|
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
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { DamperRuntime } from "./transport.js";
|
|
2
|
+
import type { UruAppRuntimeCapabilityType, UruAppRuntimeEvent } from "./types.js";
|
|
3
|
+
import type { RuntimeFetch } from "./runtime.js";
|
|
4
|
+
export interface InvocationFetchArguments {
|
|
5
|
+
capabilityName: string;
|
|
6
|
+
capabilityType: UruAppRuntimeCapabilityType;
|
|
7
|
+
damper: DamperRuntime;
|
|
8
|
+
deploymentId: string;
|
|
9
|
+
emit: (event: UruAppRuntimeEvent) => void;
|
|
10
|
+
headers: Headers;
|
|
11
|
+
requestBody: string;
|
|
12
|
+
requestId: string;
|
|
13
|
+
runtimeFetch: RuntimeFetch;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
url: string;
|
|
16
|
+
}
|
|
17
|
+
export interface RuntimeFetchResult {
|
|
18
|
+
body: unknown;
|
|
19
|
+
response: Response;
|
|
20
|
+
}
|
|
21
|
+
export declare const fetchInvocation: (args: InvocationFetchArguments, attempt?: number) => Promise<RuntimeFetchResult>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
|
|
2
|
+
import { awaitWithAbort, readRuntimeResponseBody, } from "./transport-deadline.js";
|
|
3
|
+
export const fetchInvocation = async (args, attempt = 0) => {
|
|
4
|
+
// Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
|
|
5
|
+
// would hand the fetch `args` as its receiver — the same class of mistake
|
|
6
|
+
// that broke the global one.
|
|
7
|
+
const { runtimeFetch } = args;
|
|
8
|
+
args.signal?.throwIfAborted();
|
|
9
|
+
const response = await awaitWithAbort(Promise.resolve().then(() => {
|
|
10
|
+
args.signal?.throwIfAborted();
|
|
11
|
+
return runtimeFetch(args.url, {
|
|
12
|
+
body: args.requestBody,
|
|
13
|
+
headers: args.headers,
|
|
14
|
+
method: "POST",
|
|
15
|
+
...(args.signal === undefined ? {} : { signal: args.signal }),
|
|
16
|
+
});
|
|
17
|
+
}), args.signal);
|
|
18
|
+
const body = await readRuntimeResponseBody(response, args.signal);
|
|
19
|
+
const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
|
|
20
|
+
if (!shouldRetry) {
|
|
21
|
+
return { body, response };
|
|
22
|
+
}
|
|
23
|
+
const delayMs = computeRateLimitBackoffMs({
|
|
24
|
+
attempt,
|
|
25
|
+
baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
|
|
26
|
+
maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
|
|
27
|
+
retryAfterSeconds: parseRetryAfterSeconds({
|
|
28
|
+
body,
|
|
29
|
+
header: response.headers.get("retry-after"),
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
args.signal?.throwIfAborted();
|
|
33
|
+
args.emit({
|
|
34
|
+
capabilityName: args.capabilityName,
|
|
35
|
+
capabilityType: args.capabilityType,
|
|
36
|
+
deploymentId: args.deploymentId,
|
|
37
|
+
requestId: args.requestId,
|
|
38
|
+
retryAfterSeconds: Math.ceil(delayMs / 1000),
|
|
39
|
+
state: "rate_limited",
|
|
40
|
+
type: "status",
|
|
41
|
+
});
|
|
42
|
+
args.signal?.throwIfAborted();
|
|
43
|
+
const sleepPromise = args.signal === undefined
|
|
44
|
+
? args.damper.config.sleep(delayMs)
|
|
45
|
+
: args.damper.config.sleep(delayMs, args.signal);
|
|
46
|
+
await awaitWithAbort(sleepPromise, args.signal);
|
|
47
|
+
return await fetchInvocation(args, attempt + 1);
|
|
48
|
+
};
|
package/dist/transport.js
CHANGED
|
@@ -15,10 +15,11 @@
|
|
|
15
15
|
* for by exporting four internal helpers from it. Every edge here points at a
|
|
16
16
|
* module that imports nothing back.
|
|
17
17
|
*/
|
|
18
|
-
import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
|
|
19
18
|
import { runtimeErrorMessage } from "./error-response.js";
|
|
20
19
|
import { UruAppRuntimeError } from "./errors.js";
|
|
21
20
|
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
21
|
+
import { abortReason, awaitWithAbort, readRuntimeResponseBody, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
|
|
22
|
+
import { fetchInvocation } from "./transport-invocation.js";
|
|
22
23
|
import { isRuntimeJsonObject } from "./transport-json.js";
|
|
23
24
|
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
25
|
const httpRecord = (value, label) => {
|
|
@@ -167,20 +168,13 @@ const encodeCapabilityPath = (capabilityType, capabilityName) => {
|
|
|
167
168
|
const makeRuntimeRequestId = () => `uru_app_${Math.random().toString(36).slice(2)}`;
|
|
168
169
|
const runtimeHttpRequestOptions = (options) => {
|
|
169
170
|
const transport = {};
|
|
171
|
+
validateRuntimeInvocationOptions(options);
|
|
170
172
|
const idempotencyKey = options?.idempotencyKey;
|
|
171
173
|
if (idempotencyKey !== undefined && idempotencyKey !== "") {
|
|
172
174
|
transport.idempotencyKey = idempotencyKey;
|
|
173
175
|
}
|
|
174
176
|
const timeoutMs = options?.timeoutMs;
|
|
175
177
|
if (timeoutMs !== undefined) {
|
|
176
|
-
if (!Number.isInteger(timeoutMs) ||
|
|
177
|
-
timeoutMs < 1000 ||
|
|
178
|
-
timeoutMs > 60_000) {
|
|
179
|
-
throw new UruAppRuntimeError("Invalid app runtime timeoutMs.", {
|
|
180
|
-
body: timeoutMs,
|
|
181
|
-
status: 0,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
178
|
transport.timeoutMs = timeoutMs;
|
|
185
179
|
}
|
|
186
180
|
if (options?.forceRefresh === true) {
|
|
@@ -350,43 +344,6 @@ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper,
|
|
|
350
344
|
});
|
|
351
345
|
}
|
|
352
346
|
};
|
|
353
|
-
const responseBody = async (response) => await response.json().catch(() => null);
|
|
354
|
-
const fetchInvocation = async (args, attempt = 0) => {
|
|
355
|
-
// Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
|
|
356
|
-
// would hand the fetch `args` as its receiver — the same class of mistake
|
|
357
|
-
// that broke the global one.
|
|
358
|
-
const { runtimeFetch } = args;
|
|
359
|
-
const response = await runtimeFetch(args.url, {
|
|
360
|
-
body: args.requestBody,
|
|
361
|
-
headers: args.headers,
|
|
362
|
-
method: "POST",
|
|
363
|
-
});
|
|
364
|
-
const body = await responseBody(response);
|
|
365
|
-
const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
|
|
366
|
-
if (!shouldRetry) {
|
|
367
|
-
return { body, response };
|
|
368
|
-
}
|
|
369
|
-
const delayMs = computeRateLimitBackoffMs({
|
|
370
|
-
attempt,
|
|
371
|
-
baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
|
|
372
|
-
maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
|
|
373
|
-
retryAfterSeconds: parseRetryAfterSeconds({
|
|
374
|
-
body,
|
|
375
|
-
header: response.headers.get("retry-after"),
|
|
376
|
-
}),
|
|
377
|
-
});
|
|
378
|
-
emitRuntimeEvent(args.invocationOptions, {
|
|
379
|
-
capabilityName: args.capabilityName,
|
|
380
|
-
capabilityType: args.capabilityType,
|
|
381
|
-
deploymentId: args.deploymentId,
|
|
382
|
-
requestId: args.requestId,
|
|
383
|
-
retryAfterSeconds: Math.ceil(delayMs / 1000),
|
|
384
|
-
state: "rate_limited",
|
|
385
|
-
type: "status",
|
|
386
|
-
});
|
|
387
|
-
await args.damper.config.sleep(delayMs);
|
|
388
|
-
return await fetchInvocation(args, attempt + 1);
|
|
389
|
-
};
|
|
390
347
|
const normalizedInvocationResponse = (runtimeResponse, fallbackIdentity, fallbackCapabilityType, state, diagnostics) => ({
|
|
391
348
|
capabilityName: runtimeResponse.capabilityName === ""
|
|
392
349
|
? fallbackIdentity.capabilityName
|
|
@@ -415,6 +372,9 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
|
|
|
415
372
|
const { capabilityName, deploymentId } = identity;
|
|
416
373
|
const runtimeInput = invocationInput(input);
|
|
417
374
|
const transport = runtimeHttpRequestOptions(invocationOptions);
|
|
375
|
+
if (invocationOptions?.signal?.aborted === true) {
|
|
376
|
+
throw abortReason(invocationOptions.signal);
|
|
377
|
+
}
|
|
418
378
|
// P2 damper: a requested forceRefresh is honored only if it clears the
|
|
419
379
|
// per-capability throttle; otherwise the call is sent WITHOUT force_refresh so
|
|
420
380
|
// it can be served from cache instead of hammering past it.
|
|
@@ -444,18 +404,19 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
|
|
|
444
404
|
// retries beyond the first send; the loop performs at most
|
|
445
405
|
// `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
|
|
446
406
|
// (capped) before falling through to the normal failure path.
|
|
447
|
-
const { body, response } = await fetchInvocation({
|
|
407
|
+
const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
|
|
448
408
|
capabilityName,
|
|
449
409
|
capabilityType,
|
|
450
410
|
damper,
|
|
451
411
|
deploymentId,
|
|
412
|
+
emit: event => emitRuntimeEvent(invocationOptions, event),
|
|
452
413
|
headers,
|
|
453
|
-
...(invocationOptions === undefined ? {} : { invocationOptions }),
|
|
454
414
|
requestBody,
|
|
455
415
|
requestId,
|
|
456
416
|
runtimeFetch,
|
|
417
|
+
...(requestSignal === undefined ? {} : { signal: requestSignal }),
|
|
457
418
|
url,
|
|
458
|
-
});
|
|
419
|
+
}));
|
|
459
420
|
if (!response.ok) {
|
|
460
421
|
const message = runtimeErrorMessage(body, `Uru app runtime call failed with HTTP ${response.status}`);
|
|
461
422
|
emitRuntimeEvent(invocationOptions, {
|
|
@@ -558,6 +519,8 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
|
|
|
558
519
|
const runtimeFetch = resolveRuntimeFetch(options);
|
|
559
520
|
const identity = jobIdentity(options, executionId);
|
|
560
521
|
const { deploymentId, executionId: normalizedExecutionId } = identity;
|
|
522
|
+
validateRuntimeInvocationOptions(invocationOptions);
|
|
523
|
+
invocationOptions?.signal?.throwIfAborted();
|
|
561
524
|
const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
|
|
562
525
|
emitRuntimeEvent(invocationOptions, {
|
|
563
526
|
capabilityName: "",
|
|
@@ -570,8 +533,22 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
|
|
|
570
533
|
});
|
|
571
534
|
const url = jobExecutionUrl(options, identity);
|
|
572
535
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
573
|
-
const response = await
|
|
574
|
-
|
|
536
|
+
const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
|
|
537
|
+
if (signal?.aborted === true) {
|
|
538
|
+
throw abortReason(signal);
|
|
539
|
+
}
|
|
540
|
+
const response = await awaitWithAbort(Promise.resolve().then(() => {
|
|
541
|
+
if (signal?.aborted === true) {
|
|
542
|
+
throw abortReason(signal);
|
|
543
|
+
}
|
|
544
|
+
return runtimeFetch(url, {
|
|
545
|
+
headers,
|
|
546
|
+
method: "GET",
|
|
547
|
+
...(signal === undefined ? {} : { signal }),
|
|
548
|
+
});
|
|
549
|
+
}), signal);
|
|
550
|
+
return { body: await readRuntimeResponseBody(response, signal), response };
|
|
551
|
+
});
|
|
575
552
|
if (!response.ok && response.status !== 202) {
|
|
576
553
|
const message = runtimeErrorMessage(body, `Uru app runtime job status failed with HTTP ${response.status}`);
|
|
577
554
|
emitRuntimeEvent(invocationOptions, {
|
|
@@ -615,11 +592,27 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
|
|
|
615
592
|
const runtimeFetch = resolveRuntimeFetch(options);
|
|
616
593
|
const identity = jobIdentity(options, executionId);
|
|
617
594
|
const { deploymentId, executionId: normalizedExecutionId } = identity;
|
|
595
|
+
validateRuntimeInvocationOptions(invocationOptions);
|
|
596
|
+
invocationOptions?.signal?.throwIfAborted();
|
|
618
597
|
const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
|
|
619
598
|
const url = jobExecutionUrl(options, identity, true);
|
|
620
599
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
621
|
-
const response = await
|
|
622
|
-
|
|
600
|
+
const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
|
|
601
|
+
if (signal?.aborted === true) {
|
|
602
|
+
throw abortReason(signal);
|
|
603
|
+
}
|
|
604
|
+
const response = await awaitWithAbort(Promise.resolve().then(() => {
|
|
605
|
+
if (signal?.aborted === true) {
|
|
606
|
+
throw abortReason(signal);
|
|
607
|
+
}
|
|
608
|
+
return runtimeFetch(url, {
|
|
609
|
+
headers,
|
|
610
|
+
method: "POST",
|
|
611
|
+
...(signal === undefined ? {} : { signal }),
|
|
612
|
+
});
|
|
613
|
+
}), signal);
|
|
614
|
+
return { body: await readRuntimeResponseBody(response, signal), response };
|
|
615
|
+
});
|
|
623
616
|
if (!response.ok) {
|
|
624
617
|
const message = runtimeErrorMessage(body, `Uru app runtime job cancel failed with HTTP ${response.status}`);
|
|
625
618
|
emitRuntimeEvent(invocationOptions, {
|
package/dist/types.d.ts
CHANGED
|
@@ -48,6 +48,8 @@ export interface UruAppRuntimeEvent<TResult = unknown> {
|
|
|
48
48
|
/** Per-call options accepted by every capability method. */
|
|
49
49
|
export interface UruAppRuntimeInvocationOptions {
|
|
50
50
|
idempotencyKey?: string;
|
|
51
|
+
/** Abort the network call, response-body read, or retry wait. */
|
|
52
|
+
signal?: AbortSignal;
|
|
51
53
|
timeoutMs?: number;
|
|
52
54
|
forceRefresh?: boolean;
|
|
53
55
|
requestId?: string;
|
|
@@ -151,6 +153,11 @@ export interface UruDatasetQuery {
|
|
|
151
153
|
/** One page of Dataset rows, plus the total when `includeTotal` asked for it. */
|
|
152
154
|
export interface UruDatasetRowsResult<TRow = UruDatasetRow> {
|
|
153
155
|
rows: TRow[];
|
|
156
|
+
revision?: string;
|
|
157
|
+
runtimeContext?: {
|
|
158
|
+
artifactId: string;
|
|
159
|
+
viewerUserId: string | null;
|
|
160
|
+
};
|
|
154
161
|
total?: number | null;
|
|
155
162
|
limit?: number;
|
|
156
163
|
offset?: number;
|
|
@@ -186,13 +193,18 @@ export interface UruDatasetQueryRows {
|
|
|
186
193
|
<TRow>(datasetRef: string, query: UruDatasetQuery | undefined, decodeRow: UruResultDecoder<TRow>): Promise<UruDatasetRowsResult<TRow>>;
|
|
187
194
|
(datasetRef: string, query?: UruDatasetQuery): Promise<UruDatasetRowsResult>;
|
|
188
195
|
}
|
|
196
|
+
/** Public wire contract: kept local because this package has no private workspace dependencies. */
|
|
197
|
+
export interface UruDatasetMutationOptions {
|
|
198
|
+
expectedDatasetRevision?: string;
|
|
199
|
+
idempotencyKey?: string;
|
|
200
|
+
}
|
|
189
201
|
export interface UruDatasetRowMutation {
|
|
190
|
-
<TResult>(datasetRef: string, rows: readonly unknown[], decodeResult: UruResultDecoder<TResult
|
|
191
|
-
(datasetRef: string, rows: readonly unknown[]): Promise<UruDatasetMutationResult>;
|
|
202
|
+
<TResult>(datasetRef: string, rows: readonly unknown[], decodeResult: UruResultDecoder<TResult>, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult<TResult>>;
|
|
203
|
+
(datasetRef: string, rows: readonly unknown[], decodeResult?: undefined, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult>;
|
|
192
204
|
}
|
|
193
205
|
export interface UruDatasetIdMutation {
|
|
194
|
-
<TResult>(datasetRef: string, rowIds: readonly string[], decodeResult: UruResultDecoder<TResult
|
|
195
|
-
(datasetRef: string, rowIds: readonly string[]): Promise<UruDatasetMutationResult>;
|
|
206
|
+
<TResult>(datasetRef: string, rowIds: readonly string[], decodeResult: UruResultDecoder<TResult>, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult<TResult>>;
|
|
207
|
+
(datasetRef: string, rowIds: readonly string[], decodeResult?: undefined, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult>;
|
|
196
208
|
}
|
|
197
209
|
export interface UruDatasetSqlWrite {
|
|
198
210
|
<TResult>(sql: string, options: UruDatasetSqlWriteOptions, decodeResult: UruResultDecoder<TResult>): Promise<UruDatasetMutationResult<TResult>>;
|
|
@@ -295,6 +307,20 @@ export interface UruUploadsContext {
|
|
|
295
307
|
upload(file: File, options?: {
|
|
296
308
|
signal?: AbortSignal;
|
|
297
309
|
}): Promise<UruUploadResult>;
|
|
310
|
+
/**
|
|
311
|
+
* Read one VERIFIED upload back, as a `Blob`.
|
|
312
|
+
*
|
|
313
|
+
* A Blob rather than a URL because the read is AUTHENTICATED: the platform
|
|
314
|
+
* serves the bytes under the same authority that minted the grant, and an
|
|
315
|
+
* `<img src>` or an `<a href>` carries none of the runtime's headers. Hand
|
|
316
|
+
* the Blob to `URL.createObjectURL` for a preview or a download link.
|
|
317
|
+
*
|
|
318
|
+
* Rejects when the upload is not the caller's, was never verified, or no
|
|
319
|
+
* longer exists.
|
|
320
|
+
*/
|
|
321
|
+
read(uploadId: string, options?: {
|
|
322
|
+
signal?: AbortSignal;
|
|
323
|
+
}): Promise<Blob>;
|
|
298
324
|
}
|
|
299
325
|
export interface UruJobProgress {
|
|
300
326
|
readonly completed: number;
|
package/dist/uploads.d.ts
CHANGED
|
@@ -17,6 +17,14 @@
|
|
|
17
17
|
*
|
|
18
18
|
* `upload(file)` performs all three, which is what almost every caller wants.
|
|
19
19
|
*
|
|
20
|
+
* ## And one hop back
|
|
21
|
+
*
|
|
22
|
+
* `read(uploadId)` returns the stored file as a `Blob`. The bytes come back
|
|
23
|
+
* THROUGH the platform, not from a storage link: the read is authorized per
|
|
24
|
+
* request under the same authority that minted the grant, so there is no
|
|
25
|
+
* shareable URL to leak. Keep the `uploadId` a verified upload gave you --
|
|
26
|
+
* `uru.storage` is the durable place for it -- and pass it here.
|
|
27
|
+
*
|
|
20
28
|
* ## The refusals are values, not exceptions
|
|
21
29
|
*
|
|
22
30
|
* A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
|
package/dist/uploads.js
CHANGED
|
@@ -17,6 +17,14 @@
|
|
|
17
17
|
*
|
|
18
18
|
* `upload(file)` performs all three, which is what almost every caller wants.
|
|
19
19
|
*
|
|
20
|
+
* ## And one hop back
|
|
21
|
+
*
|
|
22
|
+
* `read(uploadId)` returns the stored file as a `Blob`. The bytes come back
|
|
23
|
+
* THROUGH the platform, not from a storage link: the read is authorized per
|
|
24
|
+
* request under the same authority that minted the grant, so there is no
|
|
25
|
+
* shareable URL to leak. Keep the `uploadId` a verified upload gave you --
|
|
26
|
+
* `uru.storage` is the durable place for it -- and pass it here.
|
|
27
|
+
*
|
|
20
28
|
* ## The refusals are values, not exceptions
|
|
21
29
|
*
|
|
22
30
|
* A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
|
|
@@ -140,6 +148,48 @@ function resultFrom(value) {
|
|
|
140
148
|
cleanupFailed: row['cleanupFailed'] === true,
|
|
141
149
|
};
|
|
142
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Read the response body into a `Blob`, refusing anything above the platform's
|
|
153
|
+
* own per-file ceiling.
|
|
154
|
+
*
|
|
155
|
+
* Bounded for the same reason every other response in this SDK is: a runtime
|
|
156
|
+
* that answered with more bytes than a grant can ever hold would otherwise
|
|
157
|
+
* exhaust the Gem's memory through a call the Gem made on purpose.
|
|
158
|
+
*/
|
|
159
|
+
async function readBlob(response) {
|
|
160
|
+
const declared = Number(response.headers.get('content-length') ?? '');
|
|
161
|
+
if (Number.isFinite(declared) && declared > URU_UPLOAD_MAX_BYTES) {
|
|
162
|
+
await response.body?.cancel();
|
|
163
|
+
invalid();
|
|
164
|
+
}
|
|
165
|
+
const reader = response.body?.getReader();
|
|
166
|
+
if (reader === undefined)
|
|
167
|
+
invalid();
|
|
168
|
+
const parts = [];
|
|
169
|
+
let size = 0;
|
|
170
|
+
try {
|
|
171
|
+
for (;;) {
|
|
172
|
+
const chunk = await reader.read();
|
|
173
|
+
if (chunk.done)
|
|
174
|
+
break;
|
|
175
|
+
size += chunk.value.byteLength;
|
|
176
|
+
if (size > URU_UPLOAD_MAX_BYTES) {
|
|
177
|
+
await reader.cancel();
|
|
178
|
+
invalid();
|
|
179
|
+
}
|
|
180
|
+
parts.push(chunk.value);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
reader.releaseLock();
|
|
185
|
+
}
|
|
186
|
+
// The platform's stored media type, which is the one it verified the object
|
|
187
|
+
// against. A Blob that carried no type would render as a download of unknown
|
|
188
|
+
// kind wherever the Gem put it.
|
|
189
|
+
return new Blob(parts, {
|
|
190
|
+
type: response.headers.get('content-type') ?? 'application/octet-stream',
|
|
191
|
+
});
|
|
192
|
+
}
|
|
143
193
|
export function createUploadsContext(options) {
|
|
144
194
|
const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/uploads`;
|
|
145
195
|
// Resolved per call rather than once here, so building the context still
|
|
@@ -190,9 +240,32 @@ export function createUploadsContext(options) {
|
|
|
190
240
|
invalid();
|
|
191
241
|
return resultFrom(await post(`/${uploadId}/complete`, undefined, settings?.signal));
|
|
192
242
|
};
|
|
243
|
+
const read = async (uploadId, settings) => {
|
|
244
|
+
if (typeof uploadId !== 'string' || !UUID.test(uploadId))
|
|
245
|
+
invalid();
|
|
246
|
+
const response = await doFetch(`${base}/${uploadId}/content`, {
|
|
247
|
+
method: 'GET',
|
|
248
|
+
headers: new Headers(await resolveHeaders(options.headers)),
|
|
249
|
+
// Five minutes, not the thirty seconds the JSON hops use: a grant admits
|
|
250
|
+
// 104,857,600 bytes, and thirty seconds would need 3.5 MB/s to finish a
|
|
251
|
+
// file the platform was happy to store.
|
|
252
|
+
signal: settings?.signal === undefined
|
|
253
|
+
? AbortSignal.timeout(300_000)
|
|
254
|
+
: AbortSignal.any([settings.signal, AbortSignal.timeout(300_000)]),
|
|
255
|
+
});
|
|
256
|
+
if (!response.ok) {
|
|
257
|
+
await response.body?.cancel();
|
|
258
|
+
throw new UruAppRuntimeError('Upload could not be read.', {
|
|
259
|
+
status: response.status,
|
|
260
|
+
body: null,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return readBlob(response);
|
|
264
|
+
};
|
|
193
265
|
return {
|
|
194
266
|
request,
|
|
195
267
|
complete,
|
|
268
|
+
read,
|
|
196
269
|
upload: async (file, settings) => {
|
|
197
270
|
// The media type is the browser's, lower-cased by it already. A file the
|
|
198
271
|
// OS could not type at all gets the generic one rather than an empty
|