@uru-intelligence/app 2.1.6 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,6 +76,66 @@ 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
+ ## Recoverable background jobs
80
+
81
+ Use `createUruBackgroundJobCoordinator` when a caller must recover after a
82
+ lost start response or a process restart. It uses the existing `job`,
83
+ `jobStatus`, and `cancelJob` operations. It does not own job state.
84
+
85
+ The caller supplies a durable store scoped to the deployment and viewer. Its
86
+ `create` operation must insert only when the key is absent. Its three update
87
+ operations must be atomic and must preserve the saved request. The helper saves
88
+ the idempotency key, input, timeout, and absolute deadline before it starts a
89
+ job. If the store fails, no job starts.
90
+
91
+ ```ts
92
+ import {
93
+ createUruBackgroundJobCoordinator,
94
+ createUruServerContext,
95
+ } from '@uru-intelligence/app';
96
+
97
+ const uru = createUruServerContext(process.env);
98
+ const deploymentId = process.env.URU_DEPLOYMENT_ID;
99
+ if (!deploymentId) throw new Error('Missing deployment id');
100
+
101
+ const jobs = createUruBackgroundJobCoordinator({
102
+ app: uru.app,
103
+ deploymentId,
104
+ store: jobStore,
105
+ });
106
+
107
+ const request = {
108
+ capabilityName: 'sync_orders',
109
+ idempotencyKey: `orders:${batchId}`,
110
+ input: { batchId, source: 'orders' },
111
+ deadlineAt: Date.now() + 30 * 60 * 1000,
112
+ timeoutMs: 25_000,
113
+ };
114
+
115
+ const started = await jobs.start(request);
116
+ if (started.response.pending) {
117
+ const outcome = await jobs.wait(request.idempotencyKey);
118
+ if (outcome.kind === 'complete') {
119
+ showResult(outcome.status.result);
120
+ }
121
+ }
122
+ ```
123
+
124
+ After a lost start response, call `resume` with the same key. The helper sends
125
+ the saved input, key, and timeout again. The server uses that key to return the
126
+ same accepted work. It does not create a new logical request. While the caller's
127
+ store keeps the saved row, the helper refuses changed input, timeout, deployment,
128
+ or deadline for that key. The deadline is local. The helper does not send it to
129
+ the server. If the caller deletes the row, the helper cannot enforce the saved
130
+ request identity or deadline.
131
+
132
+ `wait` stops at the saved deadline and honors the server's retry hint. Its
133
+ `AbortSignal` stops local waiting only. Call `cancel` to ask the server to stop
134
+ the job. A cancel acknowledgement is not proof that the job has stopped; read
135
+ the returned status until it is terminal. Status and result access still follow
136
+ the server's current job-status contract. This helper cannot recover a result
137
+ that the server no longer exposes.
138
+
79
139
  ## Program job handlers
80
140
 
81
141
  A Gem can declare a job that runs code from its published source:
