@uru-intelligence/app 2.2.4 → 2.3.0

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 CHANGED
@@ -1,5 +1,91 @@
1
1
  # @uru-intelligence/app
2
2
 
3
+ ## Named values in Gem storage
4
+
5
+ Declare `"storage": true` in the root `uru.json`. The browser client and the
6
+ server context expose the same four operations:
7
+
8
+ ```ts
9
+ const app = createUruAppRuntimeClient({ deploymentId });
10
+ await app.storage.put('settings', { theme: 'dark' });
11
+ const settings = await app.storage.get('settings');
12
+ if (settings.found) console.log(settings.value);
13
+ const page = await app.storage.list({ prefix: 'settings', limit: 50 });
14
+ await app.storage.delete('settings');
15
+ ```
16
+
17
+ On the server, use `createUruServerContext(env).storage`. The server verifies
18
+ the runtime token and chooses the Gem, workspace, environment, and viewer
19
+ partition. Do not send those identities in stored values to choose a partition.
20
+ Browser and server calls share data only when their verified partition matches.
21
+ Published visitors keep their own partition. A server token uses the Gem owner's
22
+ partition. Preview data and released data remain separate.
23
+
24
+ Values must be JSON. Each value can use at most 256 KiB. The existing storage
25
+ quota, request size limits, and permission checks apply. Public requests have
26
+ a 100 KB body limit. `list` returns keys and `nextCursor`; pass
27
+ that cursor to read the next page. A missing key returns `{ found: false }`.
28
+ `null` is a stored value and returns `{ found: true, value: null }`.
29
+
30
+ Each call has a request identity. You can set `requestId` in its options.
31
+ Storage does not replay a completed write. A repeated completed identity returns
32
+ an error; read the value to resolve an uncertain write. The client does not retry
33
+ writes automatically. A program job that writes storage loses automatic attempt
34
+ retry because the storage service cannot replay its first result.
35
+
36
+ Use the Dataset API for rows and queries. Use the file and upload APIs for bytes.
37
+ Gem storage does not provide a private SQL database.
38
+
39
+ ## Declare operation inputs and outputs
40
+
41
+ The root `uru.json` remains the only authored declaration. Add `description`,
42
+ `inputSchema`, and `outputSchema` to a named action or job. For an existing query,
43
+ put these fields in `capabilities.queryContracts` under its declared name:
44
+
45
+ ```json
46
+ {
47
+ "capabilities": {
48
+ "queries": ["summary"],
49
+ "queryContracts": {
50
+ "summary": {
51
+ "description": "Read the summary for one year.",
52
+ "inputSchema": {
53
+ "type": "object",
54
+ "properties": { "year": { "type": "integer" } },
55
+ "required": ["year"],
56
+ "additionalProperties": false
57
+ },
58
+ "outputSchema": { "type": "object" }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ This fragment belongs inside a complete `uru.gem.v2` root. A query contract must
66
+ name a query in `capabilities.queries`. Schemas can use boolean schemas and local
67
+ references such as `#/$defs/Year`. Unsupported references or formats fail source
68
+ validation. A saved job input must match its input schema.
69
+
70
+ The build copies these declarations into its immutable runtime contract. Runtime
71
+ calls check the declared input before execution and the completed output before
72
+ returning it. Program jobs check their final `outputSummary`. Tool providers keep
73
+ their own validation; an authored schema adds constraints and cannot remove them.
74
+ Tool descriptions use the same saved declarations.
75
+
76
+ The build also creates `uru.generated.d.ts` beside the root declaration. It is
77
+ build input, not a saved source edit. Import `GemInput` and `GemOutput` from it
78
+ to type browser code, for example `GemInput<'query:summary'>`. Complex schemas
79
+ that TypeScript cannot express remain `unknown`; runtime checks still apply.
80
+ Do not create your own `uru.generated.d.ts` file.
81
+
82
+ ```ts
83
+ import type { GemInput } from './uru.generated';
84
+
85
+ const input: GemInput<'query:summary'> = { year: 2026 };
86
+ await app.query('summary', input);
87
+ ```
88
+
3
89
  **This package is the runtime client for [Uru](https://uruintelligence.com) Gems.
4
90
  It is published so that Gem projects install and build outside the Uru hosted
5
91
  builder. It talks only to an Uru workspace runtime and does nothing on its own.
@@ -433,10 +519,11 @@ attempt can run safely.
433
519
 
434
520
  Uru also runs the job again when the handler throws a temporary answer from
435
521
  Uru after the SDK's own resends ran out: a 408, 429 or 503 that does not say
436
- `retryable: false`, or a 502 or 504 that no server answered. This needs a job
437
- that is still retryable (see below), an attempt left (three in all), and no
438
- cancel. Any other answer ends the job: a 500, a 403, 404, 409 or 422, or an
439
- error from your own code.
522
+ `retryable: false`, a 502 or 504 that no server answered, Cloudflare's own 520
523
+ to 527 or 530, or a 500 with no Uru error code, which a proxy in front of Uru
524
+ gave. This needs a job that is still retryable (see below), an attempt left
525
+ (three in all), and no cancel. Any other answer ends the job: a 500 with Uru's
526
+ error code, a 403, 404, 409 or 422, or an error from your own code.
440
527
 
441
528
  On the next attempt:
442
529
 
@@ -545,8 +632,8 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
545
632
  A custom retry wait can accept the optional `AbortSignal` to stop its own
546
633
  work. The SDK still bounds the call when that wait ignores the signal.
547
634
  - **Calls ride out a restarting server.** When Uru gives no answer (a failed
548
- or reset connection, a reply cut off after its headers, HTTP 502 or 504, or
549
- a 503 without an Uru error code),
635
+ or reset connection, a reply cut off after its headers, HTTP 502 or 504, a
636
+ 503 without an Uru error code, or Cloudflare's own 520 to 527 or 530),
550
637
  the client sends the call again after about 0.5, 1, 2, 4, 8, 8 and 8
551
638
  seconds, each stretched by up to twice for jitter: about a minute in all.
552
639
  Each wait reports a `reconnecting` status event. An action or a job start
@@ -565,7 +652,10 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
565
652
  some Datasets and not others: do not send it again with a new key, which
566
653
  writes the saved Datasets again. The caller's
567
654
  `signal` and `timeoutMs` end the waits. Set `dampers.maxTransportRetries` to
568
- `0` to turn resends off.
655
+ `0` to turn resends off. The SDK then does not tell the Uru gateway of a
656
+ hosted job that it resends, so the gateway may still send a call that is safe
657
+ to repeat again after a lost answer, a temporary answer or a 500 with no Uru
658
+ error code.
569
659
  - **Job writes ride out a short database stall.** A Dataset row write with a
570
660
  key, `jobs.progress` and `jobs.checkpoint` are also sent again when Uru
571
661
  answers that it cannot serve the call now: HTTP 408, 429 or 503. They use
@@ -573,10 +663,19 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
573
663
  `Retry-After` is longer than the wait time that is left, the call throws
574
664
  that answer at once and never sends before the server allows. A row
575
665
  write sends the same key each time, so the server joins the first command
576
- and never writes twice. Every other answer is final and is never sent
577
- again: a 500, 403, 404, 409, 422 or any other status, an error body with
578
- `retryable: false`, or a setup failure that a resend cannot fix. When the
579
- resends run out, the call throws `UruAppRuntimeError` with the last status.
666
+ and never writes twice. They are also sent again, at most twice, after a
667
+ 500 with no Uru error code: Uru answers its own 500 with an error code, so
668
+ a 500 without one came from a proxy in front of Uru. Every other answer is
669
+ final and is never sent again: a 500 with Uru's error code, a 403, 404,
670
+ 409, 422 or any other status, an error body with `retryable: false`, or a
671
+ setup failure that a resend cannot fix. When the resends run out, the call
672
+ throws `UruAppRuntimeError` with the last status and the answer's parsed
673
+ body. A file call and an upload that are not accepted keep that body too.
674
+ - **A query rides out a short stall too.** A query only reads, so it is also
675
+ sent again, with a new key, after HTTP 408 or a 503 that is not final, such
676
+ as Uru's 503 when its database pool is full for a moment. It uses the
677
+ lost-answer waits above. A 429 keeps its rate-limit waits, and an action or
678
+ a job start keeps a temporary answer as its result.
580
679
  - **How long a call can take.** All the waits of one call add up to at most
581
680
  63 seconds. A send that gets no answer counts as lost after 30 seconds, so
582
681
  in the worst case (8 sends that each run 30 seconds) a Dataset row write,
@@ -735,7 +834,8 @@ a build to be reproducible; Uru's own Gem templates do.
735
834
 
736
835
  The public surface includes `createUruServerContext`,
737
836
  `createUruAppRuntimeClient`, `createUruBackgroundJobCoordinator`,
738
- `createUruUploadsContext`, `UruAppRuntimeError`, and the exported types.
837
+ `createUruUploadsContext`, `createUruStorageContext`, `UruAppRuntimeError`, and
838
+ the exported types.
739
839
  Nothing else is API, even if you can reach it.
740
840
 
741
841
  ## Documentation
package/dist/files.js CHANGED
@@ -4,6 +4,8 @@ import { isRuntimeJsonObject } from './transport-json.js';
4
4
  const LIBRARY_READ_BYTES = 5 * 1024 * 1024;
5
5
  const OUTPUT_BYTES = 10 * 1024 * 1024;
6
6
  const RESPONSE_BYTES = Math.ceil(OUTPUT_BYTES / 3) * 4 + 8192;
7
+ // Uru's error envelope and an edge's error page are far smaller than this.
8
+ const ERROR_BODY_BYTES = 64 * 1024;
7
9
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
10
  const HASH = /^[0-9a-f]{64}$/;
9
11
  function invalid() {
@@ -57,7 +59,7 @@ function base64(bytes) {
57
59
  }
58
60
  return btoa(binary);
59
61
  }
60
- async function readJson(response) {
62
+ async function readJson(response, maxBytes = RESPONSE_BYTES) {
61
63
  const reader = response.body?.getReader();
62
64
  if (reader === undefined)
63
65
  invalid();
@@ -70,7 +72,7 @@ async function readJson(response) {
70
72
  if (chunk.done)
71
73
  break;
72
74
  size += chunk.value.byteLength;
73
- if (size > RESPONSE_BYTES) {
75
+ if (size > maxBytes) {
74
76
  await reader.cancel();
75
77
  invalid();
76
78
  }
@@ -100,8 +102,12 @@ export function createFilesContext(options) {
100
102
  signal: signal === undefined ? AbortSignal.timeout(30_000) : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
101
103
  });
102
104
  if (!response.ok) {
103
- await response.body?.cancel();
104
- throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body: null });
105
+ // The answer's body goes with the error, null when it is not JSON. The
106
+ // job runner reads its error code: a 500 with Uru's code ends the job,
107
+ // and a 500 with none came from an edge, so a retry-safe job gets its
108
+ // next attempt.
109
+ const body = await readJson(response, ERROR_BODY_BYTES).catch(() => null);
110
+ throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body });
105
111
  }
