@uru-intelligence/app 2.1.2 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -155,6 +155,8 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
155
155
  on HTTP 429 and throttles `forceRefresh` per capability. Override these
156
156
  controls through `dampers`; see `UruRunawayDamperOptions`. Supply an explicit
157
157
  `idempotencyKey` when your application retries the same logical operation.
158
+ A custom retry wait can accept the optional `AbortSignal` to stop its own
159
+ work. The SDK still bounds the call when that wait ignores the signal.
158
160
 
159
161
  ## Transport values
160
162
 
@@ -169,6 +171,11 @@ Input that exceeds the JavaScript runtime's serialization limit also fails
169
171
  before either action. `timeoutMs`, when set, must be an integer from 1,000 to
170
172
  60,000, as required by the runtime HTTP contract.
171
173
 
174
+ Pass an `AbortSignal` as `signal` to cancel a capability call, job status read,
175
+ or job cancel request. The signal is local to the SDK and is never sent in the
176
+ JSON body. When `timeoutMs` is set, it also bounds the network request, response
177
+ body read, and any 429 retry wait.
178
+
172
179
  Response diagnostics use the same JSON rules. Invalid diagnostics in a success
173
180
  response cause `UruAppRuntimeError`. An HTTP error keeps its original status and
174
181
  body. Diagnostic keys remain opaque; the client does not change their casing.
package/dist/dampers.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface ResolvedDamperConfig {
7
7
  readonly rateLimitMaxDelayMs: number;
8
8
  readonly forceRefreshMinIntervalMs: number;
9
9
  readonly now: () => number;
10
- readonly sleep: (ms: number) => Promise<void>;
10
+ readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
11
11
  }
12
12
  /** Caller-supplied damper overrides; every field defaults (see {@link resolveDamperConfig}). */
