@uru-intelligence/app 2.0.0 → 2.1.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 +84 -4
- package/dist/datasets.js +3 -8
- package/dist/files.d.ts +2 -0
- package/dist/files.js +149 -0
- package/dist/index.d.ts +22 -6
- package/dist/index.js +47 -7
- package/dist/jobs.d.ts +4 -0
- package/dist/jobs.js +35 -0
- package/dist/runtime.d.ts +23 -2
- package/dist/runtime.js +36 -2
- package/dist/transport-json.d.ts +2 -0
- package/dist/transport-json.js +11 -2
- package/dist/transport.js +6 -14
- package/dist/types.d.ts +98 -0
- package/dist/uploads.d.ts +32 -0
- package/dist/uploads.js +231 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -76,6 +76,54 @@ and `URU_RUNTIME_TOKEN`. The Uru runtime injects all three. A missing binding
|
|
|
76
76
|
throws `UruAppRuntimeError` naming the binding, rather than failing later at a
|
|
77
77
|
request that could never have worked.
|
|
78
78
|
|
|
79
|
+
## Program job handlers
|
|
80
|
+
|
|
81
|
+
A Gem can declare a job that runs code from its published source:
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"capabilities": {
|
|
86
|
+
"jobs": {
|
|
87
|
+
"sync_orders": {
|
|
88
|
+
"handler": { "module": "src/jobs.ts", "export": "syncOrders" }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The handler receives the injected environment, saved input, the last
|
|
96
|
+
checkpoint, and an abort signal. Use the server context to report progress and
|
|
97
|
+
save small resume data after each completed write:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import {
|
|
101
|
+
createUruServerContext,
|
|
102
|
+
type UruJobCheckpoint,
|
|
103
|
+
type UruProviderRuntimeEnvironment,
|
|
104
|
+
} from '@uru-intelligence/app';
|
|
105
|
+
|
|
106
|
+
export async function syncOrders(
|
|
107
|
+
env: UruProviderRuntimeEnvironment,
|
|
108
|
+
input: { source: string },
|
|
109
|
+
checkpoint: UruJobCheckpoint | null,
|
|
110
|
+
signal: AbortSignal,
|
|
111
|
+
) {
|
|
112
|
+
const uru = createUruServerContext(env);
|
|
113
|
+
if (signal.aborted) return { processed: 0 };
|
|
114
|
+
|
|
115
|
+
await saveNextBatch(uru, input.source, checkpoint, signal);
|
|
116
|
+
await uru.jobs.progress({ completed: 1, message: 'Batch saved' });
|
|
117
|
+
await uru.jobs.checkpoint({ source: input.source, processed: 1 });
|
|
118
|
+
return { processed: 1 };
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`saveNextBatch` is Gem code. Check `signal.aborted` before each external write.
|
|
123
|
+
Make writes safe to repeat. Keep progress messages and checkpoints small. Do
|
|
124
|
+
not put secrets or source rows in them. A progress update does not complete a
|
|
125
|
+
job. The handler completes the job when it returns.
|
|
126
|
+
|
|
79
127
|
For a browser calling a public Gem page's runtime, build the client directly:
|
|
80
128
|
|
|
81
129
|
```ts
|
|
@@ -172,6 +220,38 @@ Capability and job-status envelopes can omit `result` or return `null` while
|
|
|
172
220
|
work is pending. The client preserves both forms without calling the decoder.
|
|
173
221
|
Typed callers must still handle an absent or null result.
|
|
174
222
|
|
|
223
|
+
## Files
|
|
224
|
+
|
|
225
|
+
Declare Library file IDs in `uru.json` under `bindings.files`. Each file needs
|
|
226
|
+
its own approved grant. Read access does not permit changes to the file.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
const source = await uru.files.read(fileId, { signal });
|
|
230
|
+
// source.content is a Uint8Array. Library reads are limited to 5 MiB.
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Set `fileOutputs: true` in `uru.json` to request permission to create output
|
|
234
|
+
files. Output permission is separate from Library read permission and app
|
|
235
|
+
storage. Reuse the same key when you repeat a write after an uncertain result.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
const created = await uru.files.createOutput({
|
|
239
|
+
name: 'summary.txt',
|
|
240
|
+
contentType: 'text/plain',
|
|
241
|
+
content: new TextEncoder().encode('Completed work'),
|
|
242
|
+
idempotencyKey: `summary:${batchId}`,
|
|
243
|
+
signal,
|
|
244
|
+
});
|
|
245
|
+
const saved = await uru.files.readOutput(created.outputId, { signal });
|
|
246
|
+
const page = await uru.files.listOutputs({ limit: 25, signal });
|
|
247
|
+
const nextPage = page.nextCursor === null ? null
|
|
248
|
+
: await uru.files.listOutputs({ cursor: page.nextCursor, limit: 25, signal });
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Output reads and writes are limited to 10 MiB. Later approved releases of the
|
|
252
|
+
same Gem can read its outputs in the same environment. Preview builds cannot
|
|
253
|
+
create unattended outputs. Every request checks current access.
|
|
254
|
+
|
|
175
255
|
## Errors
|
|
176
256
|
|
|
177
257
|
Transport and platform failures throw `UruAppRuntimeError`. Decoder failures
|
|
@@ -194,10 +274,10 @@ try {
|
|
|
194
274
|
|
|
195
275
|
## Stability
|
|
196
276
|
|
|
197
|
-
Semantic versioning
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
277
|
+
Semantic versioning applies. A breaking change to the public surface takes a
|
|
278
|
+
major version. The package is already load-bearing:
|
|
279
|
+
every hosted Uru Gem runs against it, so breaking it is expensive whatever the
|
|
280
|
+
version number claims.
|
|
201
281
|
|
|
202
282
|
The API still follows the Uru platform rather than the other way round. When the
|
|
203
283
|
platform's runtime contract moves, this package moves with it — additively where
|
package/dist/datasets.js
CHANGED
|
@@ -8,15 +8,9 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { datasetIdsForRequest, datasetRowIdsForRequest, datasetRowsForRequest, decodeDatasetMutationResult, decodeDatasetRowsResult, decodeDefaultDatasetMutationResult, decodeDefaultDatasetRowsResult, datasetWriteErrorMessage, serializeDatasetRequest, } from "./dataset-boundary.js";
|
|
10
10
|
import { UruAppRuntimeError } from "./errors.js";
|
|
11
|
-
import { requireCompletedRuntimeResponse, resolveHeaders, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
11
|
+
import { requireCompletedRuntimeResponse, resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
12
12
|
const fetchDatasetWrite = async (options, subpath, body) => {
|
|
13
|
-
const runtimeFetch = options
|
|
14
|
-
if (typeof runtimeFetch !== "function") {
|
|
15
|
-
throw new UruAppRuntimeError("Uru app runtime fetch is not available.", {
|
|
16
|
-
body: null,
|
|
17
|
-
status: 0,
|
|
18
|
-
});
|
|
19
|
-
}
|
|
13
|
+
const runtimeFetch = resolveRuntimeFetch(options);
|
|
20
14
|
const deploymentId = typeof options.deploymentId === "string" ? options.deploymentId.trim() : "";
|
|
21
15
|
if (!deploymentId) {
|
|
22
16
|
throw new UruAppRuntimeError("Uru app runtime deployment id is required.", {
|
|
@@ -35,6 +29,7 @@ const fetchDatasetWrite = async (options, subpath, body) => {
|
|
|
35
29
|
body: serializedBody,
|
|
36
30
|
headers,
|
|
37
31
|
method: "POST",
|
|
32
|
+
signal: AbortSignal.timeout(30_000),
|
|
38
33
|
});
|
|
39
34
|
const parsed = await response.json().catch(() => null);
|
|
40
35
|
if (!response.ok) {
|
package/dist/files.d.ts
ADDED
package/dist/files.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { UruAppRuntimeError } from './errors.js';
|
|
2
|
+
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash } from './runtime.js';
|
|
3
|
+
import { isRuntimeJsonObject } from './transport-json.js';
|
|
4
|
+
const LIBRARY_READ_BYTES = 5 * 1024 * 1024;
|
|
5
|
+
const OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
6
|
+
const RESPONSE_BYTES = Math.ceil(OUTPUT_BYTES / 3) * 4 + 8192;
|
|
7
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8
|
+
const HASH = /^[0-9a-f]{64}$/;
|
|
9
|
+
function invalid() {
|
|
10
|
+
throw new UruAppRuntimeError('Invalid file request or response.', { status: 0, body: null });
|
|
11
|
+
}
|
|
12
|
+
const identifier = (value) => typeof value === 'string' && UUID.test(value) ? value : invalid();
|
|
13
|
+
const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
|
|
14
|
+
const string = (value) => typeof value === 'string' ? value : invalid();
|
|
15
|
+
function metadata(value, maxBytes) {
|
|
16
|
+
const sizeBytes = value['sizeBytes'];
|
|
17
|
+
const filename = string(value['filename']);
|
|
18
|
+
const contentType = string(value['contentType']);
|
|
19
|
+
const sha256 = string(value['sha256']);
|
|
20
|
+
if (typeof sizeBytes !== 'number' || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0 || sizeBytes > maxBytes ||
|
|
21
|
+
filename.length < 1 || filename.length > 255 || contentType.length < 1 || contentType.length > 255 || !HASH.test(sha256))
|
|
22
|
+
invalid();
|
|
23
|
+
return { fileId: identifier(string(value['fileId'])), filename, contentType, sizeBytes, sha256 };
|
|
24
|
+
}
|
|
25
|
+
function output(value) {
|
|
26
|
+
const row = object(value);
|
|
27
|
+
const createdAt = string(row['createdAt']);
|
|
28
|
+
if (!Number.isFinite(Date.parse(createdAt)))
|
|
29
|
+
invalid();
|
|
30
|
+
return { ...metadata(row, OUTPUT_BYTES), outputId: identifier(string(row['outputId'])), createdAt };
|
|
31
|
+
}
|
|
32
|
+
function content(value, maxBytes) {
|
|
33
|
+
const row = object(value);
|
|
34
|
+
const meta = metadata(row, maxBytes);
|
|
35
|
+
const encoded = string(row['contentBase64']);
|
|
36
|
+
if (encoded.length > Math.ceil(maxBytes / 3) * 4 ||
|
|
37
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))
|
|
38
|
+
invalid();
|
|
39
|
+
let decoded;
|
|
40
|
+
try {
|
|
41
|
+
decoded = atob(encoded);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return invalid();
|
|
45
|
+
}
|
|
46
|
+
if (decoded.length !== meta.sizeBytes)
|
|
47
|
+
invalid();
|
|
48
|
+
return { ...meta, content: Uint8Array.from(decoded, character => character.charCodeAt(0)) };
|
|
49
|
+
}
|
|
50
|
+
function base64(bytes) {
|
|
51
|
+
let binary = '';
|
|
52
|
+
for (let offset = 0; offset < bytes.length; offset += 8192) {
|
|
53
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
|
54
|
+
}
|
|
55
|
+
return btoa(binary);
|
|
56
|
+
}
|
|
57
|
+
async function readJson(response) {
|
|
58
|
+
const reader = response.body?.getReader();
|
|
59
|
+
if (reader === undefined)
|
|
60
|
+
invalid();
|
|
61
|
+
const decoder = new TextDecoder();
|
|
62
|
+
let size = 0;
|
|
63
|
+
let text = '';
|
|
64
|
+
try {
|
|
65
|
+
for (;;) {
|
|
66
|
+
const chunk = await reader.read();
|
|
67
|
+
if (chunk.done)
|
|
68
|
+
break;
|
|
69
|
+
size += chunk.value.byteLength;
|
|
70
|
+
if (size > RESPONSE_BYTES) {
|
|
71
|
+
await reader.cancel();
|
|
72
|
+
invalid();
|
|
73
|
+
}
|
|
74
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
75
|
+
}
|
|
76
|
+
text += decoder.decode();
|
|
77
|
+
return JSON.parse(text);
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error instanceof UruAppRuntimeError)
|
|
81
|
+
throw error;
|
|
82
|
+
return invalid();
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
reader.releaseLock();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function createFilesContext(options) {
|
|
89
|
+
const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/files`;
|
|
90
|
+
const request = async (path, payload, signal) => {
|
|
91
|
+
const headers = new Headers(await resolveHeaders(options.headers));
|
|
92
|
+
if (payload !== undefined)
|
|
93
|
+
headers.set('content-type', 'application/json');
|
|
94
|
+
const response = await resolveRuntimeFetch(options)(`${base}${path}`, {
|
|
95
|
+
method: payload === undefined ? 'GET' : 'POST', headers,
|
|
96
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
97
|
+
signal: signal === undefined ? AbortSignal.timeout(30_000) : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
98
|
+
});
|
|
99
|
+
if (!response.ok) {
|
|
100
|
+
await response.body?.cancel();
|
|
101
|
+
throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body: null });
|
|
102
|
+
}
|
|
103
|
+
return readJson(response);
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
read: async (fileId, settings) => content(await request(`/${identifier(fileId)}`, undefined, settings?.signal), LIBRARY_READ_BYTES),
|
|
107
|
+
readOutput: async (outputId, settings) => content(await request(`/outputs/${identifier(outputId)}`, undefined, settings?.signal), OUTPUT_BYTES),
|
|
108
|
+
createOutput: async (input) => {
|
|
109
|
+
if (!(input.content instanceof Uint8Array) || input.content.byteLength > OUTPUT_BYTES ||
|
|
110
|
+
typeof input.name !== 'string' || typeof input.contentType !== 'string' || typeof input.idempotencyKey !== 'string' ||
|
|
111
|
+
input.name.trim().length < 1 || input.name.length > 255 ||
|
|
112
|
+
input.contentType.trim().length < 1 || input.contentType.length > 255 ||
|
|
113
|
+
input.idempotencyKey.trim().length < 1 || input.idempotencyKey.length > 128 ||
|
|
114
|
+
(input.sha256 !== undefined && !HASH.test(input.sha256)))
|
|
115
|
+
invalid();
|
|
116
|
+
return output(await request('/outputs', {
|
|
117
|
+
name: input.name, contentType: input.contentType, contentBase64: base64(input.content),
|
|
118
|
+
idempotencyKey: input.idempotencyKey,
|
|
119
|
+
...(input.sha256 === undefined ? {} : { sha256: input.sha256 }),
|
|
120
|
+
}, input.signal));
|
|
121
|
+
},
|
|
122
|
+
listOutputs: async (settings = {}) => {
|
|
123
|
+
if (settings.limit !== undefined && (!Number.isInteger(settings.limit) || settings.limit < 1 || settings.limit > 100))
|
|
124
|
+
invalid();
|
|
125
|
+
if (settings.cursor !== undefined && (typeof settings.cursor !== 'string' || settings.cursor.length === 0 || settings.cursor.length > 4096))
|
|
126
|
+
invalid();
|
|
127
|
+
const params = new URLSearchParams();
|
|
128
|
+
if (settings.cursor !== undefined)
|
|
129
|
+
params.set('cursor', settings.cursor);
|
|
130
|
+
if (settings.limit !== undefined)
|
|
131
|
+
params.set('limit', String(settings.limit));
|
|
132
|
+
const result = object(await request(`/outputs${params.size === 0 ? '' : `?${params}`}`, undefined, settings.signal));
|
|
133
|
+
const values = result['items'];
|
|
134
|
+
if (!Array.isArray(values) || values.length > (settings.limit ?? 100))
|
|
135
|
+
invalid();
|
|
136
|
+
const items = values.map(value => {
|
|
137
|
+
const row = object(value);
|
|
138
|
+
return { ...output(row),
|
|
139
|
+
releaseId: row['releaseId'] === null ? null : identifier(string(row['releaseId'])),
|
|
140
|
+
buildId: row['buildId'] === null ? null : identifier(string(row['buildId'])),
|
|
141
|
+
};
|
|
142
|
+
});
|
|
143
|
+
const nextCursor = result['nextCursor'] === null ? null : string(result['nextCursor']);
|
|
144
|
+
if (nextCursor !== null && (nextCursor.length === 0 || nextCursor.length > 4096))
|
|
145
|
+
invalid();
|
|
146
|
+
return { items, nextCursor };
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,16 +11,19 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeClient, UruProviderRuntimeEnvironment, UruServerContext } from "./types.js";
|
|
13
13
|
export { UruAppRuntimeError } from "./errors.js";
|
|
14
|
+
export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
|
|
14
15
|
export type { UruRunawayDamperOptions } from "./dampers.js";
|
|
15
|
-
export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruProviderRuntimeEnvironment, UruServerContext, } from "./types.js";
|
|
16
|
+
export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, 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";
|
|
16
17
|
/**
|
|
17
18
|
* Build a capability-invocation client against a Uru app runtime.
|
|
18
19
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* secrets on top
|
|
22
|
-
*
|
|
23
|
-
*
|
|
20
|
+
* {@link createUruServerContext} is the easier way to get one from a request
|
|
21
|
+
* handler's own environment bindings, and it also adds Datasets, actions,
|
|
22
|
+
* jobs and secrets on top — but only where a runtime token actually reaches
|
|
23
|
+
* that handler (see its own doc comment; a serverful Gem's request handler is
|
|
24
|
+
* the one place it never does). Use this directly when the caller already
|
|
25
|
+
* knows its deployment id and how to authenticate — a browser calling a
|
|
26
|
+
* public page's runtime, for example.
|
|
24
27
|
*/
|
|
25
28
|
export declare const createUruAppRuntimeClient: (options: CreateUruAppRuntimeClientOptions) => UruAppRuntimeClient;
|
|
26
29
|
/**
|
|
@@ -31,5 +34,18 @@ export declare const createUruAppRuntimeClient: (options: CreateUruAppRuntimeCli
|
|
|
31
34
|
* required and are injected by the Uru runtime. A missing one throws
|
|
32
35
|
* {@link UruAppRuntimeError} naming the binding, rather than failing later at a
|
|
33
36
|
* request that could not have worked.
|
|
37
|
+
*
|
|
38
|
+
* **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
|
|
39
|
+
* this does not run everywhere a Gem's own code runs:**
|
|
40
|
+
*
|
|
41
|
+
* - A Cloudflare Worker Gem always has it, at every request.
|
|
42
|
+
* - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
|
|
43
|
+
* deliberately left out of that deployment's environment, and the guest
|
|
44
|
+
* refuses to even boot if one is somehow present — so calling this from a
|
|
45
|
+
* Fly `server_web_app` request handler throws every time, not just
|
|
46
|
+
* sometimes. Do the work in a program job instead.
|
|
47
|
+
* - A program job is unaffected either way: it runs on its own dedicated
|
|
48
|
+
* Machine, which is provisioned with its own token regardless of the app's
|
|
49
|
+
* hosting class.
|
|
34
50
|
*/
|
|
35
51
|
export declare const createUruServerContext: (env: UruProviderRuntimeEnvironment, options?: CreateUruServerContextOptions) => UruServerContext;
|
package/dist/index.js
CHANGED
|
@@ -11,9 +11,12 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
|
|
13
13
|
import { createDatasetsContext } from "./datasets.js";
|
|
14
|
+
import { createFilesContext } from './files.js';
|
|
15
|
+
import { createJobProgress, createJobCheckpoint } from './jobs.js';
|
|
14
16
|
import { UruAppRuntimeError } from "./errors.js";
|
|
15
17
|
import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
|
|
16
18
|
export { UruAppRuntimeError } from "./errors.js";
|
|
19
|
+
export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
|
|
17
20
|
const ownEnvironmentValue = (env, key) => {
|
|
18
21
|
if (!Object.hasOwn(env, key)) {
|
|
19
22
|
return undefined;
|
|
@@ -21,10 +24,27 @@ const ownEnvironmentValue = (env, key) => {
|
|
|
21
24
|
const value = env[key];
|
|
22
25
|
return typeof value === "string" ? value : undefined;
|
|
23
26
|
};
|
|
24
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Read a required runtime binding, or throw naming the one that is missing.
|
|
29
|
+
*
|
|
30
|
+
* `URU_RUNTIME_TOKEN` gets its own message: on a serverful (Fly) Gem's
|
|
31
|
+
* request handler, this binding is not merely unset by accident — that
|
|
32
|
+
* hosting class never carries it at request time (see
|
|
33
|
+
* {@link createUruServerContext}'s own doc comment for exactly which classes
|
|
34
|
+
* do), so "missing" would read as a fixable configuration bug when it is
|
|
35
|
+
* actually the platform's own design.
|
|
36
|
+
*/
|
|
25
37
|
const requiredRuntimeEnv = (env, key) => {
|
|
26
38
|
const value = (ownEnvironmentValue(env, key) ?? "").trim();
|
|
27
39
|
if (value === "") {
|
|
40
|
+
if (key === "URU_RUNTIME_TOKEN") {
|
|
41
|
+
throw new UruAppRuntimeError("This hosting class does not carry a runtime token at request time, " +
|
|
42
|
+
"so createUruServerContext cannot run here. A serverful (Fly) Gem's " +
|
|
43
|
+
"request handler never receives one, by design; a Cloudflare Worker " +
|
|
44
|
+
"Gem always does. If this code needs platform capabilities, run it " +
|
|
45
|
+
"from a program job instead — a program job runs on its own " +
|
|
46
|
+
"dedicated Machine with its own token, regardless of hosting class.", { body: null, status: 0 });
|
|
47
|
+
}
|
|
28
48
|
throw new UruAppRuntimeError(`Missing Uru runtime binding: ${key}`, {
|
|
29
49
|
body: null,
|
|
30
50
|
status: 0,
|
|
@@ -46,11 +66,13 @@ const normalizedSecretName = (name) => {
|
|
|
46
66
|
/**
|
|
47
67
|
* Build a capability-invocation client against a Uru app runtime.
|
|
48
68
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* secrets on top
|
|
52
|
-
*
|
|
53
|
-
*
|
|
69
|
+
* {@link createUruServerContext} is the easier way to get one from a request
|
|
70
|
+
* handler's own environment bindings, and it also adds Datasets, actions,
|
|
71
|
+
* jobs and secrets on top — but only where a runtime token actually reaches
|
|
72
|
+
* that handler (see its own doc comment; a serverful Gem's request handler is
|
|
73
|
+
* the one place it never does). Use this directly when the caller already
|
|
74
|
+
* knows its deployment id and how to authenticate — a browser calling a
|
|
75
|
+
* public page's runtime, for example.
|
|
54
76
|
*/
|
|
55
77
|
export const createUruAppRuntimeClient = (options) => {
|
|
56
78
|
// One damper runtime per client: the resolved config plus the forceRefresh
|
|
@@ -77,6 +99,19 @@ export const createUruAppRuntimeClient = (options) => {
|
|
|
77
99
|
* required and are injected by the Uru runtime. A missing one throws
|
|
78
100
|
* {@link UruAppRuntimeError} naming the binding, rather than failing later at a
|
|
79
101
|
* request that could not have worked.
|
|
102
|
+
*
|
|
103
|
+
* **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
|
|
104
|
+
* this does not run everywhere a Gem's own code runs:**
|
|
105
|
+
*
|
|
106
|
+
* - A Cloudflare Worker Gem always has it, at every request.
|
|
107
|
+
* - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
|
|
108
|
+
* deliberately left out of that deployment's environment, and the guest
|
|
109
|
+
* refuses to even boot if one is somehow present — so calling this from a
|
|
110
|
+
* Fly `server_web_app` request handler throws every time, not just
|
|
111
|
+
* sometimes. Do the work in a program job instead.
|
|
112
|
+
* - A program job is unaffected either way: it runs on its own dedicated
|
|
113
|
+
* Machine, which is provisioned with its own token regardless of the app's
|
|
114
|
+
* hosting class.
|
|
80
115
|
*/
|
|
81
116
|
export const createUruServerContext = (env, options = {}) => {
|
|
82
117
|
const deploymentId = requiredRuntimeEnv(env, "URU_DEPLOYMENT_ID");
|
|
@@ -98,7 +133,12 @@ export const createUruServerContext = (env, options = {}) => {
|
|
|
98
133
|
actions: { run: createActionInvoker(app) },
|
|
99
134
|
app,
|
|
100
135
|
datasets: createDatasetsContext(app, clientOptions),
|
|
101
|
-
|
|
136
|
+
files: createFilesContext(clientOptions),
|
|
137
|
+
jobs: {
|
|
138
|
+
start: app.job,
|
|
139
|
+
progress: createJobProgress(clientOptions, env),
|
|
140
|
+
checkpoint: createJobCheckpoint(clientOptions, env),
|
|
141
|
+
},
|
|
102
142
|
secrets: {
|
|
103
143
|
get: (name) => {
|
|
104
144
|
const key = normalizedSecretName(name);
|
package/dist/jobs.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { RuntimeJsonObject } from './transport-json.js';
|
|
2
|
+
import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment } from './types.js';
|
|
3
|
+
export declare const createJobProgress: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (progress: UruJobProgress) => Promise<void>;
|
|
4
|
+
export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (value: RuntimeJsonObject) => Promise<void>;
|
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { UruAppRuntimeError } from './errors.js';
|
|
2
|
+
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash } from './runtime.js';
|
|
3
|
+
import { isRuntimeJsonObject } from './transport-json.js';
|
|
4
|
+
const postJobUpdate = async (options, env, operation, payload) => {
|
|
5
|
+
const runId = Object.hasOwn(env, 'URU_JOB_RUN_ID') ? env['URU_JOB_RUN_ID']?.trim() : undefined;
|
|
6
|
+
const attemptId = Object.hasOwn(env, 'URU_JOB_ATTEMPT_ID') ? env['URU_JOB_ATTEMPT_ID']?.trim() : undefined;
|
|
7
|
+
if (!runId || !attemptId) {
|
|
8
|
+
throw new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
|
|
9
|
+
}
|
|
10
|
+
const headers = new Headers(await resolveHeaders(options.headers));
|
|
11
|
+
headers.set('content-type', 'application/json');
|
|
12
|
+
const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
|
|
13
|
+
const response = await resolveRuntimeFetch(options)(url, {
|
|
14
|
+
method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000),
|
|
15
|
+
});
|
|
16
|
+
if (!response.ok) {
|
|
17
|
+
await response.body?.cancel();
|
|
18
|
+
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
|
|
19
|
+
}
|
|
20
|
+
await response.body?.cancel();
|
|
21
|
+
};
|
|
22
|
+
export const createJobProgress = (options, env) => async (progress) => {
|
|
23
|
+
if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
|
|
24
|
+
(progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
|
|
25
|
+
(progress.message !== undefined && typeof progress.message !== 'string')) {
|
|
26
|
+
throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
|
|
27
|
+
}
|
|
28
|
+
await postJobUpdate(options, env, 'progress', progress);
|
|
29
|
+
};
|
|
30
|
+
export const createJobCheckpoint = (options, env) => async (value) => {
|
|
31
|
+
if (!isRuntimeJsonObject(value)) {
|
|
32
|
+
throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
|
|
33
|
+
}
|
|
34
|
+
await postJobUpdate(options, env, 'checkpoint', { value });
|
|
35
|
+
};
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Shared runtime primitives: URL assembly, header resolution
|
|
3
|
-
* completed-response assertion
|
|
2
|
+
* Shared runtime primitives: URL assembly, header resolution, the
|
|
3
|
+
* completed-response assertion, and the one `fetch` resolver every module here
|
|
4
|
+
* calls the network through.
|
|
4
5
|
*
|
|
5
6
|
* INTERNAL. Nothing here is re-exported by `index.ts`. These four functions
|
|
6
7
|
* used to be public exports of the barrel for one reason only — `transport.ts`
|
|
@@ -30,3 +31,23 @@ export declare const resolveHeaders: (headers: CreateUruAppRuntimeClientOptions[
|
|
|
30
31
|
* than a state to render.
|
|
31
32
|
*/
|
|
32
33
|
export declare const requireCompletedRuntimeResponse: (responsePromise: Promise<UruAppRuntimeInvocationResponse>) => Promise<unknown>;
|
|
34
|
+
/** The `fetch` shape the transport calls. Exactly the caller-supplied option. */
|
|
35
|
+
export type RuntimeFetch = NonNullable<CreateUruAppRuntimeClientOptions["fetch"]>;
|
|
36
|
+
/**
|
|
37
|
+
* The one `fetch` every runtime call in this package goes through.
|
|
38
|
+
*
|
|
39
|
+
* The returned function MUST stay a wrapper around `globalThis.fetch` rather
|
|
40
|
+
* than the global itself. Holding the global in a variable and calling it from
|
|
41
|
+
* there drops its receiver, and a host that checks the receiver refuses the
|
|
42
|
+
* call: Cloudflare Workers answers
|
|
43
|
+
*
|
|
44
|
+
* Illegal invocation: function called with incorrect `this` reference
|
|
45
|
+
*
|
|
46
|
+
* and browsers throw the same kind of TypeError. The wrapper reads
|
|
47
|
+
* `globalThis.fetch` at CALL time, so `this` is the global object, which is
|
|
48
|
+
* what the host demands.
|
|
49
|
+
*
|
|
50
|
+
* `.bind` is deliberately not used: it would read the global once, at resolve
|
|
51
|
+
* time, and a runtime that installs `fetch` later would be captured as missing.
|
|
52
|
+
*/
|
|
53
|
+
export declare const resolveRuntimeFetch: (options: CreateUruAppRuntimeClientOptions) => RuntimeFetch;
|
package/dist/runtime.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Shared runtime primitives: URL assembly, header resolution
|
|
3
|
-
* completed-response assertion
|
|
2
|
+
* Shared runtime primitives: URL assembly, header resolution, the
|
|
3
|
+
* completed-response assertion, and the one `fetch` resolver every module here
|
|
4
|
+
* calls the network through.
|
|
4
5
|
*
|
|
5
6
|
* INTERNAL. Nothing here is re-exported by `index.ts`. These four functions
|
|
6
7
|
* used to be public exports of the barrel for one reason only — `transport.ts`
|
|
@@ -69,3 +70,36 @@ export const requireCompletedRuntimeResponse = async (responsePromise) => {
|
|
|
69
70
|
}
|
|
70
71
|
return response.result;
|
|
71
72
|
};
|
|
73
|
+
/**
|
|
74
|
+
* The one `fetch` every runtime call in this package goes through.
|
|
75
|
+
*
|
|
76
|
+
* The returned function MUST stay a wrapper around `globalThis.fetch` rather
|
|
77
|
+
* than the global itself. Holding the global in a variable and calling it from
|
|
78
|
+
* there drops its receiver, and a host that checks the receiver refuses the
|
|
79
|
+
* call: Cloudflare Workers answers
|
|
80
|
+
*
|
|
81
|
+
* Illegal invocation: function called with incorrect `this` reference
|
|
82
|
+
*
|
|
83
|
+
* and browsers throw the same kind of TypeError. The wrapper reads
|
|
84
|
+
* `globalThis.fetch` at CALL time, so `this` is the global object, which is
|
|
85
|
+
* what the host demands.
|
|
86
|
+
*
|
|
87
|
+
* `.bind` is deliberately not used: it would read the global once, at resolve
|
|
88
|
+
* time, and a runtime that installs `fetch` later would be captured as missing.
|
|
89
|
+
*/
|
|
90
|
+
export const resolveRuntimeFetch = (options) => {
|
|
91
|
+
// A caller's own `fetch` is returned exactly as given, EXCEPT when the caller
|
|
92
|
+
// handed us the global itself — `{ fetch: globalThis.fetch }` is the obvious
|
|
93
|
+
// thing for a Gem to write, and it needs the same receiver the global always
|
|
94
|
+
// needs.
|
|
95
|
+
if (options.fetch !== undefined && options.fetch !== globalThis.fetch) {
|
|
96
|
+
return options.fetch;
|
|
97
|
+
}
|
|
98
|
+
if (typeof globalThis.fetch !== "function") {
|
|
99
|
+
throw new UruAppRuntimeError("Uru app runtime fetch is not available.", {
|
|
100
|
+
body: null,
|
|
101
|
+
status: 0,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return async (...args) => await globalThis.fetch(...args);
|
|
105
|
+
};
|
package/dist/transport-json.d.ts
CHANGED
|
@@ -3,5 +3,7 @@ export type RuntimeJsonValue = boolean | null | number | string | RuntimeJsonVal
|
|
|
3
3
|
[key: string]: RuntimeJsonValue;
|
|
4
4
|
};
|
|
5
5
|
export type RuntimeJsonObject = Record<string, RuntimeJsonValue>;
|
|
6
|
+
/** Keep later JSON.stringify calls below the JavaScript stack limit. */
|
|
7
|
+
export declare const RUNTIME_JSON_NESTING_DEPTH_MAX = 64;
|
|
6
8
|
/** Validate without invoking getters or recursing on the JavaScript call stack. */
|
|
7
9
|
export declare const isRuntimeJsonObject: (value: unknown) => value is RuntimeJsonObject;
|
package/dist/transport-json.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Keep later JSON.stringify calls below the JavaScript stack limit. */
|
|
2
|
+
export const RUNTIME_JSON_NESTING_DEPTH_MAX = 64;
|
|
1
3
|
const isJsonPrimitive = (value) => value === null ||
|
|
2
4
|
typeof value === "string" ||
|
|
3
5
|
typeof value === "boolean" ||
|
|
@@ -49,7 +51,7 @@ const inspectRuntimeJsonObject = (value) => {
|
|
|
49
51
|
return false;
|
|
50
52
|
}
|
|
51
53
|
const ancestors = new WeakSet();
|
|
52
|
-
const frames = [{ phase: "enter", value }];
|
|
54
|
+
const frames = [{ phase: "enter", value, depth: 0 }];
|
|
53
55
|
while (frames.length > 0) {
|
|
54
56
|
const frame = frames.pop();
|
|
55
57
|
if (frame === undefined) {
|
|
@@ -60,6 +62,9 @@ const inspectRuntimeJsonObject = (value) => {
|
|
|
60
62
|
continue;
|
|
61
63
|
}
|
|
62
64
|
const candidate = frame.value;
|
|
65
|
+
if (frame.depth > RUNTIME_JSON_NESTING_DEPTH_MAX) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
63
68
|
if (isJsonPrimitive(candidate)) {
|
|
64
69
|
continue;
|
|
65
70
|
}
|
|
@@ -75,7 +80,11 @@ const inspectRuntimeJsonObject = (value) => {
|
|
|
75
80
|
ancestors.add(candidate);
|
|
76
81
|
frames.push({ phase: "leave", value: candidate });
|
|
77
82
|
for (const property of properties) {
|
|
78
|
-
frames.push({
|
|
83
|
+
frames.push({
|
|
84
|
+
phase: "enter",
|
|
85
|
+
value: property.value,
|
|
86
|
+
depth: frame.depth + 1,
|
|
87
|
+
});
|
|
79
88
|
}
|
|
80
89
|
}
|
|
81
90
|
return true;
|
package/dist/transport.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
|
|
19
19
|
import { runtimeErrorMessage } from "./error-response.js";
|
|
20
20
|
import { UruAppRuntimeError } from "./errors.js";
|
|
21
|
-
import { resolveHeaders, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
21
|
+
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
|
|
22
22
|
import { isRuntimeJsonObject } from "./transport-json.js";
|
|
23
23
|
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
24
|
const httpRecord = (value, label) => {
|
|
@@ -286,18 +286,6 @@ const emitRuntimeEvent = (options, event) => {
|
|
|
286
286
|
options.onStatus(event);
|
|
287
287
|
}
|
|
288
288
|
};
|
|
289
|
-
const resolveRuntimeFetch = (options) => {
|
|
290
|
-
if (options.fetch !== undefined) {
|
|
291
|
-
return options.fetch;
|
|
292
|
-
}
|
|
293
|
-
if (typeof globalThis.fetch !== "function") {
|
|
294
|
-
throw new UruAppRuntimeError("Uru app runtime fetch is not available.", {
|
|
295
|
-
body: null,
|
|
296
|
-
status: 0,
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
return globalThis.fetch;
|
|
300
|
-
};
|
|
301
289
|
const invocationIdentity = (options, name) => {
|
|
302
290
|
const capabilityName = name.trim();
|
|
303
291
|
const deploymentId = options.deploymentId.trim();
|
|
@@ -364,7 +352,11 @@ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper,
|
|
|
364
352
|
};
|
|
365
353
|
const responseBody = async (response) => await response.json().catch(() => null);
|
|
366
354
|
const fetchInvocation = async (args, attempt = 0) => {
|
|
367
|
-
|
|
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, {
|
|
368
360
|
body: args.requestBody,
|
|
369
361
|
headers: args.headers,
|
|
370
362
|
method: "POST",
|
package/dist/types.d.ts
CHANGED
|
@@ -207,8 +207,104 @@ export interface UruDatasetsContext {
|
|
|
207
207
|
restoreRows: UruDatasetIdMutation;
|
|
208
208
|
sqlWrite: UruDatasetSqlWrite;
|
|
209
209
|
}
|
|
210
|
+
export interface UruFileMetadata {
|
|
211
|
+
readonly fileId: string;
|
|
212
|
+
readonly filename: string;
|
|
213
|
+
readonly contentType: string;
|
|
214
|
+
readonly sizeBytes: number;
|
|
215
|
+
readonly sha256: string;
|
|
216
|
+
}
|
|
217
|
+
export interface UruFileContent extends UruFileMetadata {
|
|
218
|
+
readonly content: Uint8Array;
|
|
219
|
+
}
|
|
220
|
+
export interface UruFileOutput extends UruFileMetadata {
|
|
221
|
+
readonly outputId: string;
|
|
222
|
+
readonly createdAt: string;
|
|
223
|
+
}
|
|
224
|
+
export interface UruFileOutputSummary extends UruFileOutput {
|
|
225
|
+
readonly releaseId: string | null;
|
|
226
|
+
readonly buildId: string | null;
|
|
227
|
+
}
|
|
228
|
+
export interface UruFilesContext {
|
|
229
|
+
read(fileId: string, options?: {
|
|
230
|
+
signal?: AbortSignal;
|
|
231
|
+
}): Promise<UruFileContent>;
|
|
232
|
+
readOutput(outputId: string, options?: {
|
|
233
|
+
signal?: AbortSignal;
|
|
234
|
+
}): Promise<UruFileContent>;
|
|
235
|
+
createOutput(input: {
|
|
236
|
+
name: string;
|
|
237
|
+
contentType: string;
|
|
238
|
+
content: Uint8Array;
|
|
239
|
+
idempotencyKey: string;
|
|
240
|
+
sha256?: string;
|
|
241
|
+
signal?: AbortSignal;
|
|
242
|
+
}): Promise<UruFileOutput>;
|
|
243
|
+
listOutputs(options?: {
|
|
244
|
+
cursor?: string;
|
|
245
|
+
limit?: number;
|
|
246
|
+
signal?: AbortSignal;
|
|
247
|
+
}): Promise<{
|
|
248
|
+
items: readonly UruFileOutputSummary[];
|
|
249
|
+
nextCursor: string | null;
|
|
250
|
+
}>;
|
|
251
|
+
}
|
|
252
|
+
/** Every conclusion the platform can reach about one upload. */
|
|
253
|
+
export type UruUploadOutcome = "verified" | "pending" | "absent" | "expired" | "unverifiable" | "size_mismatch" | "type_mismatch";
|
|
254
|
+
/**
|
|
255
|
+
* A minted grant. `uploadUrl` is a CREDENTIAL: do not log it or store it.
|
|
256
|
+
*
|
|
257
|
+
* `requiredHeaders` is not advice. The provider rebuilds the signature from
|
|
258
|
+
* what actually arrives, so a PUT that omits or alters either header is
|
|
259
|
+
* refused.
|
|
260
|
+
*/
|
|
261
|
+
export interface UruUploadGrant {
|
|
262
|
+
readonly uploadId: string;
|
|
263
|
+
readonly uploadUrl: string;
|
|
264
|
+
readonly method: "PUT";
|
|
265
|
+
readonly requiredHeaders: Readonly<Record<string, string>>;
|
|
266
|
+
readonly filename: string;
|
|
267
|
+
readonly contentType: string;
|
|
268
|
+
readonly sizeBytes: number;
|
|
269
|
+
readonly expiresAt: string;
|
|
270
|
+
}
|
|
271
|
+
/** The verdict a completion reached. */
|
|
272
|
+
export interface UruUploadResult {
|
|
273
|
+
readonly uploadId: string;
|
|
274
|
+
readonly state: "granted" | "verified" | "rejected" | "expired";
|
|
275
|
+
readonly outcome: UruUploadOutcome;
|
|
276
|
+
readonly filename: string;
|
|
277
|
+
readonly contentType: string;
|
|
278
|
+
/** The VERIFIED byte count, or `null` when the object was not admitted. */
|
|
279
|
+
readonly sizeBytes: number | null;
|
|
280
|
+
/** True only when a refused object could not be removed from storage. */
|
|
281
|
+
readonly cleanupFailed: boolean;
|
|
282
|
+
}
|
|
283
|
+
/** The file-upload lane a Gem gets with the `storage` capability. */
|
|
284
|
+
export interface UruUploadsContext {
|
|
285
|
+
request(input: {
|
|
286
|
+
filename: string;
|
|
287
|
+
contentType: string;
|
|
288
|
+
sizeBytes: number;
|
|
289
|
+
signal?: AbortSignal;
|
|
290
|
+
}): Promise<UruUploadGrant>;
|
|
291
|
+
complete(uploadId: string, options?: {
|
|
292
|
+
signal?: AbortSignal;
|
|
293
|
+
}): Promise<UruUploadResult>;
|
|
294
|
+
/** Request, PUT and complete in one call. What almost every caller wants. */
|
|
295
|
+
upload(file: File, options?: {
|
|
296
|
+
signal?: AbortSignal;
|
|
297
|
+
}): Promise<UruUploadResult>;
|
|
298
|
+
}
|
|
299
|
+
export interface UruJobProgress {
|
|
300
|
+
readonly completed: number;
|
|
301
|
+
readonly total?: number;
|
|
302
|
+
readonly message?: string;
|
|
303
|
+
}
|
|
304
|
+
export type UruJobCheckpoint = RuntimeJsonObject;
|
|
210
305
|
/** Everything a Uru server runtime hands an app. */
|
|
211
306
|
export interface UruServerContext {
|
|
307
|
+
files: UruFilesContext;
|
|
212
308
|
datasets: UruDatasetsContext;
|
|
213
309
|
app: UruAppRuntimeClient;
|
|
214
310
|
actions: {
|
|
@@ -216,6 +312,8 @@ export interface UruServerContext {
|
|
|
216
312
|
};
|
|
217
313
|
jobs: {
|
|
218
314
|
start: UruCapabilityInvoker;
|
|
315
|
+
progress: (progress: UruJobProgress) => Promise<void>;
|
|
316
|
+
checkpoint: (value: UruJobCheckpoint) => Promise<void>;
|
|
219
317
|
};
|
|
220
318
|
secrets: {
|
|
221
319
|
has: (name: string) => boolean;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `uru.uploads` — how a Gem accepts a file from the person using it.
|
|
3
|
+
*
|
|
4
|
+
* ## Three hops, and the middle one does not touch Uru
|
|
5
|
+
*
|
|
6
|
+
* 1. `request(...)` asks the platform for a grant. The answer carries a
|
|
7
|
+
* credential that authorizes ONE PUT: exactly one object key, exactly the
|
|
8
|
+
* declared byte count, exactly the declared media type, for a short window
|
|
9
|
+
* the server derived from the size.
|
|
10
|
+
* 2. The browser PUTs the bytes STRAIGHT to object storage with that
|
|
11
|
+
* credential. They never pass through Uru: every runtime invocation body is
|
|
12
|
+
* capped at 100 KB and hashed in worker memory before it is forwarded, so a
|
|
13
|
+
* file could not travel that way at any size worth calling a file.
|
|
14
|
+
* 3. `complete(...)` consumes the grant. The platform then READS the stored
|
|
15
|
+
* object and decides for itself whether it is what was authorized. A
|
|
16
|
+
* "done!" from this SDK is a trigger for that read, never evidence.
|
|
17
|
+
*
|
|
18
|
+
* `upload(file)` performs all three, which is what almost every caller wants.
|
|
19
|
+
*
|
|
20
|
+
* ## The refusals are values, not exceptions
|
|
21
|
+
*
|
|
22
|
+
* A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
|
|
23
|
+
* that nobody redeemed (`expired`) is a normal outcome of an upload a user
|
|
24
|
+
* started, and a Gem has to render it. So `complete` RESOLVES with the verdict
|
|
25
|
+
* and throws only when the platform could not be asked at all. `pending` is the
|
|
26
|
+
* one non-terminal outcome: the window is still open and nothing has landed, so
|
|
27
|
+
* the grant is untouched and may be completed again.
|
|
28
|
+
*/
|
|
29
|
+
import type { CreateUruAppRuntimeClientOptions, UruUploadsContext } from './types.js';
|
|
30
|
+
/** The platform's per-file ceiling. Restated so a caller is refused locally. */
|
|
31
|
+
export declare const URU_UPLOAD_MAX_BYTES: number;
|
|
32
|
+
export declare function createUploadsContext(options: CreateUruAppRuntimeClientOptions): UruUploadsContext;
|
package/dist/uploads.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `uru.uploads` — how a Gem accepts a file from the person using it.
|
|
3
|
+
*
|
|
4
|
+
* ## Three hops, and the middle one does not touch Uru
|
|
5
|
+
*
|
|
6
|
+
* 1. `request(...)` asks the platform for a grant. The answer carries a
|
|
7
|
+
* credential that authorizes ONE PUT: exactly one object key, exactly the
|
|
8
|
+
* declared byte count, exactly the declared media type, for a short window
|
|
9
|
+
* the server derived from the size.
|
|
10
|
+
* 2. The browser PUTs the bytes STRAIGHT to object storage with that
|
|
11
|
+
* credential. They never pass through Uru: every runtime invocation body is
|
|
12
|
+
* capped at 100 KB and hashed in worker memory before it is forwarded, so a
|
|
13
|
+
* file could not travel that way at any size worth calling a file.
|
|
14
|
+
* 3. `complete(...)` consumes the grant. The platform then READS the stored
|
|
15
|
+
* object and decides for itself whether it is what was authorized. A
|
|
16
|
+
* "done!" from this SDK is a trigger for that read, never evidence.
|
|
17
|
+
*
|
|
18
|
+
* `upload(file)` performs all three, which is what almost every caller wants.
|
|
19
|
+
*
|
|
20
|
+
* ## The refusals are values, not exceptions
|
|
21
|
+
*
|
|
22
|
+
* A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
|
|
23
|
+
* that nobody redeemed (`expired`) is a normal outcome of an upload a user
|
|
24
|
+
* started, and a Gem has to render it. So `complete` RESOLVES with the verdict
|
|
25
|
+
* and throws only when the platform could not be asked at all. `pending` is the
|
|
26
|
+
* one non-terminal outcome: the window is still open and nothing has landed, so
|
|
27
|
+
* the grant is untouched and may be completed again.
|
|
28
|
+
*/
|
|
29
|
+
import { UruAppRuntimeError } from './errors.js';
|
|
30
|
+
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash } from './runtime.js';
|
|
31
|
+
import { isRuntimeJsonObject } from './transport-json.js';
|
|
32
|
+
/** The platform's per-file ceiling. Restated so a caller is refused locally. */
|
|
33
|
+
export const URU_UPLOAD_MAX_BYTES = 100 * 1024 * 1024;
|
|
34
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
35
|
+
const RESPONSE_BYTES = 64 * 1024;
|
|
36
|
+
const OUTCOMES = [
|
|
37
|
+
'verified',
|
|
38
|
+
'pending',
|
|
39
|
+
'absent',
|
|
40
|
+
'expired',
|
|
41
|
+
'unverifiable',
|
|
42
|
+
'size_mismatch',
|
|
43
|
+
'type_mismatch',
|
|
44
|
+
];
|
|
45
|
+
function invalid() {
|
|
46
|
+
throw new UruAppRuntimeError('Invalid upload request or response.', {
|
|
47
|
+
status: 0,
|
|
48
|
+
body: null,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
|
|
52
|
+
const string = (value) => typeof value === 'string' ? value : invalid();
|
|
53
|
+
/**
|
|
54
|
+
* Read a bounded JSON body.
|
|
55
|
+
*
|
|
56
|
+
* Bounded rather than trusted for the same reason the files context bounds its
|
|
57
|
+
* own: a runtime that answered with an unbounded body would otherwise be able
|
|
58
|
+
* to exhaust the Gem's memory through a call the Gem made on purpose.
|
|
59
|
+
*/
|
|
60
|
+
async function readJson(response) {
|
|
61
|
+
const reader = response.body?.getReader();
|
|
62
|
+
if (reader === undefined)
|
|
63
|
+
invalid();
|
|
64
|
+
const decoder = new TextDecoder();
|
|
65
|
+
let size = 0;
|
|
66
|
+
let text = '';
|
|
67
|
+
try {
|
|
68
|
+
for (;;) {
|
|
69
|
+
const chunk = await reader.read();
|
|
70
|
+
if (chunk.done)
|
|
71
|
+
break;
|
|
72
|
+
size += chunk.value.byteLength;
|
|
73
|
+
if (size > RESPONSE_BYTES) {
|
|
74
|
+
await reader.cancel();
|
|
75
|
+
invalid();
|
|
76
|
+
}
|
|
77
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
78
|
+
}
|
|
79
|
+
text += decoder.decode();
|
|
80
|
+
return JSON.parse(text);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error instanceof UruAppRuntimeError)
|
|
84
|
+
throw error;
|
|
85
|
+
return invalid();
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
reader.releaseLock();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function grantFrom(value) {
|
|
92
|
+
const row = object(value);
|
|
93
|
+
const uploadId = string(row['uploadId']);
|
|
94
|
+
const uploadUrl = string(row['uploadUrl']);
|
|
95
|
+
const sizeBytes = row['sizeBytes'];
|
|
96
|
+
const headers = row['requiredHeaders'];
|
|
97
|
+
if (!UUID.test(uploadId) ||
|
|
98
|
+
uploadUrl === '' ||
|
|
99
|
+
typeof sizeBytes !== 'number' ||
|
|
100
|
+
!Number.isSafeInteger(sizeBytes) ||
|
|
101
|
+
sizeBytes < 1 ||
|
|
102
|
+
!isRuntimeJsonObject(headers)) {
|
|
103
|
+
invalid();
|
|
104
|
+
}
|
|
105
|
+
const requiredHeaders = {};
|
|
106
|
+
for (const [name, headerValue] of Object.entries(headers)) {
|
|
107
|
+
requiredHeaders[name] = string(headerValue);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
uploadId,
|
|
111
|
+
uploadUrl,
|
|
112
|
+
method: 'PUT',
|
|
113
|
+
requiredHeaders,
|
|
114
|
+
filename: string(row['filename']),
|
|
115
|
+
contentType: string(row['contentType']),
|
|
116
|
+
sizeBytes,
|
|
117
|
+
expiresAt: string(row['expiresAt']),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function resultFrom(value) {
|
|
121
|
+
const row = object(value);
|
|
122
|
+
const outcome = string(row['outcome']);
|
|
123
|
+
const state = string(row['state']);
|
|
124
|
+
const sizeBytes = row['sizeBytes'];
|
|
125
|
+
if (!OUTCOMES.includes(outcome) ||
|
|
126
|
+
(state !== 'granted' &&
|
|
127
|
+
state !== 'verified' &&
|
|
128
|
+
state !== 'rejected' &&
|
|
129
|
+
state !== 'expired') ||
|
|
130
|
+
(sizeBytes !== null && typeof sizeBytes !== 'number')) {
|
|
131
|
+
invalid();
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
uploadId: string(row['uploadId']),
|
|
135
|
+
state,
|
|
136
|
+
outcome: outcome,
|
|
137
|
+
filename: string(row['filename']),
|
|
138
|
+
contentType: string(row['contentType']),
|
|
139
|
+
sizeBytes: sizeBytes === null ? null : sizeBytes,
|
|
140
|
+
cleanupFailed: row['cleanupFailed'] === true,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
export function createUploadsContext(options) {
|
|
144
|
+
const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/uploads`;
|
|
145
|
+
// Resolved per call rather than once here, so building the context still
|
|
146
|
+
// costs nothing on a runtime whose `fetch` arrives later, and so the global
|
|
147
|
+
// is always called with the global as its receiver.
|
|
148
|
+
const doFetch = async (...args) => await resolveRuntimeFetch(options)(...args);
|
|
149
|
+
const post = async (path, payload, signal) => {
|
|
150
|
+
const headers = new Headers(await resolveHeaders(options.headers));
|
|
151
|
+
if (payload !== undefined)
|
|
152
|
+
headers.set('content-type', 'application/json');
|
|
153
|
+
const response = await doFetch(`${base}${path}`, {
|
|
154
|
+
method: 'POST',
|
|
155
|
+
headers,
|
|
156
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
157
|
+
signal: signal === undefined
|
|
158
|
+
? AbortSignal.timeout(30_000)
|
|
159
|
+
: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
160
|
+
});
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
await response.body?.cancel();
|
|
163
|
+
throw new UruAppRuntimeError('Upload request was not accepted.', {
|
|
164
|
+
status: response.status,
|
|
165
|
+
body: null,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
return readJson(response);
|
|
169
|
+
};
|
|
170
|
+
const request = async (input) => {
|
|
171
|
+
if (typeof input.filename !== 'string' ||
|
|
172
|
+
input.filename.trim().length < 1 ||
|
|
173
|
+
input.filename.length > 255 ||
|
|
174
|
+
typeof input.contentType !== 'string' ||
|
|
175
|
+
input.contentType.trim().length < 3 ||
|
|
176
|
+
input.contentType.length > 255 ||
|
|
177
|
+
!Number.isSafeInteger(input.sizeBytes) ||
|
|
178
|
+
input.sizeBytes < 1 ||
|
|
179
|
+
input.sizeBytes > URU_UPLOAD_MAX_BYTES) {
|
|
180
|
+
invalid();
|
|
181
|
+
}
|
|
182
|
+
return grantFrom(await post('', {
|
|
183
|
+
filename: input.filename,
|
|
184
|
+
contentType: input.contentType,
|
|
185
|
+
sizeBytes: input.sizeBytes,
|
|
186
|
+
}, input.signal));
|
|
187
|
+
};
|
|
188
|
+
const complete = async (uploadId, settings) => {
|
|
189
|
+
if (typeof uploadId !== 'string' || !UUID.test(uploadId))
|
|
190
|
+
invalid();
|
|
191
|
+
return resultFrom(await post(`/${uploadId}/complete`, undefined, settings?.signal));
|
|
192
|
+
};
|
|
193
|
+
return {
|
|
194
|
+
request,
|
|
195
|
+
complete,
|
|
196
|
+
upload: async (file, settings) => {
|
|
197
|
+
// The media type is the browser's, lower-cased by it already. A file the
|
|
198
|
+
// OS could not type at all gets the generic one rather than an empty
|
|
199
|
+
// header, because a grant must name ONE concrete media type and an empty
|
|
200
|
+
// one would be refused at the mint with a message about a header the
|
|
201
|
+
// caller never wrote.
|
|
202
|
+
const contentType = typeof file.type === 'string' && file.type.trim() !== ''
|
|
203
|
+
? file.type
|
|
204
|
+
: 'application/octet-stream';
|
|
205
|
+
const grant = await request({
|
|
206
|
+
filename: file.name,
|
|
207
|
+
contentType,
|
|
208
|
+
sizeBytes: file.size,
|
|
209
|
+
...(settings?.signal === undefined ? {} : { signal: settings.signal }),
|
|
210
|
+
});
|
|
211
|
+
const put = await doFetch(grant.uploadUrl, {
|
|
212
|
+
method: 'PUT',
|
|
213
|
+
// Exactly the headers the grant was SIGNED with. Adding or altering one
|
|
214
|
+
// changes the canonical request the provider rebuilds, and the PUT is
|
|
215
|
+
// refused with a signature error that names nothing.
|
|
216
|
+
headers: new Headers(grant.requiredHeaders),
|
|
217
|
+
body: file,
|
|
218
|
+
...(settings?.signal === undefined ? {} : { signal: settings.signal }),
|
|
219
|
+
});
|
|
220
|
+
if (!put.ok) {
|
|
221
|
+
await put.body?.cancel();
|
|
222
|
+
throw new UruAppRuntimeError('Upload was refused by object storage.', {
|
|
223
|
+
status: put.status,
|
|
224
|
+
body: null,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
await put.body?.cancel();
|
|
228
|
+
return complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|