106
112
  return readJson(response);
107
113
  };
package/dist/index.d.ts CHANGED
@@ -14,9 +14,10 @@ import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, U
14
14
  export { datasetRowForMutation } from "./dataset-row.js";
15
15
  export { UruAppRuntimeError } from "./errors.js";
16
16
  export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
17
- export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
17
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext, } from "./uploads.js";
18
+ export { createStorageContext as createUruStorageContext } from "./storage.js";
18
19
  export type { UruRunawayDamperOptions } from "./dampers.js";
19
- export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadStatus, UruUploadsContext, } from "./types.js";
20
+ export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruStorageContext, UruStorageRequestOptions, UruStorageValue, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadStatus, UruUploadsContext, } from "./types.js";
20
21
  /**
21
22
  * Build a capability-invocation client against a Uru app runtime.
22
23
  *
package/dist/index.js CHANGED
@@ -12,15 +12,17 @@
12
12
  */
13
13
  import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
14
14
  import { createDatasetsContext } from "./datasets.js";
15
- import { createFilesContext } from './files.js';
16
- import { createJobProgress, createJobCheckpoint, createJobStep } from './jobs.js';
17
- import { RANDOM_CALL_KEYS, jobAttemptFor, jobCallKeys } from './job-run.js';
18
15
  import { UruAppRuntimeError } from "./errors.js";