13
13
  export interface UruRunawayDamperOptions {
@@ -23,8 +23,8 @@ export interface UruRunawayDamperOptions {
23
23
  forceRefreshMinIntervalMs?: number;
24
24
  /** Clock (ms); injectable for tests. Defaults to `Date.now`. */
25
25
  now?: () => number;
26
- /** Async delay; injectable for tests. Defaults to `setTimeout`. */
27
- sleep?: (ms: number) => Promise<void>;
26
+ /** Async delay; injectable for tests. Defaults to an abortable `setTimeout`. */
27
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
28
28
  }
29
29
  /** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
30
30
  export declare const resolveDamperConfig: (options: UruRunawayDamperOptions | undefined) => ResolvedDamperConfig;
package/dist/dampers.js CHANGED
@@ -10,13 +10,31 @@ const positiveOr = (value, fallback) => typeof value === "number" && Number.isFi
10
10
  const nonNegativeOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0
11
11
  ? value
12
12
  : fallback;
13
- const defaultSleep = async (ms) => {
14
- const { promise, resolve } = Promise.withResolvers();
15
- setTimeout(() => {
16
- resolve(true);
13
+ const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
14
+ let timeout;
15
+ const abort = () => {
16
+ cleanup();
17
+ reject(signal?.reason ??
18
+ new DOMException("The operation was aborted.", "AbortError"));
19
+ };
20
+ const cleanup = () => {
21
+ clearTimeout(timeout);
22
+ signal?.removeEventListener("abort", abort);
23
+ };
24
+ timeout = setTimeout(() => {
25
+ cleanup();
26
+ resolve();
17
27
  }, Math.max(0, ms));
18
- await promise;
19
- };
28
+ if (signal === undefined)
29
+ return;
30
+ if (signal.aborted) {
31
+ abort();
32
+ return;
33
+ }
34
+ signal.addEventListener("abort", abort, { once: true });
35
+ if (signal.aborted)
36
+ abort();
37
+ });
20
38
  /** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
21
39
  export const resolveDamperConfig = (options) => ({
22
40
  defaultIdempotencyKeys: options?.defaultIdempotencyKeys ?? true,
@@ -0,0 +1,8 @@
1
+ import type { UruAppRuntimeInvocationOptions } from "./types.js";
2
+ export declare const assertRuntimeSignal: (value: unknown) => void;
3
+ export declare const validateRuntimeInvocationOptions: (options?: UruAppRuntimeInvocationOptions) => void;
4
+ export declare const withRuntimeRequestSignal: <T>(options: UruAppRuntimeInvocationOptions | undefined, action: (signal: AbortSignal | undefined) => Promise<T>) => Promise<T>;
5
+ export declare const abortReason: (signal: AbortSignal) => unknown;
6
+ /** Race a fetch, body read, or retry wait against the same request signal. */
7
+ export declare const awaitWithAbort: <T>(promise: Promise<T>, signal: AbortSignal | undefined) => Promise<T>;
8
+ export declare const readRuntimeResponseBody: (response: Response, signal?: AbortSignal) => Promise<unknown>;
@@ -0,0 +1,107 @@
1
+ import { UruAppRuntimeError } from "./errors.js";
2
+ export const assertRuntimeSignal = (value) => {
3
+ if (value !== undefined &&
4
+ (typeof AbortSignal === "undefined" || !(value instanceof AbortSignal))) {
5
+ throw new UruAppRuntimeError("Invalid app runtime signal.", {
6
+ body: null,
7
+ status: 0,
8
+ });
9
+ }
10
+ };
11
+ const assertRuntimeTimeout = (value) => {
12
+ if (!Number.isInteger(value) || value < 1000 || value > 60_000) {
13
+ throw new UruAppRuntimeError("Invalid app runtime timeoutMs.", {
14
+ body: value,
15
+ status: 0,
16
+ });
17
+ }
18
+ };
19
+ export const validateRuntimeInvocationOptions = (options) => {
20
+ assertRuntimeSignal(options?.signal);
21
+ if (options?.timeoutMs !== undefined) {
22
+ assertRuntimeTimeout(options.timeoutMs);
23
+ }
24
+ };
25
+ const runtimeSignalIsAborted = (signal) => signal?.aborted === true;
26
+ /**
27
+ * Make one deadline for the whole network operation. The regular timer keeps
28
+ * the deadline live even when the caller has no other active event-loop work.
29
+ * The owner clears it after the response body or aborted request settles.
30
+ */
31
+ const runtimeRequestSignal = (options) => {
32
+ validateRuntimeInvocationOptions(options);
33
+ const timeoutMs = options?.timeoutMs;
34
+ const callerSignal = options?.signal;
35
+ if (timeoutMs === undefined) {
36
+ return callerSignal === undefined
37
+ ? { dispose: () => undefined }
38
+ : { signal: callerSignal, dispose: () => undefined };
39
+ }
40
+ const timeoutController = new AbortController();
41
+ const timeout = setTimeout(() => {
42
+ timeoutController.abort(new DOMException("The operation timed out.", "TimeoutError"));
43
+ }, timeoutMs);
44
+ return {
45
+ signal: callerSignal === undefined
46
+ ? timeoutController.signal
47
+ : AbortSignal.any([callerSignal, timeoutController.signal]),
48
+ dispose: () => clearTimeout(timeout),
49
+ };
50
+ };
51
+ export const withRuntimeRequestSignal = async (options, action) => {
52
+ const request = runtimeRequestSignal(options);
53
+ try {
54
+ return await action(request.signal);
55
+ }
56
+ finally {
57
+ request.dispose();
58
+ }
59
+ };
60
+ export const abortReason = (signal) => signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
61
+ /** Race a fetch, body read, or retry wait against the same request signal. */
62
+ export const awaitWithAbort = async (promise, signal) => {
63
+ if (signal === undefined)
64
+ return await promise;
65
+ if (signal.aborted)
66
+ throw abortReason(signal);
67
+ return await new Promise((resolve, reject) => {
68
+ const onAbort = () => {
69
+ signal.removeEventListener("abort", onAbort);
70
+ reject(abortReason(signal));
71
+ };
72
+ signal.addEventListener("abort", onAbort, { once: true });
73
+ void promise.then(value => {
74
+ signal.removeEventListener("abort", onAbort);
75
+ resolve(value);
76
+ }, error => {
77
+ signal.removeEventListener("abort", onAbort);
78
+ reject(error);
79
+ });
80
+ });
81
+ };
82
+ export const readRuntimeResponseBody = async (response, signal) => {
83
+ if (runtimeSignalIsAborted(signal)) {
84
+ void response.body?.cancel().catch(() => undefined);
85
+ throw abortReason(signal);
86
+ }
87
+ const parsed = Promise.resolve()
88
+ .then(() => {
89
+ if (runtimeSignalIsAborted(signal))
90
+ throw abortReason(signal);
91
+ return response.json();
92
+ })
93
+ .catch(() => {
94
+ if (runtimeSignalIsAborted(signal))
95
+ throw abortReason(signal);
96
+ return null;
97
+ });
98
+ try {
99
+ return await awaitWithAbort(parsed, signal);
100
+ }
101
+ catch (error) {
102
+ if (runtimeSignalIsAborted(signal)) {
103
+ void response.body?.cancel().catch(() => undefined);
104
+ }
105
+ throw error;
106
+ }
107
+ };
@@ -0,0 +1,21 @@
1
+ import type { DamperRuntime } from "./transport.js";
2
+ import type { UruAppRuntimeCapabilityType, UruAppRuntimeEvent } from "./types.js";
3
+ import type { RuntimeFetch } from "./runtime.js";
4
+ export interface InvocationFetchArguments {
5
+ capabilityName: string;
6
+ capabilityType: UruAppRuntimeCapabilityType;
7
+ damper: DamperRuntime;
8
+ deploymentId: string;
9
+ emit: (event: UruAppRuntimeEvent) => void;
10
+ headers: Headers;
11
+ requestBody: string;
12
+ requestId: string;
13
+ runtimeFetch: RuntimeFetch;
14
+ signal?: AbortSignal;
15
+ url: string;
16
+ }
17
+ export interface RuntimeFetchResult {
18
+ body: unknown;
19
+ response: Response;
20
+ }
21
+ export declare const fetchInvocation: (args: InvocationFetchArguments, attempt?: number) => Promise<RuntimeFetchResult>;
@@ -0,0 +1,48 @@
1
+ import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
2
+ import { awaitWithAbort, readRuntimeResponseBody, } from "./transport-deadline.js";
3
+ export const fetchInvocation = async (args, attempt = 0) => {
4
+ // Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
5
+ // would hand the fetch `args` as its receiver — the same class of mistake
6
+ // that broke the global one.
7
+ const { runtimeFetch } = args;
8
+ args.signal?.throwIfAborted();
9
+ const response = await awaitWithAbort(Promise.resolve().then(() => {
10
+ args.signal?.throwIfAborted();
11
+ return runtimeFetch(args.url, {
12
+ body: args.requestBody,
13
+ headers: args.headers,
14
+ method: "POST",
15
+ ...(args.signal === undefined ? {} : { signal: args.signal }),
16
+ });
17
+ }), args.signal);
18
+ const body = await readRuntimeResponseBody(response, args.signal);
19
+ const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
20
+ if (!shouldRetry) {
21
+ return { body, response };
22
+ }
23
+ const delayMs = computeRateLimitBackoffMs({
24
+ attempt,
25
+ baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
26
+ maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
27
+ retryAfterSeconds: parseRetryAfterSeconds({
28
+ body,
29
+ header: response.headers.get("retry-after"),
30
+ }),
31
+ });
32
+ args.signal?.throwIfAborted();
33
+ args.emit({
34
+ capabilityName: args.capabilityName,
35
+ capabilityType: args.capabilityType,
36
+ deploymentId: args.deploymentId,
37
+ requestId: args.requestId,
38
+ retryAfterSeconds: Math.ceil(delayMs / 1000),
39
+ state: "rate_limited",
40
+ type: "status",
41
+ });
42
+ args.signal?.throwIfAborted();
43
+ const sleepPromise = args.signal === undefined
44
+ ? args.damper.config.sleep(delayMs)
45
+ : args.damper.config.sleep(delayMs, args.signal);
46
+ await awaitWithAbort(sleepPromise, args.signal);
47
+ return await fetchInvocation(args, attempt + 1);
48
+ };
package/dist/transport.js CHANGED
@@ -15,10 +15,11 @@
15
15
  * for by exporting four internal helpers from it. Every edge here points at a
16
16
  * module that imports nothing back.
17
17
  */
18
- import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
19
18
  import { runtimeErrorMessage } from "./error-response.js";
20
19
  import { UruAppRuntimeError } from "./errors.js";
21
20
  import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
21
+ import { abortReason, awaitWithAbort, readRuntimeResponseBody, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
22
+ import { fetchInvocation } from "./transport-invocation.js";
22
23
  import { isRuntimeJsonObject } from "./transport-json.js";
23
24
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24
25
  const httpRecord = (value, label) => {
@@ -167,20 +168,13 @@ const encodeCapabilityPath = (capabilityType, capabilityName) => {
167
168
  const makeRuntimeRequestId = () => `uru_app_${Math.random().toString(36).slice(2)}`;
168
169
  const runtimeHttpRequestOptions = (options) => {
169
170
  const transport = {};
171
+ validateRuntimeInvocationOptions(options);
170
172
  const idempotencyKey = options?.idempotencyKey;
171
173
  if (idempotencyKey !== undefined && idempotencyKey !== "") {
172
174
  transport.idempotencyKey = idempotencyKey;
173
175
  }
174
176
  const timeoutMs = options?.timeoutMs;
175
177
  if (timeoutMs !== undefined) {
176
- if (!Number.isInteger(timeoutMs) ||
177
- timeoutMs < 1000 ||
178
- timeoutMs > 60_000) {
179
- throw new UruAppRuntimeError("Invalid app runtime timeoutMs.", {
180
- body: timeoutMs,
181
- status: 0,
182
- });
183
- }
184
178
  transport.timeoutMs = timeoutMs;
185
179
  }
186
180
  if (options?.forceRefresh === true) {
@@ -350,43 +344,6 @@ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper,
350
344
  });
351
345
  }
352
346
  };
353
- const responseBody = async (response) => await response.json().catch(() => null);
354
- const fetchInvocation = async (args, attempt = 0) => {
355
- // Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
356
- // would hand the fetch `args` as its receiver — the same class of mistake
357
- // that broke the global one.
358
- const { runtimeFetch } = args;
359
- const response = await runtimeFetch(args.url, {
360
- body: args.requestBody,
361
- headers: args.headers,
362
- method: "POST",
363
- });
364
- const body = await responseBody(response);
365
- const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
366
- if (!shouldRetry) {
367
- return { body, response };
368
- }
369
- const delayMs = computeRateLimitBackoffMs({
370
- attempt,
371
- baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
372
- maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
373
- retryAfterSeconds: parseRetryAfterSeconds({
374
- body,
375
- header: response.headers.get("retry-after"),
376
- }),
377
- });
378
- emitRuntimeEvent(args.invocationOptions, {
379
- capabilityName: args.capabilityName,
380
- capabilityType: args.capabilityType,
381
- deploymentId: args.deploymentId,
382
- requestId: args.requestId,
383
- retryAfterSeconds: Math.ceil(delayMs / 1000),
384
- state: "rate_limited",
385
- type: "status",
386
- });
387
- await args.damper.config.sleep(delayMs);
388
- return await fetchInvocation(args, attempt + 1);
389
- };
390
347
  const normalizedInvocationResponse = (runtimeResponse, fallbackIdentity, fallbackCapabilityType, state, diagnostics) => ({
391
348
  capabilityName: runtimeResponse.capabilityName === ""
392
349
  ? fallbackIdentity.capabilityName
@@ -415,6 +372,9 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
415
372
  const { capabilityName, deploymentId } = identity;
416
373
  const runtimeInput = invocationInput(input);
417
374
  const transport = runtimeHttpRequestOptions(invocationOptions);
375
+ if (invocationOptions?.signal?.aborted === true) {
376
+ throw abortReason(invocationOptions.signal);
377
+ }
418
378
  // P2 damper: a requested forceRefresh is honored only if it clears the
419
379
  // per-capability throttle; otherwise the call is sent WITHOUT force_refresh so
420
380
  // it can be served from cache instead of hammering past it.
@@ -444,18 +404,19 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
444
404
  // retries beyond the first send; the loop performs at most
445
405
  // `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
446
406
  // (capped) before falling through to the normal failure path.
447
- const { body, response } = await fetchInvocation({
407
+ const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
448
408
  capabilityName,
449
409
  capabilityType,
450
410
  damper,
451
411
  deploymentId,
412
+ emit: event => emitRuntimeEvent(invocationOptions, event),
452
413
  headers,
453
- ...(invocationOptions === undefined ? {} : { invocationOptions }),
454
414
  requestBody,
455
415
  requestId,
456
416
  runtimeFetch,
417
+ ...(requestSignal === undefined ? {} : { signal: requestSignal }),
457
418
  url,
458
- });
419
+ }));
459
420
  if (!response.ok) {
460
421
  const message = runtimeErrorMessage(body, `Uru app runtime call failed with HTTP ${response.status}`);
461
422
  emitRuntimeEvent(invocationOptions, {
@@ -558,6 +519,8 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
558
519
  const runtimeFetch = resolveRuntimeFetch(options);
559
520
  const identity = jobIdentity(options, executionId);
560
521
  const { deploymentId, executionId: normalizedExecutionId } = identity;
522
+ validateRuntimeInvocationOptions(invocationOptions);
523
+ invocationOptions?.signal?.throwIfAborted();
561
524
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
562
525
  emitRuntimeEvent(invocationOptions, {
563
526
  capabilityName: "",
@@ -570,8 +533,22 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
570
533
  });
571
534
  const url = jobExecutionUrl(options, identity);
572
535
  const headers = new Headers(await resolveHeaders(options.headers));
573
- const response = await runtimeFetch(url, { headers, method: "GET" });
574
- const body = await responseBody(response);
536
+ const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
537
+ if (signal?.aborted === true) {
538
+ throw abortReason(signal);
539
+ }
540
+ const response = await awaitWithAbort(Promise.resolve().then(() => {
541
+ if (signal?.aborted === true) {
542
+ throw abortReason(signal);
543
+ }
544
+ return runtimeFetch(url, {
545
+ headers,
546
+ method: "GET",
547
+ ...(signal === undefined ? {} : { signal }),
548
+ });
549
+ }), signal);
550
+ return { body: await readRuntimeResponseBody(response, signal), response };
551
+ });
575
552
  if (!response.ok && response.status !== 202) {
576
553
  const message = runtimeErrorMessage(body, `Uru app runtime job status failed with HTTP ${response.status}`);
577
554
  emitRuntimeEvent(invocationOptions, {
@@ -615,11 +592,27 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
615
592
  const runtimeFetch = resolveRuntimeFetch(options);
616
593
  const identity = jobIdentity(options, executionId);
617
594
  const { deploymentId, executionId: normalizedExecutionId } = identity;
595
+ validateRuntimeInvocationOptions(invocationOptions);
596
+ invocationOptions?.signal?.throwIfAborted();
618
597
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
619
598
  const url = jobExecutionUrl(options, identity, true);
620
599
  const headers = new Headers(await resolveHeaders(options.headers));
621
- const response = await runtimeFetch(url, { headers, method: "POST" });
622
- const body = await responseBody(response);
600
+ const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
601
+ if (signal?.aborted === true) {
602
+ throw abortReason(signal);
603
+ }
604
+ const response = await awaitWithAbort(Promise.resolve().then(() => {
605
+ if (signal?.aborted === true) {
606
+ throw abortReason(signal);
607
+ }
608
+ return runtimeFetch(url, {
609
+ headers,
610
+ method: "POST",
611
+ ...(signal === undefined ? {} : { signal }),
612
+ });
613
+ }), signal);
614
+ return { body: await readRuntimeResponseBody(response, signal), response };
615
+ });
623
616
  if (!response.ok) {
624
617
  const message = runtimeErrorMessage(body, `Uru app runtime job cancel failed with HTTP ${response.status}`);
625
618
  emitRuntimeEvent(invocationOptions, {
package/dist/types.d.ts CHANGED
@@ -48,6 +48,8 @@ export interface UruAppRuntimeEvent<TResult = unknown> {
48
48
  /** Per-call options accepted by every capability method. */
49
49
  export interface UruAppRuntimeInvocationOptions {
50
50
  idempotencyKey?: string;
51
+ /** Abort the network call, response-body read, or retry wait. */
52
+ signal?: AbortSignal;
51
53
  timeoutMs?: number;
52
54
  forceRefresh?: boolean;
53
55
  requestId?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.1.2",
3
+ "version": "2.1.3",
4
4
  "private": false,
5
5
  "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
6
6
  "keywords": [