@@ -122,7 +182,67 @@ export async function syncOrders(
122
182
  `saveNextBatch` is Gem code. Check `signal.aborted` before each external write.
123
183
  Make writes safe to repeat. Keep progress messages and checkpoints small. Do
124
184
  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.
185
+ job. The handler completes the job when it returns. Each progress update and
186
+ checkpoint also tells Uru the job is alive.
187
+
188
+ ### A job that survives a lost machine
189
+
190
+ Uru runs a lost job attempt again from its start, under the same job run, with
191
+ the last checkpoint. Put the job's writes in `jobs.step` so that the next
192
+ attempt can run safely.
193
+
194
+ A step runs once per job run: its result is saved in the checkpoint, and the
195
+ next attempt returns the saved result without running the step. Inside a step,
196
+ each action, job start and Dataset row write gets a default key that the job
197
+ run owns (`uru-job:<run id>:...`). A step that was cut short runs again from
198
+ its start and sends the same keys in the same order, so Uru answers each call
199
+ from its first run instead of running it twice, and the job stays retryable.
200
+
201
+ Outside a step, a call gets a random key, and a write there ends the job's
202
+ automatic retry. A job that resumes from its own checkpoint does not make the
203
+ same calls again, so Uru cannot tell which earlier call a later one repeats.
204
+
205
+ ```ts
206
+ const ids = await uru.jobs.step('load', async () => {
207
+ const page = await uru.datasets.queryRows('invoices', { where: [] });
208
+ return page.rows.map(row => row.id);
209
+ });
210
+ for (const id of ids) {
211
+ await uru.jobs.step(`send ${id}`, async step => {
212
+ await uru.actions.run('send_invoice', { id });
213
+ await uru.files.createOutput({
214
+ name: `${id}.txt`,
215
+ contentType: 'text/plain',
216
+ content: new TextEncoder().encode(`Sent ${id}`),
217
+ idempotencyKey: step.idempotencyKey,
218
+ });
219
+ });
220
+ }
221
+ ```
222
+
223
+ - Give each step its own name, and run steps one at a time. While a step runs,
224
+ make only that step's calls.
225
+ - A step must make the same calls in the same order each time it runs. Save
226
+ your own checkpoint between steps, not inside one: Uru refuses
227
+ `jobs.checkpoint` while a step runs. Use `jobs.progress` inside a step.
228
+ - A call sent again under its key must carry the same input, or Uru refuses
229
+ it with a conflict. Make a time, a random id or a Dataset revision you pin
230
+ in a step of its own, and pass the saved result to the call: the next
231
+ attempt reuses it.
232
+ - Return small JSON from a step: ids and counts, not rows or files. The
233
+ checkpoint, with every saved step, must stay under 64 KB. The handler's
234
+ `checkpoint` holds the saved steps under `$uruSteps`; a checkpoint you save
235
+ keeps them, also when you save a changed copy of the one you received.
236
+ - `step.idempotencyKey` is the same on every attempt of the run. Use it for
237
+ one write of the step: a file output, or a request to an external API that
238
+ takes an idempotency key.
239
+ - A call that Uru cannot replay ends the job's automatic retry before it is
240
+ sent: an endpoint, `sqlWrite`, or a write with a key the run does not own
241
+ (a call outside a step, your own `idempotencyKey`, or
242
+ `dampers.defaultIdempotencyKeys: false`).
243
+ A lost attempt after such a call fails, so a person can check what it wrote.
244
+ - Uru cannot see an HTTP request the job sends to another service. Give that
245
+ service `step.idempotencyKey` when it accepts one.
126
246
 
127
247
  For a browser calling a public Gem page's runtime, build the client directly:
128
248
 
@@ -147,16 +267,36 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
147
267
  Surface them. A Gem that hides expensive work behind a spinner is a Gem whose
148
268
  users cannot tell a slow query from a blocked budget.
149
269
  - **Server-side Datasets.** Read with `queryRows`; write with `insertRows`,
150
- `upsertRows`, `deleteRows`, `restoreRows` and `sqlWrite`. Totals, counts and
151
- top-N summaries must come from the server, never from one fetched page.
270
+ `upsertRows`, `upsertRowViews`, `deleteRows`, `restoreRows` and `sqlWrite`.
271
+ Totals, counts and top-N summaries must come from the server, never from one
272
+ fetched page.
152
273
  - **Retry and refresh controls, on by default.** Each invocation gets a unique
153
274
  idempotency key. Its HTTP retries keep that key. Equal calls from separate
154
- clients or later calls remain separate operations. The client also backs off
275
+ clients or later calls remain separate operations. Inside a program job's
276
+ step the key belongs to the job run instead, so a later attempt that runs
277
+ the step again sends it again (see "A job that survives a lost machine"). The client also backs off
155
278
  on HTTP 429 and throttles `forceRefresh` per capability. Override these
156
279
  controls through `dampers`; see `UruRunawayDamperOptions`. Supply an explicit
157
280
  `idempotencyKey` when your application retries the same logical operation.
158
281
  A custom retry wait can accept the optional `AbortSignal` to stop its own
159
282
  work. The SDK still bounds the call when that wait ignores the signal.
283
+ - **Calls ride out a restarting server.** When Uru gives no answer (a failed
284
+ or reset connection, a reply cut off after its headers, HTTP 502 or 504, or
285
+ a 503 without an Uru error code),
286
+ the client sends the call again after about 0.5, 1, 2, 4, 8, 8 and 8
287
+ seconds, each stretched by up to twice for jitter: about a minute in all.
288
+ Each wait reports a `reconnecting` status event. An action or a job start
289
+ sends the same body with the same key, so the server replays the first run
290
+ instead of running it twice. A query sends a new key each time. Job status
291
+ reads, job cancels, `jobs.progress` and `jobs.checkpoint` are always sent
292
+ again. A Dataset row write is sent again with its key (each call gets one
293
+ when you give none). An endpoint, a server function and `sqlWrite` are never
294
+ sent again, because they have no stored result to replay. `sqlWrite` still
295
+ sends a key: if your code sends the same statement again with the same
296
+ `idempotencyKey`, each row change it planned is replayed when the plan is
297
+ unchanged and refused when it changed, so the statement never writes twice. The caller's
298
+ `signal` and `timeoutMs` end the waits. Set `dampers.maxTransportRetries` to
299
+ `0` to turn resends off.
160
300
 
161
301
  ## Transport values
162
302
 
@@ -174,7 +314,7 @@ before either action. `timeoutMs`, when set, must be an integer from 1,000 to
174
314
  Pass an `AbortSignal` as `signal` to cancel a capability call, job status read,
175
315
  or job cancel request. The signal is local to the SDK and is never sent in the
176
316
  JSON body. When `timeoutMs` is set, it also bounds the network request, response
177
- body read, and any 429 retry wait.
317
+ body read, any 429 retry wait and any resend wait.
178
318
 
179
319
  Response diagnostics use the same JSON rules. Invalid diagnostics in a success
180
320
  response cause `UruAppRuntimeError`. An HTTP error keeps its original status and
@@ -223,6 +363,16 @@ the decoder's row type. Dataset writes accept the result decoder as their third
223
363
  argument. A decoder error is the caller's error and propagates unchanged. A
224
364
  transport or platform failure remains `UruAppRuntimeError`.
225
365
 
366
+ Native Dataset V2 rows keep customer fields in `row.fields`. The row's `id`,
367
+ `rowVersion`, `createdAt`, `updatedAt`, and `deleted` values are Uru metadata.
368
+ Use `datasetRowForMutation(row)` with `upsertRowViews` to keep row identity
369
+ separate from customer data. This saves a customer field named `id` without
370
+ changing the native row id. It also sends `rowVersion` as the row precondition.
371
+ Pass the page's `revision` as `expectedDatasetRevision` when it must match the
372
+ read. Use flat `upsertRows` calls for new or partial rows that do not need to
373
+ carry a customer field named `id`. A customer field named `fields` is read or
374
+ edited as `row.fields.fields`, because `row.fields` is the customer-field map.
375
+
226
376
  Capability and job-status envelopes can omit `result` or return `null` while
227
377
  work is pending. The client preserves both forms without calling the decoder.
228
378
  Typed callers must still handle an absent or null result.
@@ -259,6 +409,13 @@ Output reads and writes are limited to 10 MiB. Later approved releases of the
259
409
  same Gem can read its outputs in the same environment. Preview builds cannot
260
410
  create unattended outputs. Every request checks current access.
261
411
 
412
+ A person can delete an output's Library file forever. The output then stays in
413
+ `listOutputs` with the `fileId` it had and `fileDeleted: true`, and
414
+ `readOutput` throws `UruAppRuntimeError` with `status` 410. Show such an
415
+ output as deleted. `createOutput` with the idempotency key of that output also
416
+ throws with `status` 410 and writes nothing: to write the file again, use a new
417
+ idempotency key.
418
+
262
419
  ## Errors
263
420
 
264
421
  Transport and platform failures throw `UruAppRuntimeError`. Decoder failures
@@ -291,9 +448,10 @@ platform's runtime contract moves, this package moves with it — additively whe
291
448
  it can, and in a major version where it cannot. Pin an exact version if you need
292
449
  a build to be reproducible; Uru's own Gem templates do.
293
450
 
294
- The public surface is `createUruServerContext`, `createUruAppRuntimeClient`,
295
- `UruAppRuntimeError`, and the exported types. Nothing else is API, even if you
296
- can reach it.
451
+ The public surface includes `createUruServerContext`,
452
+ `createUruAppRuntimeClient`, `createUruBackgroundJobCoordinator`,
453
+ `createUruUploadsContext`, `UruAppRuntimeError`, and the exported types.
454
+ Nothing else is API, even if you can reach it.
297
455
 
298
456
  ## Documentation
299
457
 
@@ -320,10 +478,11 @@ await uru.datasets.upsertRows('contacts', [{ id: rowId, name: 'Updated' }],
320
478
  ```
321
479
 
322
480
  Keep the key for that save across retries. Hosted Gems scope it to the verified
323
- Gem and viewer. A repeated request can report a conflict if preparing the row
324
- would now produce different values. Read the saved record before retrying;
325
- confirm the intended fields were saved or ask the user to resolve the conflict.
326
- Never assign a new key merely to bypass a conflict. Browser conditional saves
481
+ Gem and viewer. A repeated request with the same key and the same rows returns
482
+ the first result, even after the first send was saved and the revision moved
483
+ on. The same key with different rows is a conflict. Read the saved record
484
+ before retrying; confirm the intended fields were saved or ask the user to
485
+ resolve the conflict. Never assign a new key merely to bypass a conflict. Browser conditional saves
327
486
  require a built Gem runtime, including GitHub previews. External datasets do
328
487
  not supply a native revision and remain read-only.
329
488
 
@@ -0,0 +1,7 @@
1
+ import type { CreateUruBackgroundJobCoordinatorOptions, UruBackgroundJobCoordinator } from "./types.js";
2
+ /**
3
+ * Coordinate the released `job`, `jobStatus`, and `cancelJob` operations.
4
+ * The store saves request identity and control intent only; the server remains
5
+ * authoritative for execution state and results.
6
+ */
7
+ export declare const createUruBackgroundJobCoordinator: (options: CreateUruBackgroundJobCoordinatorOptions) => UruBackgroundJobCoordinator;