16
+ import { createFilesContext } from "./files.js";
19
17
  import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
18
+ import { RANDOM_CALL_KEYS, jobAttemptFor, jobCallKeys } from "./job-run.js";
19
+ import { createJobProgress, createJobCheckpoint, createJobStep, } from "./jobs.js";
20
+ import { createStorageContext } from "./storage.js";
20
21
  export { datasetRowForMutation } from "./dataset-row.js";
21
22
  export { UruAppRuntimeError } from "./errors.js";
22
23
  export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
23
- export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
24
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext, } from "./uploads.js";
25
+ export { createStorageContext as createUruStorageContext } from "./storage.js";
24
26
  const ownEnvironmentValue = (env, key) => {
25
27
  if (!Object.hasOwn(env, key)) {
26
28
  return undefined;
@@ -88,6 +90,7 @@ const appRuntimeClient = (options, keys) => {
88
90
  throttle: new ForceRefreshThrottle(),
89
91
  };
90
92
  return {
93
+ storage: createStorageContext(options),
91
94
  action: createCapabilityInvoker(options, damper, "action"),
92
95
  cancelJob: createCancelJobInvoker(options, damper),
93
96
  deploymentId: options.deploymentId.trim(),
@@ -144,6 +147,7 @@ export const createUruServerContext = (env, options = {}) => {
144
147
  return {
145
148
  actions: { run: createActionInvoker(app) },
146
149
  app,
150
+ storage: app.storage,
147
151
  datasets: createDatasetsContext(app, clientOptions, keys),
148
152
  files: createFilesContext(clientOptions),
149
153
  jobs: {
package/dist/jobs.js CHANGED
@@ -18,7 +18,7 @@ const postJobUpdate = async (options, env, operation, body) => {
18
18
  // temporary answer such as the job token's 503 during a short database
19
19
  // stall. A temporary answer comes before the route saves anything. Each one
20
20
  // also keeps the attempt's lease: it proves the job is alive.
21
- const { response } = await postWithResends({
21
+ const { body: answer, response } = await postWithResends({
22
22
  body,
23
23
  config: resolveDamperConfig(options.dampers),
24
24
  headers,
@@ -27,8 +27,11 @@ const postJobUpdate = async (options, env, operation, body) => {
27
27
  sendTimeoutMs: 30_000,
28
28
  url,
29
29
  });
30
+ // The answer's body goes with the error. The job runner reads its error
31
+ // code: a 500 with Uru's code ends the job, and a 500 with none came from
32
+ // an edge, so a retry-safe job gets its next attempt.
30
33
  if (!response.ok) {
31
- throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
34
+ throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: answer });
32
35
  }
33
36
  };
34
37
  const noJobAttempt = () => new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
@@ -0,0 +1,3 @@
1
+ import type { CreateUruAppRuntimeClientOptions, UruStorageContext } from "./types.js";
2
+ /** Named JSON values in the existing Gem storage partition. */
3
+ export declare function createStorageContext(options: CreateUruAppRuntimeClientOptions): UruStorageContext;
@@ -0,0 +1,149 @@
1
+ import { runtimeErrorMessage } from "./error-response.js";
2
+ import { UruAppRuntimeError } from "./errors.js";
3
+ import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
4
+ import { isRuntimeJsonObject } from "./transport-json.js";
5
+ const RESPONSE_BYTES = 540_672;
6
+ const KEY_LENGTH = 512;
7
+ function invalid() {
8
+ throw new UruAppRuntimeError("Invalid storage request or response.", {
9
+ status: 0,
10
+ body: null,
11
+ });
12
+ }
13
+ function key(value, allowEmpty = false) {
14
+ if (typeof value !== "string" ||
15
+ value.trim().length > KEY_LENGTH ||
16
+ value.includes("\0") ||
17
+ (!allowEmpty && value.trim() === ""))
18
+ invalid();
19
+ return value.trim();
20
+ }
21
+ async function readJson(response) {
22
+ const reader = response.body?.getReader();
23
+ if (reader === undefined)
24
+ invalid();
25
+ let size = 0;
26
+ let text = "";
27
+ const decoder = new TextDecoder();
28
+ try {
29
+ for (;;) {
30
+ const chunk = await reader.read();
31
+ if (chunk.done)
32
+ break;
33
+ size += chunk.value.byteLength;
34
+ if (size > RESPONSE_BYTES) {
35
+ await reader.cancel();
36
+ invalid();
37
+ }
38
+ text += decoder.decode(chunk.value, { stream: true });
39
+ }
40
+ return JSON.parse(text + decoder.decode());
41
+ }
42
+ catch (error) {
43
+ if (error instanceof UruAppRuntimeError)
44
+ throw error;
45
+ return invalid();
46
+ }
47
+ finally {
48
+ reader.releaseLock();
49
+ }
50
+ }
51
+ /** Named JSON values in the existing Gem storage partition. */
52
+ export function createStorageContext(options) {
53
+ const deploymentId = options.deploymentId.trim();
54
+ if (deploymentId === "")
55
+ invalid();
56
+ const url = `${trimTrailingSlash(options.baseUrl ?? "")}${runtimeBasePath(options)}/apps/${encodeURIComponent(deploymentId)}/storage`;
57
+ const request = async (payload, settings) => {
58
+ const serialized = JSON.stringify(payload);
59
+ const headers = new Headers(await resolveHeaders(options.headers));
60
+ headers.set("content-type", "application/json");
61
+ const requestId = settings?.requestId ?? `uru-storage:${crypto.randomUUID()}`;
62
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(requestId))
63
+ invalid();
64
+ headers.set("x-uru-storage-request-id", requestId);
65
+ const response = await resolveRuntimeFetch(options)(url, {
66
+ method: "POST",
67
+ headers,
68
+ body: serialized,
69
+ signal: settings?.signal === undefined
70
+ ? AbortSignal.timeout(30_000)
71
+ : AbortSignal.any([settings.signal, AbortSignal.timeout(30_000)]),
72
+ });
73
+ const body = response.ok
74
+ ? await readJson(response)
75
+ : await readJson(response).catch(() => null);
76
+ if (!response.ok) {
77
+ throw new UruAppRuntimeError(runtimeErrorMessage(body, "Storage request was not accepted."), { status: response.status, body });
78
+ }
79
+ if (!isRuntimeJsonObject(body) ||
80
+ body["operation"] !== payload["operation"])
81
+ invalid();
82
+ return body;
83
+ };
84
+ return {
85
+ get: async (name, settings) => {
86
+ const normalized = key(name);
87
+ const result = await request({ operation: "get", key: normalized }, settings);
88
+ if (result["key"] !== normalized || typeof result["found"] !== "boolean")
89
+ invalid();
90
+ if (!result["found"])
91
+ return { found: false };
92
+ const value = result["value"];
93
+ if (value === undefined)
94
+ invalid();
95
+ return { found: true, value };
96
+ },
97
+ put: async (name, value, settings) => {
98
+ if (!isRuntimeJsonObject({ value }))
99
+ invalid();
100
+ const normalized = key(name);
101
+ const payload = { operation: "put", key: normalized, value };
102
+ // Reject before sending a value that the private route cannot accept.
103
+ if (new TextEncoder().encode(JSON.stringify(payload)).byteLength >
104
+ RESPONSE_BYTES)
105
+ invalid();
106
+ const result = await request(payload, settings);
107
+ const storedValue = result["value"];
108
+ if (result["key"] !== normalized || storedValue === undefined)
109
+ invalid();
110
+ return { value: storedValue };
111
+ },
112
+ delete: async (name, settings) => {
113
+ const normalized = key(name);
114
+ const result = await request({ operation: "delete", key: normalized }, settings);
115
+ if (result["key"] !== normalized ||
116
+ typeof result["deleted"] !== "boolean")
117
+ invalid();
118
+ return { deleted: result["deleted"] };
119
+ },
120
+ list: async (settings = {}) => {
121
+ if (settings.limit !== undefined &&
122
+ (!Number.isInteger(settings.limit) ||
123
+ settings.limit < 1 ||
124
+ settings.limit > 100))
125
+ invalid();
126
+ const result = await request({
127
+ operation: "list",
128
+ ...(settings.prefix === undefined
129
+ ? {}
130
+ : { prefix: key(settings.prefix, true) }),
131
+ ...(settings.cursor === undefined
132
+ ? {}
133
+ : { cursor: key(settings.cursor) }),
134
+ ...(settings.limit === undefined ? {} : { limit: settings.limit }),
135
+ }, settings);
136
+ const keys = result["keys"];
137
+ const nextCursor = result["nextCursor"];
138
+ if (!Array.isArray(keys) ||
139
+ keys.length > (settings.limit ?? 50) ||
140
+ keys.some((value) => typeof value !== "string") ||
141
+ (nextCursor !== null && typeof nextCursor !== "string"))
142
+ invalid();
143
+ return {
144
+ keys: keys.map((value) => key(String(value))),
145
+ nextCursor: nextCursor === null ? null : key(nextCursor),
146
+ };
147
+ },
148
+ };
149
+ }
@@ -1,6 +1,6 @@
1
1
  import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, } from "./dampers.js";
2
2
  import { awaitWithAbort } from "./transport-deadline.js";
3
- import { canResend, isLostRequest, isLostResponse, readRuntimeResponseBody, resendDelayMs, waitBeforeResend, } from "./transport-retry.js";
3
+ import { canResend, isLostRequest, isLostResponse, isTemporaryAnswer, readRuntimeResponseBody, resendDelayMs, waitBeforeResend, } from "./transport-retry.js";
4
4
  const FIRST_SEND = { rateLimited: 0, resent: 0 };
5
5
  /** One send. A lost request comes back as an outcome so the caller can decide. */
6
6
  const sendOnce = async (runtimeFetch, url, init, signal) => {
@@ -26,6 +26,17 @@ const sendOnce = async (runtimeFetch, url, init, signal) => {
26
26
  /** Whether a send ended without an answer from the platform. */
27
27
  const isLost = (outcome) => outcome.kind !== "response" ||
28
28
  isLostResponse(outcome.result.response.status, outcome.result.body);
29
+ /**
30
+ * Whether a query got a temporary answer: a 408, or a 503 that is not final
31
+ * ({@link isTemporaryAnswer}), such as the API's 503 when its database pool
32
+ * is full for a moment. A query only reads, so it is sent again, as after a
33
+ * lost answer. A 429 keeps its own rate-limit waits. An action or a job keeps
34
+ * the answer: its key replays a stored run, which may hold that answer.
35
+ */
36
+ const isTemporaryQueryAnswer = (capabilityType, outcome) => capabilityType === "query" &&
37
+ outcome.kind === "response" &&
38
+ outcome.result.response.status !== 429 &&
39
+ isTemporaryAnswer(outcome.result.response.status, outcome.result.body);
29
40
  /** Report the coming resend, then wait for it. */
30
41
  const reconnect = async (damper, resent, signal, report) => {
31
42
  const delayMs = resendDelayMs(resent, damper.config.random);
@@ -42,7 +53,7 @@ export const fetchInvocation = async (args, counts = FIRST_SEND) => {
42
53
  headers: args.headers,
43
54
  method: "POST",
44
55
  }, args.signal);
45
- if (isLost(outcome) &&
56
+ if ((isLost(outcome) || isTemporaryQueryAnswer(args.capabilityType, outcome)) &&
46
57
  args.resendLost &&
47
58
  canResend(args.damper.config, counts.resent)) {
48
59
  await reconnect(args.damper, counts.resent, args.signal, retryAfterSeconds => args.emit({
@@ -3,18 +3,31 @@
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
- * from the edge, or a 503 from an edge with no healthy replica. None of them
6
+ * from the edge, a 503 from an edge with no healthy replica, or Cloudflare's
7
+ * own 520 to 527 or 530 when the origin gave it no valid answer. None of them
7
8
  * is an answer from Uru: the call may not have arrived, or it arrived and its
8
9
  * 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.
10
+ * Uru: a 408, a 429 or a 503. An edge can also answer a plain 500 of its own
11
+ * ({@link isBareServerError}). Each caller decides whether its request is
12
+ * safe to send again (a keyed Dataset write is, a Dataset SQL statement is
13
+ * not); this module owns what counts as lost, what counts as temporary, and
14
+ * how long to wait.
13
15
  */
14
16
  import type { ResolvedDamperConfig } from "./dampers.js";
15
17
  import type { RuntimeFetch } from "./runtime.js";
16
18
  /** A status the edge gives when no replica answered. */
17
19
  export declare const isLostResponse: (status: number, body: unknown) => boolean;
20
+ /**
21
+ * An answer from Uru that it cannot serve the call now but can soon: a 408,
22
+ * a 429 or a 503 (HTTP defines 503 as temporary, RFC 9110 section 15.6.4).
23
+ * Every other status is final, whatever its body says: a 500 with Uru's error
24
+ * code means the call failed in a way that a resend repeats, and a 4xx such
25
+ * as 403, 404, 409 or 422 refuses this request. A body that says
26
+ * `retryable: false` (a Dataset job that ended) or names a missing setup is
27
+ * final too. A 500 with no Uru error code is not Uru's answer
28
+ * ({@link isBareServerError}).
29
+ */
30
+ export declare const isTemporaryAnswer: (status: number, body: unknown) => boolean;
18
31
  /** A fetch that failed before a response, and not because the caller stopped it. */
19
32
  export declare const isLostRequest: (error: unknown, signal: AbortSignal | undefined) => boolean;
20
33
  /** One response body, and whether the connection broke before all of it arrived. */
@@ -43,9 +56,11 @@ export interface PostWithResendsArguments {
43
56
  /**
44
57
  * Whether the same body is safe to send again: the server answers a keyed
45
58
  * command from its first run, or the call replaces saved state. Such a call
46
- * is sent again after a lost response and after a temporary answer
47
- * ({@link isTemporaryAnswer}), and carries {@link SDK_RESENDS_HEADER}. Any
48
- * other call is sent once.
59
+ * is sent again after a lost response, after a temporary answer
60
+ * ({@link isTemporaryAnswer}) and, a few times, after a bare 500
61
+ * ({@link isBareServerError}), and carries {@link SDK_RESENDS_HEADER} and
62
+ * {@link SDK_RESENDS_BARE_500_HEADER} (unless `maxTransportRetries` is 0).
63
+ * Any other call is sent once.
49
64
  */
50
65
  readonly repeatable: boolean;
51
66
  readonly runtimeFetch: RuntimeFetch;
@@ -59,10 +74,11 @@ export interface PostWithResendsResult {
59
74
  readonly response: Response;
60
75
  }
61
76
  /**
62
- * POST one prepared body. When the platform gave no answer or a temporary
63
- * answer, and the call is repeatable, send the same bytes again after
64
- * {@link resendWaitMs}. The resends stop at `maxTransportRetries` or when the
65
- * wait budget is spent, and the last answer then goes to the caller. A final
66
- * answer is never sent again.
77
+ * POST one prepared body. When the platform gave no answer, a temporary
78
+ * answer or a bare 500, and the call is repeatable, send the same bytes again
79
+ * after {@link resendWaitMs}. The resends stop at `maxTransportRetries`, when
80
+ * the wait budget is spent, or after {@link BARE_SERVER_ERROR_RESENDS} bare
81
+ * 500s, and the last answer then goes to the caller. A final answer is never
82
+ * sent again. `bareServerErrors` counts the bare 500s before this send.
67
83
  */
68
- export declare const postWithResends: (args: PostWithResendsArguments, resent?: number, waitedMs?: number) => Promise<PostWithResendsResult>;
84
+ export declare const postWithResends: (args: PostWithResendsArguments, resent?: number, waitedMs?: number, bareServerErrors?: number) => Promise<PostWithResendsResult>;
@@ -3,13 +3,15 @@
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
- * from the edge, or a 503 from an edge with no healthy replica. None of them
6
+ * from the edge, a 503 from an edge with no healthy replica, or Cloudflare's
7
+ * own 520 to 527 or 530 when the origin gave it no valid answer. None of them
7
8
  * is an answer from Uru: the call may not have arrived, or it arrived and its
8
9
  * 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.
10
+ * Uru: a 408, a 429 or a 503. An edge can also answer a plain 500 of its own
11
+ * ({@link isBareServerError}). Each caller decides whether its request is
12
+ * safe to send again (a keyed Dataset write is, a Dataset SQL statement is
13
+ * not); this module owns what counts as lost, what counts as temporary, and
14
+ * how long to wait.
13
15
  */
14
16
  import { parseRetryable, parseRetryAfterSeconds } from "./dampers.js";
15
17
  import { abortReason, awaitWithAbort } from "./transport-deadline.js";
@@ -55,9 +57,16 @@ const ownedErrorCode = (body) => {
55
57
  codeOf(safeRecordValue(body, "code")) ??
56
58
  (isRecord(error) ? codeOf(safeRecordValue(error, "code")) : null));
57
59
  };
60
+ /**
61
+ * Cloudflare's own statuses for an origin that gave no valid answer: it was
62
+ * down, refused or dropped the connection, or did not answer in time. Uru
63
+ * never sends them.
64
+ */
65
+ const isEdgeOriginStatus = (status) => (status >= 520 && status <= 527) || status === 530;
58
66
  /** A status the edge gives when no replica answered. */
59
67
  export const isLostResponse = (status, body) => status === 502 ||
60
68
  status === 504 ||
69
+ isEdgeOriginStatus(status) ||
61
70
  (status === 503 && ownedErrorCode(body) === null);
62
71
  /** The statuses Uru gives when it cannot serve a call now but can soon. */
63
72
  const TEMPORARY_STATUSES = new Set([408, 429, 503]);
@@ -71,12 +80,14 @@ const SETUP_FAILURE_CODES = new Set([
71
80
  /**
72
81
  * An answer from Uru that it cannot serve the call now but can soon: a 408,
73
82
  * 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.
83
+ * Every other status is final, whatever its body says: a 500 with Uru's error
84
+ * code means the call failed in a way that a resend repeats, and a 4xx such
85
+ * as 403, 404, 409 or 422 refuses this request. A body that says
86
+ * `retryable: false` (a Dataset job that ended) or names a missing setup is
87
+ * final too. A 500 with no Uru error code is not Uru's answer
88
+ * ({@link isBareServerError}).
78
89
  */
79
- const isTemporaryAnswer = (status, body) => {
90
+ export const isTemporaryAnswer = (status, body) => {
80
91
  if (!TEMPORARY_STATUSES.has(status))
81
92
  return false;
82
93
  if (parseRetryable(body) === false)
@@ -84,6 +95,25 @@ const isTemporaryAnswer = (status, body) => {
84
95
  const code = ownedErrorCode(body);
85
96
  return code === null || !SETUP_FAILURE_CODES.has(code);
86
97
  };
98
+ /**
99
+ * A 500 with no Uru error code. The API answers every failure of its
100
+ * handlers, an unexpected throw too, in its error envelope with a code. So no
101
+ * API handler wrote this 500: an edge did (Traefik's own 500 for a proxy
102
+ * failure it has no other status for, as while an API replica starts;
103
+ * Cloudflare's own 500; a Worker that threw), or the API process failed
104
+ * outside its handlers. A call that may be sent again is sent again after
105
+ * it, but only a few times ({@link BARE_SERVER_ERROR_RESENDS}), because that
106
+ * last case can repeat.
107
+ */
108
+ const isBareServerError = (status, body) => status === 500 && ownedErrorCode(body) === null;
109
+ /**
110
+ * The most resends that the bare 500s of one call get. They use the
111
+ * lost-answer waits, so a call whose first answer is a bare 500 that repeats
112
+ * ends about 1.5 to 3 seconds later. That covers the 2 seconds or so that
113
+ * Traefik answered 500 while an API replica started (PR #8488), and a 500
114
+ * that repeats costs at most 2 more sends.
115
+ */
116
+ const BARE_SERVER_ERROR_RESENDS = 2;
87
117
  /**
88
118
  * The request header that tells the provider gateway this client sends a
89
119
  * temporary answer again itself, so the gateway passes it straight back
@@ -91,6 +121,14 @@ const isTemporaryAnswer = (status, body) => {
91
121
  * the API once for each SDK send times each gateway send.
92
122
  */
93
123
  const SDK_RESENDS_HEADER = "x-uru-sdk-resends";
124
+ /**
125
+ * The same for a bare 500 ({@link isBareServerError}). It is a second header
126
+ * and not a second value of {@link SDK_RESENDS_HEADER}, because SDK 2.2.4
127
+ * sends that one too and gives a bare 500 to the caller, so the gateway has
128
+ * to send a bare 500 again for it. A gateway that does not know this header
129
+ * ignores it.
130
+ */
131
+ const SDK_RESENDS_BARE_500_HEADER = "x-uru-sdk-resends-bare-500";
94
132
  /** A fetch that failed before a response, and not because the caller stopped it. */
95
133
  export const isLostRequest = (error, signal) => {
96
134
  if (signal?.aborted === true)
@@ -192,19 +230,24 @@ const resendWaitMs = (args, resent, waitedMs, temporary) => {
192
230
  return Math.min(Math.max(resendDelayMs(resent, args.config.random), retryAfter), left);
193
231
  };
194
232
  /**
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.
233
+ * POST one prepared body. When the platform gave no answer, a temporary
234
+ * answer or a bare 500, and the call is repeatable, send the same bytes again
235
+ * after {@link resendWaitMs}. The resends stop at `maxTransportRetries`, when
236
+ * the wait budget is spent, or after {@link BARE_SERVER_ERROR_RESENDS} bare
237
+ * 500s, and the last answer then goes to the caller. A final answer is never
238
+ * sent again. `bareServerErrors` counts the bare 500s before this send.
200
239
  */
201
- export const postWithResends = async (args, resent = 0, waitedMs = 0) => {
240
+ export const postWithResends = async (args, resent = 0, waitedMs = 0, bareServerErrors = 0) => {
202
241
  // Read the fetch out of `args` so it is not called with `args` as `this`.
203
242
  const { runtimeFetch } = args;
204
243
  const sendSignal = AbortSignal.timeout(args.sendTimeoutMs);
205
244
  const headers = new Headers(args.headers);
206
- if (args.repeatable)
245
+ // The headers say "I send this again myself". With `maxTransportRetries` at
246
+ // 0 that is false, so the gateway keeps its own resends.
247
+ if (args.repeatable && canResend(args.config, 0)) {
207
248
  headers.set(SDK_RESENDS_HEADER, "temporary");
249
+ headers.set(SDK_RESENDS_BARE_500_HEADER, "1");
250
+ }
208
251
  let outcome = null;
209
252
  let cut = false;
210
253
  let lostError = null;
@@ -226,13 +269,23 @@ export const postWithResends = async (args, resent = 0, waitedMs = 0) => {
226
269
  lostError = error;
227
270
  }
228
271
  let temporary = null;
272
+ let bare = false;
229
273
  if (outcome !== null &&
230
274
  !cut &&
231
275
  !isLostResponse(outcome.response.status, outcome.body)) {
232
- if (!isTemporaryAnswer(outcome.response.status, outcome.body)) {
276
+ bare = isBareServerError(outcome.response.status, outcome.body);
277
+ if (bare) {
278
+ // An edge's 500 says nothing about when to send again, so it keeps
279
+ // the lost-answer waits, as a 502 does.
280
+ if (bareServerErrors >= BARE_SERVER_ERROR_RESENDS)
281
+ return outcome;
282
+ }
283
+ else if (isTemporaryAnswer(outcome.response.status, outcome.body)) {
284
+ temporary = outcome;
285
+ }
286
+ else {
233
287
  return outcome;
234
288
  }
235
- temporary = outcome;
236
289
  }
237
290
  const delayMs = resendWaitMs(args, resent, waitedMs, temporary);
238
291
  if (delayMs === null) {
@@ -241,5 +294,5 @@ export const postWithResends = async (args, resent = 0, waitedMs = 0) => {
241
294
  return outcome;
242
295
  }
243
296
  await waitBeforeResend(args.config, delayMs, undefined);
244
- return await postWithResends(args, resent + 1, waitedMs + delayMs);
297
+ return await postWithResends(args, resent + 1, waitedMs + delayMs, bareServerErrors + (bare ? 1 : 0));
245
298
  };
package/dist/transport.js CHANGED
@@ -494,7 +494,8 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
494
494
  // `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
495
495
  // (capped) before falling through to the normal failure path. A response the
496
496
  // platform never gave (a restarting replica) is sent again separately, at
497
- // most `maxTransportRetries` times, when the call is safe to send again.
497
+ // most `maxTransportRetries` times, when the call is safe to send again. So
498
+ // is a query's temporary answer: a query only reads.
498
499
  const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
499
500
  capabilityName,
500
501
  capabilityType,
package/dist/types.d.ts CHANGED
@@ -117,6 +117,8 @@ export interface UruActionInvoker {
117
117
  }
118
118
  /** The capability-invocation client returned by `createUruAppRuntimeClient`. */
119
119
  export interface UruAppRuntimeClient {
120
+ /** Named JSON values in this Gem's authorized storage partition. */
121
+ storage: UruStorageContext;
120
122
  /** Deployment identity used by every operation on this client. */
121
123
  readonly deploymentId: string;
122
124
  query: UruCapabilityInvoker;
@@ -454,7 +456,7 @@ export interface UruUploadResult {
454
456
  }
455
457
  export interface UruUploadStatus {
456
458
  readonly uploadId: string;
457
- readonly state: UruUploadResult['state'];
459
+ readonly state: UruUploadResult["state"];
458
460
  readonly outcome: UruUploadOutcome | null;
459
461
  readonly filename: string;
460
462
  readonly contentType: string;
@@ -522,6 +524,7 @@ export interface UruJobStep {
522
524
  export type UruJobStepResult = RuntimeJsonValue | undefined | void;
523
525
  /** Everything a Uru server runtime hands an app. */
524
526
  export interface UruServerContext {
527
+ storage: UruStorageContext;
525
528
  files: UruFilesContext;
526
529
  datasets: UruDatasetsContext;
527
530
  app: UruAppRuntimeClient;
@@ -554,6 +557,35 @@ export interface UruServerContext {
554
557
  get: (name: string) => string;
555
558
  };
556
559
  }
560
+ export type UruStorageValue = RuntimeJsonValue;
561
+ export interface UruStorageRequestOptions {
562
+ signal?: AbortSignal;
563
+ /** Stable retry identity. Completed writes are reported as completed, not replayed. */
564
+ requestId?: string;
565
+ }
566
+ /** Small named JSON values. Scope and quotas are enforced by the server. */
567
+ export interface UruStorageContext {
568
+ get(name: string, options?: UruStorageRequestOptions): Promise<{
569
+ found: false;
570
+ } | {
571
+ found: true;
572
+ value: UruStorageValue;
573
+ }>;
574
+ put(name: string, value: UruStorageValue, options?: UruStorageRequestOptions): Promise<{
575
+ value: UruStorageValue;
576
+ }>;
577
+ delete(name: string, options?: UruStorageRequestOptions): Promise<{
578
+ deleted: boolean;
579
+ }>;
580
+ list(options?: UruStorageRequestOptions & {
581
+ prefix?: string;
582
+ cursor?: string;
583
+ limit?: number;
584
+ }): Promise<{
585
+ keys: string[];
586
+ nextCursor: string | null;
587
+ }>;
588
+ }
557
589
  /**
558
590
  * The environment a Uru provider runtime injects.
559
591
  *
package/dist/uploads.js CHANGED
@@ -277,10 +277,14 @@ export function createUploadsContext(options) {
277
277
  : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
278
278
  });
279
279
  if (!response.ok) {
280
- await response.body?.cancel();
280
+ // The answer's body goes with the error, null when it is not JSON. The
281
+ // job runner reads its error code: a 500 with Uru's code ends the job,
282
+ // and a 500 with none came from an edge, so a retry-safe job gets its
283
+ // next attempt.
284
+ const body = await readJson(response).catch(() => null);
281
285
  throw new UruAppRuntimeError('Upload request was not accepted.', {
282
286
  status: response.status,
283
- body: null,
287
+ body,
284
288
  });
285
289
  }
286
290
  return readJson(response);
@@ -343,10 +347,11 @@ export function createUploadsContext(options) {
343
347
  : AbortSignal.any([settings.signal, AbortSignal.timeout(300_000)]),
344
348
  });
345
349
  if (!response.ok) {
346
- await response.body?.cancel();
350
+ // Uru's answer, not the file: its body goes with the error, as above.
351
+ const body = await readJson(response).catch(() => null);
347
352
  throw new UruAppRuntimeError('Upload could not be read.', {
348
353
  status: response.status,
349
- body: null,
354
+ body,
350
355
  });
351
356
  }
352
357
  return readBlob(response);
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.2.4",
3
+ "version": "2.3.0",
4
4
  "private": false,
5
- "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
5
+ "description": "Runtime client for Uru Gems: capability calls, Datasets, storage, jobs and secrets",
6
6
  "keywords": [
7
7
  "gem",
8
8
  "runtime",
@@ -85,5 +85,5 @@
85
85
  "engines": {
86
86
  "node": ">=22.12.0"
87
87
  },
88
- "packageManager": "bun@1.3.14"
88
+ "packageManager": "bun@1.4.2"
89
89
  }