@uru-intelligence/app 2.2.1 → 2.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +303 -13
- package/dist/background-jobs.d.ts +4 -0
- package/dist/background-jobs.js +17 -22
- package/dist/dampers.d.ts +11 -4
- package/dist/datasets.js +9 -8
- package/dist/errors.js +4 -4
- package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
- package/dist/examples/customer-workflows/approved-external-write.js +162 -0
- package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
- package/dist/examples/customer-workflows/file-processor.js +53 -0
- package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
- package/dist/examples/customer-workflows/job-coordinator.js +1 -0
- package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
- package/dist/examples/customer-workflows/review-only-draft.js +48 -0
- package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
- package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
- package/dist/index.d.ts +1 -1
- package/dist/invocations.d.ts +10 -0
- package/dist/invocations.js +70 -2
- package/dist/jobs.js +5 -3
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +27 -7
- package/dist/transport-invocation.d.ts +3 -1
- package/dist/transport-invocation.js +6 -2
- package/dist/transport-retry.d.ts +20 -9
- package/dist/transport-retry.js +118 -27
- package/dist/transport.d.ts +1 -19
- package/dist/transport.js +1 -1
- package/dist/types.d.ts +20 -1
- package/dist/uploads.js +158 -19
- package/package.json +32 -7
package/dist/transport-retry.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Resends for a response the platform never gave.
|
|
2
|
+
* Resends for a response the platform never gave, and for a temporary answer.
|
|
3
3
|
*
|
|
4
4
|
* A deploy, a crash or a memory kill of one API replica shows up here as a
|
|
5
5
|
* failed or reset connection, a reply cut off after its headers, a 502 or 504
|
|
6
6
|
* from the edge, or a 503 from an edge with no healthy replica. None of them
|
|
7
7
|
* is an answer from Uru: the call may not have arrived, or it arrived and its
|
|
8
|
-
* reply was lost.
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* reply was lost. A short database stall shows up as a temporary answer from
|
|
9
|
+
* Uru: a 408, a 429 or a 503. Each caller decides whether its request is safe
|
|
10
|
+
* to send again (a keyed Dataset write is, a Dataset SQL statement is not);
|
|
11
|
+
* this module owns what counts as lost, what counts as temporary, and how
|
|
12
|
+
* long to wait.
|
|
11
13
|
*/
|
|
14
|
+
import { parseRetryable, parseRetryAfterSeconds } from "./dampers.js";
|
|
12
15
|
import { abortReason, awaitWithAbort } from "./transport-deadline.js";
|
|
13
16
|
/** Waits before jitter. With jitter the whole schedule lasts about a minute. */
|
|
14
17
|
const RESEND_BASE_DELAYS_MS = [
|
|
@@ -37,24 +40,57 @@ const safeRecordValue = (record, field) => {
|
|
|
37
40
|
return undefined;
|
|
38
41
|
}
|
|
39
42
|
};
|
|
40
|
-
const
|
|
43
|
+
const codeOf = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
|
|
41
44
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* answer
|
|
45
|
+
* The code of a JSON error body: the backend's `{ error: { code } }`
|
|
46
|
+
* envelope, the Gem dispatcher's `{ error: "gem_unavailable" }`, or
|
|
47
|
+
* `{ code }`. Uru wrote such a body, so the answer is Uru's. An edge with no
|
|
48
|
+
* replica answers with text.
|
|
45
49
|
*/
|
|
46
|
-
const
|
|
50
|
+
const ownedErrorCode = (body) => {
|
|
47
51
|
if (!isRecord(body))
|
|
48
|
-
return
|
|
52
|
+
return null;
|
|
49
53
|
const error = safeRecordValue(body, "error");
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
54
|
+
return (codeOf(error) ??
|
|
55
|
+
codeOf(safeRecordValue(body, "code")) ??
|
|
56
|
+
(isRecord(error) ? codeOf(safeRecordValue(error, "code")) : null));
|
|
53
57
|
};
|
|
54
58
|
/** A status the edge gives when no replica answered. */
|
|
55
59
|
export const isLostResponse = (status, body) => status === 502 ||
|
|
56
60
|
status === 504 ||
|
|
57
|
-
(status === 503 &&
|
|
61
|
+
(status === 503 && ownedErrorCode(body) === null);
|
|
62
|
+
/** The statuses Uru gives when it cannot serve a call now but can soon. */
|
|
63
|
+
const TEMPORARY_STATUSES = new Set([408, 429, 503]);
|
|
64
|
+
/**
|
|
65
|
+
* 503 codes for a missing setup, which a resend cannot fix. The provider
|
|
66
|
+
* gateway answers this one before any API replica sees the call.
|
|
67
|
+
*/
|
|
68
|
+
const SETUP_FAILURE_CODES = new Set([
|
|
69
|
+
"provider_gateway_limiter_unavailable",
|
|
70
|
+
]);
|
|
71
|
+
/**
|
|
72
|
+
* An answer from Uru that it cannot serve the call now but can soon: a 408,
|
|
73
|
+
* a 429 or a 503 (HTTP defines 503 as temporary, RFC 9110 section 15.6.4).
|
|
74
|
+
* Every other status is final, whatever its body says: a 500 means the call
|
|
75
|
+
* failed in a way that a resend repeats, and a 4xx such as 403, 404, 409 or
|
|
76
|
+
* 422 refuses this request. A body that says `retryable: false` (a Dataset
|
|
77
|
+
* job that ended) or names a missing setup is final too.
|
|
78
|
+
*/
|
|
79
|
+
const isTemporaryAnswer = (status, body) => {
|
|
80
|
+
if (!TEMPORARY_STATUSES.has(status))
|
|
81
|
+
return false;
|
|
82
|
+
if (parseRetryable(body) === false)
|
|
83
|
+
return false;
|
|
84
|
+
const code = ownedErrorCode(body);
|
|
85
|
+
return code === null || !SETUP_FAILURE_CODES.has(code);
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* The request header that tells the provider gateway this client sends a
|
|
89
|
+
* temporary answer again itself, so the gateway passes it straight back
|
|
90
|
+
* instead of sending the call again too. Without it, one call could reach
|
|
91
|
+
* the API once for each SDK send times each gateway send.
|
|
92
|
+
*/
|
|
93
|
+
const SDK_RESENDS_HEADER = "x-uru-sdk-resends";
|
|
58
94
|
/** A fetch that failed before a response, and not because the caller stopped it. */
|
|
59
95
|
export const isLostRequest = (error, signal) => {
|
|
60
96
|
if (signal?.aborted === true)
|
|
@@ -105,6 +141,19 @@ export const resendDelayMs = (resend, random) => {
|
|
|
105
141
|
};
|
|
106
142
|
/** Whether one more resend is allowed after `resend` earlier ones. */
|
|
107
143
|
export const canResend = (config, resend) => resend < config.maxTransportRetries;
|
|
144
|
+
/**
|
|
145
|
+
* The most that all the waits of one call may add up to: every allowed
|
|
146
|
+
* resend at its longest jittered wait, 63 seconds by default. A temporary
|
|
147
|
+
* answer's `Retry-After` can make one wait longer than the schedule gives it.
|
|
148
|
+
* A `Retry-After` longer than what is left of this budget ends the resends.
|
|
149
|
+
*/
|
|
150
|
+
const resendBudgetMs = (config) => {
|
|
151
|
+
const resends = Math.ceil(config.maxTransportRetries);
|
|
152
|
+
const listed = RESEND_BASE_DELAYS_MS.slice(0, resends).reduce((sum, delay) => sum + delay, 0);
|
|
153
|
+
const lastBase = RESEND_BASE_DELAYS_MS.at(-1) ?? 0;
|
|
154
|
+
const beyond = Math.max(0, resends - RESEND_BASE_DELAYS_MS.length) * lastBase;
|
|
155
|
+
return 2 * (listed + beyond);
|
|
156
|
+
};
|
|
108
157
|
/** Wait before a resend. The request signal (caller signal or deadline) ends the wait. */
|
|
109
158
|
export const waitBeforeResend = async (config, delayMs, signal) => {
|
|
110
159
|
signal?.throwIfAborted();
|
|
@@ -113,21 +162,56 @@ export const waitBeforeResend = async (config, delayMs, signal) => {
|
|
|
113
162
|
: config.sleep(delayMs, signal), signal);
|
|
114
163
|
};
|
|
115
164
|
const reachedSendLimit = (error, sendSignal) => sendSignal.aborted && error === sendSignal.reason;
|
|
165
|
+
/** The server's `Retry-After` (header or envelope) in milliseconds, else 0. */
|
|
166
|
+
const retryAfterMs = (outcome) => {
|
|
167
|
+
const seconds = parseRetryAfterSeconds({
|
|
168
|
+
body: outcome.body,
|
|
169
|
+
header: outcome.response.headers.get("retry-after"),
|
|
170
|
+
});
|
|
171
|
+
return seconds === null ? 0 : Math.ceil(seconds * 1000);
|
|
172
|
+
};
|
|
116
173
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
174
|
+
* How long to wait before resend `resent`, or null when the call is not sent
|
|
175
|
+
* again: it is not repeatable, it used its resends, the wait budget is spent,
|
|
176
|
+
* or a temporary answer's `Retry-After` is longer than what is left of the
|
|
177
|
+
* budget. The server's limit wins, so the call never goes out before the
|
|
178
|
+
* time it names. Otherwise the wait is the jittered schedule, or the
|
|
179
|
+
* `Retry-After` when that is longer. A lost response (`temporary` null) keeps
|
|
180
|
+
* the schedule as before, because no API replica wrote its headers. A
|
|
181
|
+
* scheduled wait is cut to what is left of the budget.
|
|
119
182
|
*/
|
|
120
|
-
|
|
183
|
+
const resendWaitMs = (args, resent, waitedMs, temporary) => {
|
|
184
|
+
if (!args.repeatable || !canResend(args.config, resent))
|
|
185
|
+
return null;
|
|
186
|
+
const left = resendBudgetMs(args.config) - waitedMs;
|
|
187
|
+
if (left <= 0)
|
|
188
|
+
return null;
|
|
189
|
+
const retryAfter = temporary === null ? 0 : retryAfterMs(temporary);
|
|
190
|
+
if (retryAfter > left)
|
|
191
|
+
return null;
|
|
192
|
+
return Math.min(Math.max(resendDelayMs(resent, args.config.random), retryAfter), left);
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* POST one prepared body. When the platform gave no answer or a temporary
|
|
196
|
+
* answer, and the call is repeatable, send the same bytes again after
|
|
197
|
+
* {@link resendWaitMs}. The resends stop at `maxTransportRetries` or when the
|
|
198
|
+
* wait budget is spent, and the last answer then goes to the caller. A final
|
|
199
|
+
* answer is never sent again.
|
|
200
|
+
*/
|
|
201
|
+
export const postWithResends = async (args, resent = 0, waitedMs = 0) => {
|
|
121
202
|
// Read the fetch out of `args` so it is not called with `args` as `this`.
|
|
122
203
|
const { runtimeFetch } = args;
|
|
123
204
|
const sendSignal = AbortSignal.timeout(args.sendTimeoutMs);
|
|
205
|
+
const headers = new Headers(args.headers);
|
|
206
|
+
if (args.repeatable)
|
|
207
|
+
headers.set(SDK_RESENDS_HEADER, "temporary");
|
|
124
208
|
let outcome = null;
|
|
125
209
|
let cut = false;
|
|
126
210
|
let lostError = null;
|
|
127
211
|
try {
|
|
128
212
|
const response = await runtimeFetch(args.url, {
|
|
129
213
|
body: args.body,
|
|
130
|
-
headers
|
|
214
|
+
headers,
|
|
131
215
|
method: "POST",
|
|
132
216
|
signal: sendSignal,
|
|
133
217
|
});
|
|
@@ -141,14 +225,21 @@ export const postWithResends = async (args, resent = 0) => {
|
|
|
141
225
|
}
|
|
142
226
|
lostError = error;
|
|
143
227
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
228
|
+
let temporary = null;
|
|
229
|
+
if (outcome !== null &&
|
|
230
|
+
!cut &&
|
|
231
|
+
!isLostResponse(outcome.response.status, outcome.body)) {
|
|
232
|
+
if (!isTemporaryAnswer(outcome.response.status, outcome.body)) {
|
|
233
|
+
return outcome;
|
|
234
|
+
}
|
|
235
|
+
temporary = outcome;
|
|
236
|
+
}
|
|
237
|
+
const delayMs = resendWaitMs(args, resent, waitedMs, temporary);
|
|
238
|
+
if (delayMs === null) {
|
|
239
|
+
if (outcome === null)
|
|
240
|
+
throw lostError;
|
|
241
|
+
return outcome;
|
|
150
242
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
return outcome;
|
|
243
|
+
await waitBeforeResend(args.config, delayMs, undefined);
|
|
244
|
+
return await postWithResends(args, resent + 1, waitedMs + delayMs);
|
|
154
245
|
};
|
package/dist/transport.d.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import type { ForceRefreshThrottle, ResolvedDamperConfig } from "./dampers.js";
|
|
19
19
|
import type { CallKeys } from "./job-run.js";
|
|
20
20
|
import type { RuntimeJsonObject } from "./transport-json.js";
|
|
21
|
-
import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeCapabilityType,
|
|
21
|
+
import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeCapabilityType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruResultDecoder } from "./types.js";
|
|
22
22
|
/** Per-client damper state: the resolved config plus the forceRefresh throttle. */
|
|
23
23
|
export interface DamperRuntime {
|
|
24
24
|
readonly config: ResolvedDamperConfig;
|
|
@@ -38,26 +38,8 @@ interface AppRuntimeInvocationHttpResponse {
|
|
|
38
38
|
pending: boolean;
|
|
39
39
|
diagnostics?: RuntimeJsonObject;
|
|
40
40
|
}
|
|
41
|
-
interface AppRuntimeExecutionHttpResponse {
|
|
42
|
-
success?: boolean;
|
|
43
|
-
pending?: boolean;
|
|
44
|
-
result?: unknown;
|
|
45
|
-
error?: string | null;
|
|
46
|
-
state?: string;
|
|
47
|
-
status?: string | null;
|
|
48
|
-
executionId?: string | null;
|
|
49
|
-
statusUrl?: string | null;
|
|
50
|
-
retryAfterSeconds?: number | null;
|
|
51
|
-
cacheStatus?: string | null;
|
|
52
|
-
executor?: string | null;
|
|
53
|
-
executorKind?: string | null;
|
|
54
|
-
code?: string | null;
|
|
55
|
-
diagnostics?: UruAppRuntimeExecutionDiagnostics;
|
|
56
|
-
}
|
|
57
41
|
/** Map the owned camelCase HTTP envelope without copying unknown fields. */
|
|
58
42
|
export declare const appRuntimeInvocationResponseFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeInvocationHttpResponse;
|
|
59
|
-
/** Map the owned camelCase job-status envelope without copying unknown fields. */
|
|
60
|
-
export declare const appRuntimeExecutionStatusFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeExecutionHttpResponse;
|
|
61
43
|
export declare const invokeAppRuntime: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType, name: string, input?: unknown, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
|
|
62
44
|
export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeExecutionStatus>;
|
|
63
45
|
export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeInvocationResponse>;
|
package/dist/transport.js
CHANGED
|
@@ -149,7 +149,7 @@ export const appRuntimeInvocationResponseFromHttp = (value, decodeResult) => {
|
|
|
149
149
|
return output;
|
|
150
150
|
};
|
|
151
151
|
/** Map the owned camelCase job-status envelope without copying unknown fields. */
|
|
152
|
-
|
|
152
|
+
const appRuntimeExecutionStatusFromHttp = (value, decodeResult) => {
|
|
153
153
|
const label = "app runtime job status";
|
|
154
154
|
const body = httpRecord(value, label);
|
|
155
155
|
const output = {
|
package/dist/types.d.ts
CHANGED
|
@@ -427,7 +427,7 @@ export type UruUploadOutcome = "verified" | "pending" | "absent" | "expired" | "
|
|
|
427
427
|
* A minted grant. `uploadUrl` is a CREDENTIAL: do not log it or store it.
|
|
428
428
|
*
|
|
429
429
|
* `requiredHeaders` is not advice. The provider rebuilds the signature from
|
|
430
|
-
* what actually arrives, so a PUT that omits or alters
|
|
430
|
+
* what actually arrives, so a PUT that omits or alters any header is
|
|
431
431
|
* refused.
|
|
432
432
|
*/
|
|
433
433
|
export interface UruUploadGrant {
|
|
@@ -452,20 +452,39 @@ export interface UruUploadResult {
|
|
|
452
452
|
/** True only when a refused object could not be removed from storage. */
|
|
453
453
|
readonly cleanupFailed: boolean;
|
|
454
454
|
}
|
|
455
|
+
export interface UruUploadStatus {
|
|
456
|
+
readonly uploadId: string;
|
|
457
|
+
readonly state: UruUploadResult['state'];
|
|
458
|
+
readonly outcome: UruUploadOutcome | null;
|
|
459
|
+
readonly filename: string;
|
|
460
|
+
readonly contentType: string;
|
|
461
|
+
readonly sizeBytes: number | null;
|
|
462
|
+
readonly expiresAt: string;
|
|
463
|
+
/** True while the platform still needs to retry object cleanup. */
|
|
464
|
+
readonly cleanupFailed: boolean;
|
|
465
|
+
}
|
|
455
466
|
/** The file-upload lane a Gem gets with the `storage` capability. */
|
|
456
467
|
export interface UruUploadsContext {
|
|
457
468
|
request(input: {
|
|
458
469
|
filename: string;
|
|
459
470
|
contentType: string;
|
|
460
471
|
sizeBytes: number;
|
|
472
|
+
/** Reuse this key after an uncertain response. The SDK also retains an
|
|
473
|
+
* automatic key when its response is uncertain. */
|
|
474
|
+
idempotencyKey?: string;
|
|
461
475
|
signal?: AbortSignal;
|
|
462
476
|
}): Promise<UruUploadGrant>;
|
|
477
|
+
/** Read the saved result for a request key without starting another upload. */
|
|
478
|
+
status(idempotencyKey: string, options?: {
|
|
479
|
+
signal?: AbortSignal;
|
|
480
|
+
}): Promise<UruUploadStatus>;
|
|
463
481
|
complete(uploadId: string, options?: {
|
|
464
482
|
signal?: AbortSignal;
|
|
465
483
|
}): Promise<UruUploadResult>;
|
|
466
484
|
/** Request, PUT and complete in one call. What almost every caller wants. */
|
|
467
485
|
upload(file: File, options?: {
|
|
468
486
|
signal?: AbortSignal;
|
|
487
|
+
idempotencyKey?: string;
|
|
469
488
|
}): Promise<UruUploadResult>;
|
|
470
489
|
/**
|
|
471
490
|
* Read one VERIFIED upload back, as a `Blob`.
|
package/dist/uploads.js
CHANGED
|
@@ -114,6 +114,8 @@ function grantFrom(value) {
|
|
|
114
114
|
for (const [name, headerValue] of Object.entries(headers)) {
|
|
115
115
|
requiredHeaders[name] = string(headerValue);
|
|
116
116
|
}
|
|
117
|
+
if (requiredHeaders['if-none-match'] !== '*')
|
|
118
|
+
invalid();
|
|
117
119
|
return {
|
|
118
120
|
uploadId,
|
|
119
121
|
uploadUrl,
|
|
@@ -148,6 +150,34 @@ function resultFrom(value) {
|
|
|
148
150
|
cleanupFailed: row['cleanupFailed'] === true,
|
|
149
151
|
};
|
|
150
152
|
}
|
|
153
|
+
function statusFrom(value) {
|
|
154
|
+
const row = object(value);
|
|
155
|
+
const state = string(row['state']);
|
|
156
|
+
const outcome = row['outcome'];
|
|
157
|
+
const sizeBytes = row['sizeBytes'];
|
|
158
|
+
if (!UUID.test(string(row['uploadId'])) ||
|
|
159
|
+
!['granted', 'verified', 'rejected', 'expired'].includes(state) ||
|
|
160
|
+
(outcome !== null && (typeof outcome !== 'string' || !OUTCOMES.includes(outcome))) ||
|
|
161
|
+
(sizeBytes !== null && (typeof sizeBytes !== 'number' || !Number.isSafeInteger(sizeBytes))) ||
|
|
162
|
+
typeof row['cleanupFailed'] !== 'boolean')
|
|
163
|
+
invalid();
|
|
164
|
+
return {
|
|
165
|
+
uploadId: string(row['uploadId']),
|
|
166
|
+
state: state,
|
|
167
|
+
outcome: outcome,
|
|
168
|
+
filename: string(row['filename']),
|
|
169
|
+
contentType: string(row['contentType']),
|
|
170
|
+
sizeBytes: sizeBytes,
|
|
171
|
+
expiresAt: string(row['expiresAt']),
|
|
172
|
+
cleanupFailed: row['cleanupFailed'],
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function requestKey(value) {
|
|
176
|
+
const key = value.trim();
|
|
177
|
+
if (key.trim().length < 1 || key.trim().length > 128)
|
|
178
|
+
invalid();
|
|
179
|
+
return key.trim();
|
|
180
|
+
}
|
|
151
181
|
/**
|
|
152
182
|
* Read the response body into a `Blob`, refusing anything above the platform's
|
|
153
183
|
* own per-file ceiling.
|
|
@@ -196,10 +226,48 @@ export function createUploadsContext(options) {
|
|
|
196
226
|
// costs nothing on a runtime whose `fetch` arrives later, and so the global
|
|
197
227
|
// is always called with the global as its receiver.
|
|
198
228
|
const doFetch = async (...args) => await resolveRuntimeFetch(options)(...args);
|
|
199
|
-
const
|
|
229
|
+
const generatedRequestKeys = new Map();
|
|
230
|
+
const generatedFileIds = new WeakMap();
|
|
231
|
+
const fileFingerprint = (file, contentType) => {
|
|
232
|
+
let fileId = generatedFileIds.get(file);
|
|
233
|
+
if (fileId === undefined) {
|
|
234
|
+
fileId = globalThis.crypto.randomUUID();
|
|
235
|
+
generatedFileIds.set(file, fileId);
|
|
236
|
+
}
|
|
237
|
+
return JSON.stringify([
|
|
238
|
+
fileId,
|
|
239
|
+
file.name,
|
|
240
|
+
contentType,
|
|
241
|
+
file.size,
|
|
242
|
+
typeof file.lastModified === 'number' ? file.lastModified : 0,
|
|
243
|
+
]);
|
|
244
|
+
};
|
|
245
|
+
const keyFor = (value, fingerprint) => {
|
|
246
|
+
if (value !== undefined)
|
|
247
|
+
return { key: requestKey(value), generated: false };
|
|
248
|
+
const existing = generatedRequestKeys.get(fingerprint);
|
|
249
|
+
if (existing !== undefined)
|
|
250
|
+
return { key: existing, generated: true };
|
|
251
|
+
const key = requestKey(globalThis.crypto.randomUUID());
|
|
252
|
+
if (generatedRequestKeys.size >= 128) {
|
|
253
|
+
const oldest = generatedRequestKeys.keys().next().value;
|
|
254
|
+
if (typeof oldest === 'string')
|
|
255
|
+
generatedRequestKeys.delete(oldest);
|
|
256
|
+
}
|
|
257
|
+
generatedRequestKeys.set(fingerprint, key);
|
|
258
|
+
return { key, generated: true };
|
|
259
|
+
};
|
|
260
|
+
const forgetGeneratedKey = (fingerprint, key) => {
|
|
261
|
+
if (generatedRequestKeys.get(fingerprint) === key) {
|
|
262
|
+
generatedRequestKeys.delete(fingerprint);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const post = async (path, payload, signal, idempotencyKey) => {
|
|
200
266
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
201
267
|
if (payload !== undefined)
|
|
202
268
|
headers.set('content-type', 'application/json');
|
|
269
|
+
if (idempotencyKey !== undefined)
|
|
270
|
+
headers.set('Idempotency-Key', idempotencyKey);
|
|
203
271
|
const response = await doFetch(`${base}${path}`, {
|
|
204
272
|
method: 'POST',
|
|
205
273
|
headers,
|
|
@@ -217,7 +285,11 @@ export function createUploadsContext(options) {
|
|
|
217
285
|
}
|
|
218
286
|
return readJson(response);
|
|
219
287
|
};
|
|
220
|
-
const
|
|
288
|
+
const requestResponse = async (input, fingerprint = JSON.stringify([
|
|
289
|
+
input.filename,
|
|
290
|
+
input.contentType,
|
|
291
|
+
input.sizeBytes,
|
|
292
|
+
])) => {
|
|
221
293
|
if (typeof input.filename !== 'string' ||
|
|
222
294
|
input.filename.trim().length < 1 ||
|
|
223
295
|
input.filename.length > 255 ||
|
|
@@ -229,12 +301,29 @@ export function createUploadsContext(options) {
|
|
|
229
301
|
input.sizeBytes > URU_UPLOAD_MAX_BYTES) {
|
|
230
302
|
invalid();
|
|
231
303
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
304
|
+
const { key, generated } = keyFor(input.idempotencyKey, fingerprint);
|
|
305
|
+
return {
|
|
306
|
+
row: object(await post('', {
|
|
307
|
+
filename: input.filename,
|
|
308
|
+
contentType: input.contentType,
|
|
309
|
+
sizeBytes: input.sizeBytes,
|
|
310
|
+
}, input.signal, key)),
|
|
311
|
+
key,
|
|
312
|
+
generated,
|
|
313
|
+
fingerprint,
|
|
314
|
+
};
|
|
315
|
+
};
|
|
316
|
+
const request = async (input) => {
|
|
317
|
+
const response = await requestResponse(input);
|
|
318
|
+
if (response.row['state'] !== undefined && response.row['state'] !== 'granted') {
|
|
319
|
+
throw new UruAppRuntimeError('This upload request is finished. Read its saved status with the same request key.', { status: 409, body: null });
|
|
320
|
+
}
|
|
321
|
+
const grant = grantFrom(response.row);
|
|
322
|
+
if (response.generated)
|
|
323
|
+
forgetGeneratedKey(response.fingerprint, response.key);
|
|
324
|
+
return grant;
|
|
237
325
|
};
|
|
326
|
+
const status = async (idempotencyKey, options) => statusFrom(await post('/status', undefined, options?.signal, requestKey(idempotencyKey)));
|
|
238
327
|
const complete = async (uploadId, settings) => {
|
|
239
328
|
if (typeof uploadId !== 'string' || !UUID.test(uploadId))
|
|
240
329
|
invalid();
|
|
@@ -264,6 +353,7 @@ export function createUploadsContext(options) {
|
|
|
264
353
|
};
|
|
265
354
|
return {
|
|
266
355
|
request,
|
|
356
|
+
status,
|
|
267
357
|
complete,
|
|
268
358
|
read,
|
|
269
359
|
upload: async (file, settings) => {
|
|
@@ -275,30 +365,79 @@ export function createUploadsContext(options) {
|
|
|
275
365
|
const contentType = typeof file.type === 'string' && file.type.trim() !== ''
|
|
276
366
|
? file.type
|
|
277
367
|
: 'application/octet-stream';
|
|
278
|
-
const
|
|
368
|
+
const response = await requestResponse({
|
|
279
369
|
filename: file.name,
|
|
280
370
|
contentType,
|
|
281
371
|
sizeBytes: file.size,
|
|
372
|
+
...(settings?.idempotencyKey === undefined
|
|
373
|
+
? {}
|
|
374
|
+
: { idempotencyKey: settings.idempotencyKey }),
|
|
282
375
|
...(settings?.signal === undefined ? {} : { signal: settings.signal }),
|
|
283
|
-
});
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
//
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
376
|
+
}, fileFingerprint(file, contentType));
|
|
377
|
+
const row = response.row;
|
|
378
|
+
if (row['state'] === 'verified' ||
|
|
379
|
+
row['state'] === 'rejected' ||
|
|
380
|
+
row['state'] === 'expired') {
|
|
381
|
+
// A prior call may have finished after its response was lost. The
|
|
382
|
+
// completion read is idempotent and returns the stored verdict.
|
|
383
|
+
const result = await complete(string(row['uploadId']), settings);
|
|
384
|
+
if (response.generated)
|
|
385
|
+
forgetGeneratedKey(response.fingerprint, response.key);
|
|
386
|
+
return result;
|
|
387
|
+
}
|
|
388
|
+
const grant = grantFrom(row);
|
|
389
|
+
const completeIfStored = async () => {
|
|
390
|
+
if (settings?.signal?.aborted === true)
|
|
391
|
+
return null;
|
|
392
|
+
try {
|
|
393
|
+
const recovered = await complete(grant.uploadId, settings);
|
|
394
|
+
return recovered.state === 'granted' && recovered.outcome === 'pending'
|
|
395
|
+
? null
|
|
396
|
+
: recovered;
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
let put;
|
|
403
|
+
try {
|
|
404
|
+
put = await doFetch(grant.uploadUrl, {
|
|
405
|
+
method: 'PUT',
|
|
406
|
+
// Exactly the headers the grant was SIGNED with. Adding or altering one
|
|
407
|
+
// changes the canonical request the provider rebuilds, and the PUT is
|
|
408
|
+
// refused with a signature error that names nothing.
|
|
409
|
+
headers: new Headers(grant.requiredHeaders),
|
|
410
|
+
body: file,
|
|
411
|
+
...(settings?.signal === undefined ? {} : { signal: settings.signal }),
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
const recovered = await completeIfStored();
|
|
416
|
+
if (recovered !== null) {
|
|
417
|
+
if (response.generated)
|
|
418
|
+
forgetGeneratedKey(response.fingerprint, response.key);
|
|
419
|
+
return recovered;
|
|
420
|
+
}
|
|
421
|
+
throw error;
|
|
422
|
+
}
|
|
293
423
|
if (!put.ok) {
|
|
294
424
|
await put.body?.cancel();
|
|
425
|
+
const recovered = await completeIfStored();
|
|
426
|
+
if (recovered !== null) {
|
|
427
|
+
if (response.generated)
|
|
428
|
+
forgetGeneratedKey(response.fingerprint, response.key);
|
|
429
|
+
return recovered;
|
|
430
|
+
}
|
|
295
431
|
throw new UruAppRuntimeError('Upload was refused by object storage.', {
|
|
296
432
|
status: put.status,
|
|
297
433
|
body: null,
|
|
298
434
|
});
|
|
299
435
|
}
|
|
300
436
|
await put.body?.cancel();
|
|
301
|
-
|
|
437
|
+
const result = await complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
|
|
438
|
+
if (response.generated)
|
|
439
|
+
forgetGeneratedKey(response.fingerprint, response.key);
|
|
440
|
+
return result;
|
|
302
441
|
},
|
|
303
442
|
};
|
|
304
443
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uru-intelligence/app",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
|
|
6
6
|
"keywords": [
|
|
@@ -28,11 +28,34 @@
|
|
|
28
28
|
"sideEffects": false,
|
|
29
29
|
"main": "./dist/index.js",
|
|
30
30
|
"types": "./dist/index.d.ts",
|
|
31
|
+
"typesVersions": {
|
|
32
|
+
"*": {
|
|
33
|
+
"examples/customer-workflows/*": [
|
|
34
|
+
"dist/examples/customer-workflows/*"
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
},
|
|
31
38
|
"exports": {
|
|
32
39
|
".": {
|
|
33
40
|
"types": "./dist/index.d.ts",
|
|
34
41
|
"default": "./dist/index.js"
|
|
35
42
|
},
|
|
43
|
+
"./examples/customer-workflows/scheduled-collector": {
|
|
44
|
+
"types": "./dist/examples/customer-workflows/scheduled-collector.d.ts",
|
|
45
|
+
"default": "./dist/examples/customer-workflows/scheduled-collector.js"
|
|
46
|
+
},
|
|
47
|
+
"./examples/customer-workflows/review-only-draft": {
|
|
48
|
+
"types": "./dist/examples/customer-workflows/review-only-draft.d.ts",
|
|
49
|
+
"default": "./dist/examples/customer-workflows/review-only-draft.js"
|
|
50
|
+
},
|
|
51
|
+
"./examples/customer-workflows/file-processor": {
|
|
52
|
+
"types": "./dist/examples/customer-workflows/file-processor.d.ts",
|
|
53
|
+
"default": "./dist/examples/customer-workflows/file-processor.js"
|
|
54
|
+
},
|
|
55
|
+
"./examples/customer-workflows/approved-external-write": {
|
|
56
|
+
"types": "./dist/examples/customer-workflows/approved-external-write.d.ts",
|
|
57
|
+
"default": "./dist/examples/customer-workflows/approved-external-write.js"
|
|
58
|
+
},
|
|
36
59
|
"./package.json": "./package.json"
|
|
37
60
|
},
|
|
38
61
|
"publishConfig": {
|
|
@@ -40,16 +63,18 @@
|
|
|
40
63
|
"provenance": false
|
|
41
64
|
},
|
|
42
65
|
"scripts": {
|
|
43
|
-
"build": "tsc -p tsconfig.build.json",
|
|
66
|
+
"build": "tsc -p tsconfig.build.json && tsc -p tsconfig.examples.build.json",
|
|
44
67
|
"clean": "rm -rf dist",
|
|
45
68
|
"prepack": "bun run clean && bun run build",
|
|
46
|
-
"type-check": "tsc --noEmit",
|
|
47
|
-
"lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts .",
|
|
69
|
+
"type-check": "tsc --noEmit && tsc -p tsconfig.examples.json --noEmit",
|
|
70
|
+
"lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts . && node ../../scripts/checks/check-bun-test-integrity.mjs",
|
|
48
71
|
"lint:fix": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts --fix .",
|
|
49
|
-
"test": "bun test",
|
|
50
|
-
"test:unit": "bun test",
|
|
72
|
+
"test": "bun run test:safety",
|
|
73
|
+
"test:unit": "bun run test:safety",
|
|
74
|
+
"test:safety": "node ../../scripts/ci/run-named-test-files.mjs bun test --files-from test-lists/test-safety.txt",
|
|
51
75
|
"check:package": "node ../../scripts/checks/check-app-package-publishable.mjs",
|
|
52
|
-
"check:node-floor": "node ../../scripts/checks/check-app-package-node-floor.mjs"
|
|
76
|
+
"check:node-floor": "node ../../scripts/checks/check-app-package-node-floor.mjs",
|
|
77
|
+
"test:focused": "node ../../scripts/ci/run-named-test-files.mjs bun test --files"
|
|
53
78
|
},
|
|
54
79
|
"devDependencies": {
|
|
55
80
|
"@types/node": "24.13.3",
|