@uru-intelligence/app 2.1.5 → 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.
@@ -1,27 +1,75 @@
1
- import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
2
- import { awaitWithAbort, readRuntimeResponseBody, } from "./transport-deadline.js";
3
- export const fetchInvocation = async (args, attempt = 0) => {
1
+ import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, } from "./dampers.js";
2
+ import { awaitWithAbort } from "./transport-deadline.js";
3
+ import { canResend, isLostRequest, isLostResponse, readRuntimeResponseBody, resendDelayMs, waitBeforeResend, } from "./transport-retry.js";
4
+ const FIRST_SEND = { rateLimited: 0, resent: 0 };
5
+ /** One send. A lost request comes back as an outcome so the caller can decide. */
6
+ const sendOnce = async (runtimeFetch, url, init, signal) => {
7
+ signal?.throwIfAborted();
8
+ let response;
9
+ try {
10
+ response = await awaitWithAbort(Promise.resolve().then(() => {
11
+ signal?.throwIfAborted();
12
+ return runtimeFetch(url, {
13
+ ...init,
14
+ ...(signal === undefined ? {} : { signal }),
15
+ });
16
+ }), signal);
17
+ }
18
+ catch (error) {
19
+ if (isLostRequest(error, signal))
20
+ return { error, kind: "lost" };
21
+ throw error;
22
+ }
23
+ const { body, cut } = await readRuntimeResponseBody(response, signal);
24
+ return { kind: cut ? "cut" : "response", result: { body, response } };
25
+ };
26
+ /** Whether a send ended without an answer from the platform. */
27
+ const isLost = (outcome) => outcome.kind !== "response" ||
28
+ isLostResponse(outcome.result.response.status, outcome.result.body);
29
+ /** Report the coming resend, then wait for it. */
30
+ const reconnect = async (damper, resent, signal, report) => {
31
+ const delayMs = resendDelayMs(resent, damper.config.random);
32
+ report(Math.ceil(delayMs / 1000));
33
+ await waitBeforeResend(damper.config, delayMs, signal);
34
+ };
35
+ export const fetchInvocation = async (args, counts = FIRST_SEND) => {
4
36
  // Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
5
37
  // would hand the fetch `args` as its receiver — the same class of mistake
6
38
  // that broke the global one.
7
39
  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 }),
40
+ const outcome = await sendOnce(runtimeFetch, args.url, {
41
+ body: args.requestBody(counts.resent),
42
+ headers: args.headers,
43
+ method: "POST",
44
+ }, args.signal);
45
+ if (isLost(outcome) &&
46
+ args.resendLost &&
47
+ canResend(args.damper.config, counts.resent)) {
48
+ await reconnect(args.damper, counts.resent, args.signal, retryAfterSeconds => args.emit({
49
+ capabilityName: args.capabilityName,
50
+ capabilityType: args.capabilityType,
51
+ deploymentId: args.deploymentId,
52
+ requestId: args.requestId,
53
+ retryAfterSeconds,
54
+ state: "reconnecting",
55
+ type: "status",
56
+ }));
57
+ return await fetchInvocation(args, {
58
+ ...counts,
59
+ resent: counts.resent + 1,
16
60
  });
17
- }), args.signal);
18
- const body = await readRuntimeResponseBody(response, args.signal);
19
- const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
61
+ }
62
+ if (outcome.kind === "lost")
63
+ throw outcome.error;
64
+ const { body, response } = outcome.result;
65
+ const shouldRetry = response.status === 429 &&
66
+ parseRetryable(body) !== false &&
67
+ counts.rateLimited < args.damper.config.maxRateLimitRetries;
20
68
  if (!shouldRetry) {
21
69
  return { body, response };
22
70
  }
23
- const delayMs = computeRateLimitBackoffMs({
24
- attempt,
71
+ const delayMs = computeRateLimitRetryDelayMs({
72
+ attempt: counts.rateLimited,
25
73
  baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
26
74
  maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
27
75
  retryAfterSeconds: parseRetryAfterSeconds({
@@ -44,5 +92,83 @@ export const fetchInvocation = async (args, attempt = 0) => {
44
92
  ? args.damper.config.sleep(delayMs)
45
93
  : args.damper.config.sleep(delayMs, args.signal);
46
94
  await awaitWithAbort(sleepPromise, args.signal);
47
- return await fetchInvocation(args, attempt + 1);
95
+ return await fetchInvocation(args, {
96
+ ...counts,
97
+ rateLimited: counts.rateLimited + 1,
98
+ });
99
+ };
100
+ const jobReconnectingEvent = (args, retryAfterSeconds) => ({
101
+ capabilityName: "",
102
+ capabilityType: "job",
103
+ deploymentId: args.deploymentId,
104
+ executionId: args.executionId,
105
+ requestId: args.requestId,
106
+ retryAfterSeconds,
107
+ state: "reconnecting",
108
+ type: "status",
109
+ });
110
+ /**
111
+ * Fetch one accepted execution's status with bounded, same-identity retries.
112
+ * A status read changes nothing, so a lost response is always read again.
113
+ */
114
+ export const fetchJobStatus = async (args, counts = FIRST_SEND) => {
115
+ const { runtimeFetch } = args;
116
+ const outcome = await sendOnce(runtimeFetch, args.url, { headers: args.headers, method: "GET" }, args.signal);
117
+ if (isLost(outcome) && canResend(args.damper.config, counts.resent)) {
118
+ await reconnect(args.damper, counts.resent, args.signal, retryAfterSeconds => args.emit(jobReconnectingEvent(args, retryAfterSeconds)));
119
+ return await fetchJobStatus(args, {
120
+ ...counts,
121
+ resent: counts.resent + 1,
122
+ });
123
+ }
124
+ if (outcome.kind === "lost")
125
+ throw outcome.error;
126
+ const { body, response } = outcome.result;
127
+ const shouldRetry = response.status === 429 &&
128
+ parseRetryable(body) !== false &&
129
+ counts.rateLimited < args.damper.config.maxRateLimitRetries;
130
+ if (!shouldRetry) {
131
+ return { body, response };
132
+ }
133
+ const retryAfterSeconds = parseRetryAfterSeconds({
134
+ body,
135
+ header: response.headers.get("retry-after"),
136
+ });
137
+ const delayMs = computeRateLimitRetryDelayMs({
138
+ attempt: counts.rateLimited,
139
+ baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
140
+ maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
141
+ retryAfterSeconds,
142
+ });
143
+ args.signal?.throwIfAborted();
144
+ args.emit({
145
+ capabilityName: "",
146
+ capabilityType: "job",
147
+ deploymentId: args.deploymentId,
148
+ executionId: args.executionId,
149
+ requestId: args.requestId,
150
+ retryAfterSeconds: retryAfterSeconds ?? Math.ceil(delayMs / 1000),
151
+ state: "rate_limited",
152
+ type: "status",
153
+ });
154
+ await awaitWithAbort(args.damper.config.sleep(delayMs, args.signal), args.signal);
155
+ return await fetchJobStatus(args, {
156
+ ...counts,
157
+ rateLimited: counts.rateLimited + 1,
158
+ });
159
+ };
160
+ /**
161
+ * Ask for one execution to stop. A cancel names its execution and asks for
162
+ * the same end state every time, so a lost response is sent again.
163
+ */
164
+ export const fetchJobCancel = async (args, resent = 0) => {
165
+ const { runtimeFetch } = args;
166
+ const outcome = await sendOnce(runtimeFetch, args.url, { headers: args.headers, method: "POST" }, args.signal);
167
+ if (isLost(outcome) && canResend(args.damper.config, resent)) {
168
+ await reconnect(args.damper, resent, args.signal, retryAfterSeconds => args.emit(jobReconnectingEvent(args, retryAfterSeconds)));
169
+ return await fetchJobCancel(args, resent + 1);
170
+ }
171
+ if (outcome.kind === "lost")
172
+ throw outcome.error;
173
+ return outcome.result;
48
174
  };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Resends for a response the platform never gave.
3
+ *
4
+ * A deploy, a crash or a memory kill of one API replica shows up here as a
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
7
+ * is an answer from Uru: the call may not have arrived, or it arrived and its
8
+ * reply was lost. Each caller decides whether its request is safe to send
9
+ * again (a keyed action is, a Dataset SQL statement is not); this module owns
10
+ * what counts as lost and how long to wait.
11
+ */
12
+ import type { ResolvedDamperConfig } from "./dampers.js";
13
+ import type { RuntimeFetch } from "./runtime.js";
14
+ /** A status the edge gives when no replica answered. */
15
+ export declare const isLostResponse: (status: number, body: unknown) => boolean;
16
+ /** A fetch that failed before a response, and not because the caller stopped it. */
17
+ export declare const isLostRequest: (error: unknown, signal: AbortSignal | undefined) => boolean;
18
+ /** One response body, and whether the connection broke before all of it arrived. */
19
+ export interface RuntimeResponseBody {
20
+ /** The parsed JSON body, or null when the body is not JSON. */
21
+ readonly body: unknown;
22
+ /**
23
+ * The connection broke while the body was arriving: the replica died after
24
+ * it sent the headers. The answer never arrived, so a call that may be sent
25
+ * again treats it as lost.
26
+ */
27
+ readonly cut: boolean;
28
+ }
29
+ /** Read one JSON body. The request signal (caller signal or deadline) ends the read. */
30
+ export declare const readRuntimeResponseBody: (response: Response, signal: AbortSignal | undefined) => Promise<RuntimeResponseBody>;
31
+ /** The jittered wait before resend `resend` (0-based): base to twice base. */
32
+ export declare const resendDelayMs: (resend: number, random: () => number) => number;
33
+ /** Whether one more resend is allowed after `resend` earlier ones. */
34
+ export declare const canResend: (config: ResolvedDamperConfig, resend: number) => boolean;
35
+ /** Wait before a resend. The request signal (caller signal or deadline) ends the wait. */
36
+ export declare const waitBeforeResend: (config: ResolvedDamperConfig, delayMs: number, signal: AbortSignal | undefined) => Promise<void>;
37
+ export interface PostWithResendsArguments {
38
+ readonly body: string;
39
+ readonly config: ResolvedDamperConfig;
40
+ readonly headers: Headers;
41
+ /** Whether a lost response may be sent again with the same body. */
42
+ readonly resendLost: boolean;
43
+ readonly runtimeFetch: RuntimeFetch;
44
+ /** The limit for one send. A send that reaches it counts as lost. */
45
+ readonly sendTimeoutMs: number;
46
+ readonly url: string;
47
+ }
48
+ export interface PostWithResendsResult {
49
+ /** The parsed JSON body, or null when the body is not JSON. */
50
+ readonly body: unknown;
51
+ readonly response: Response;
52
+ }
53
+ /**
54
+ * POST one prepared body. When the platform gave no answer and the caller
55
+ * allows it, send the same bytes again after the jittered wait.
56
+ */
57
+ export declare const postWithResends: (args: PostWithResendsArguments, resent?: number) => Promise<PostWithResendsResult>;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Resends for a response the platform never gave.
3
+ *
4
+ * A deploy, a crash or a memory kill of one API replica shows up here as a
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
7
+ * is an answer from Uru: the call may not have arrived, or it arrived and its
8
+ * reply was lost. Each caller decides whether its request is safe to send
9
+ * again (a keyed action is, a Dataset SQL statement is not); this module owns
10
+ * what counts as lost and how long to wait.
11
+ */
12
+ import { abortReason, awaitWithAbort } from "./transport-deadline.js";
13
+ /** Waits before jitter. With jitter the whole schedule lasts about a minute. */
14
+ const RESEND_BASE_DELAYS_MS = [
15
+ 500, 1000, 2000, 4000, 8000, 8000, 8000,
16
+ ];
17
+ /**
18
+ * Error codes that Bun and Node attach to a failed connection. Browsers,
19
+ * Workers and Node's fetch raise a `TypeError` instead.
20
+ */
21
+ const NETWORK_ERROR_CODES = new Set([
22
+ "ConnectionClosed",
23
+ "ConnectionRefused",
24
+ "ECONNREFUSED",
25
+ "ECONNRESET",
26
+ "EPIPE",
27
+ "ETIMEDOUT",
28
+ "UND_ERR_CLOSED",
29
+ "UND_ERR_SOCKET",
30
+ ]);
31
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
32
+ const safeRecordValue = (record, field) => {
33
+ try {
34
+ return record[field];
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ };
40
+ const isCode = (value) => typeof value === "string" && value.trim() !== "";
41
+ /**
42
+ * A JSON error body with a code: the backend's `{ error: { code } }` envelope
43
+ * or the Gem dispatcher's `{ error: "gem_unavailable" }`. Uru wrote it, so the
44
+ * answer stands. An edge with no replica answers with text.
45
+ */
46
+ const hasOwnedErrorCode = (body) => {
47
+ if (!isRecord(body))
48
+ return false;
49
+ const error = safeRecordValue(body, "error");
50
+ if (isCode(error) || isCode(safeRecordValue(body, "code")))
51
+ return true;
52
+ return isRecord(error) && isCode(safeRecordValue(error, "code"));
53
+ };
54
+ /** A status the edge gives when no replica answered. */
55
+ export const isLostResponse = (status, body) => status === 502 ||
56
+ status === 504 ||
57
+ (status === 503 && !hasOwnedErrorCode(body));
58
+ /** A fetch that failed before a response, and not because the caller stopped it. */
59
+ export const isLostRequest = (error, signal) => {
60
+ if (signal?.aborted === true)
61
+ return false;
62
+ if (error instanceof TypeError)
63
+ return true;
64
+ if (!(error instanceof Error) || !("code" in error))
65
+ return false;
66
+ const { code } = error;
67
+ return typeof code === "string" && NETWORK_ERROR_CODES.has(code);
68
+ };
69
+ /** The request signal when it has stopped the call, else null. */
70
+ const stoppedSignal = (signal) => signal !== undefined && signal.aborted ? signal : null;
71
+ /** Read one JSON body. The request signal (caller signal or deadline) ends the read. */
72
+ export const readRuntimeResponseBody = async (response, signal) => {
73
+ const stopReading = (stopped) => {
74
+ void response.body?.cancel().catch(() => undefined);
75
+ throw abortReason(stopped);
76
+ };
77
+ const stoppedBefore = stoppedSignal(signal);
78
+ if (stoppedBefore !== null)
79
+ return stopReading(stoppedBefore);
80
+ let text;
81
+ try {
82
+ text = await awaitWithAbort(response.text(), signal);
83
+ }
84
+ catch (error) {
85
+ const stoppedDuring = stoppedSignal(signal);
86
+ if (stoppedDuring !== null)
87
+ return stopReading(stoppedDuring);
88
+ return { body: null, cut: isLostRequest(error, signal) };
89
+ }
90
+ try {
91
+ const body = JSON.parse(text);
92
+ return { body, cut: false };
93
+ }
94
+ catch {
95
+ return { body: null, cut: false };
96
+ }
97
+ };
98
+ /** The jittered wait before resend `resend` (0-based): base to twice base. */
99
+ export const resendDelayMs = (resend, random) => {
100
+ const base = RESEND_BASE_DELAYS_MS[Math.min(resend, RESEND_BASE_DELAYS_MS.length - 1)] ??
101
+ 500;
102
+ const sample = random();
103
+ const jitter = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1) : 0;
104
+ return Math.round(base * (1 + jitter));
105
+ };
106
+ /** Whether one more resend is allowed after `resend` earlier ones. */
107
+ export const canResend = (config, resend) => resend < config.maxTransportRetries;
108
+ /** Wait before a resend. The request signal (caller signal or deadline) ends the wait. */
109
+ export const waitBeforeResend = async (config, delayMs, signal) => {
110
+ signal?.throwIfAborted();
111
+ await awaitWithAbort(signal === undefined
112
+ ? config.sleep(delayMs)
113
+ : config.sleep(delayMs, signal), signal);
114
+ };
115
+ const reachedSendLimit = (error, sendSignal) => sendSignal.aborted && error === sendSignal.reason;
116
+ /**
117
+ * POST one prepared body. When the platform gave no answer and the caller
118
+ * allows it, send the same bytes again after the jittered wait.
119
+ */
120
+ export const postWithResends = async (args, resent = 0) => {
121
+ // Read the fetch out of `args` so it is not called with `args` as `this`.
122
+ const { runtimeFetch } = args;
123
+ const sendSignal = AbortSignal.timeout(args.sendTimeoutMs);
124
+ let outcome = null;
125
+ let cut = false;
126
+ let lostError = null;
127
+ try {
128
+ const response = await runtimeFetch(args.url, {
129
+ body: args.body,
130
+ headers: args.headers,
131
+ method: "POST",
132
+ signal: sendSignal,
133
+ });
134
+ const read = await readRuntimeResponseBody(response, sendSignal);
135
+ outcome = { body: read.body, response };
136
+ cut = read.cut;
137
+ }
138
+ catch (error) {
139
+ if (!isLostRequest(error, undefined) && !reachedSendLimit(error, sendSignal)) {
140
+ throw error;
141
+ }
142
+ lostError = error;
143
+ }
144
+ const lost = outcome === null ||
145
+ cut ||
146
+ isLostResponse(outcome.response.status, outcome.body);
147
+ if (lost && args.resendLost && canResend(args.config, resent)) {
148
+ await waitBeforeResend(args.config, resendDelayMs(resent, args.config.random), undefined);
149
+ return await postWithResends(args, resent + 1);
150
+ }
151
+ if (outcome === null)
152
+ throw lostError;
153
+ return outcome;
154
+ };
@@ -16,12 +16,15 @@
16
16
  * module that imports nothing back.
17
17
  */
18
18
  import type { ForceRefreshThrottle, ResolvedDamperConfig } from "./dampers.js";
19
+ import type { CallKeys } from "./job-run.js";
19
20
  import type { RuntimeJsonObject } from "./transport-json.js";
20
21
  import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeCapabilityType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruResultDecoder } from "./types.js";
21
22
  /** Per-client damper state: the resolved config plus the forceRefresh throttle. */
22
23
  export interface DamperRuntime {
23
24
  readonly config: ResolvedDamperConfig;
24
25
  readonly throttle: ForceRefreshThrottle;
26
+ /** Where a call's default key comes from: random, or owned by a job run. */
27
+ readonly keys: CallKeys;
25
28
  }
26
29
  interface AppRuntimeInvocationHttpResponse {
27
30
  ok: boolean;
@@ -56,6 +59,6 @@ export declare const appRuntimeInvocationResponseFromHttp: (value: unknown, deco
56
59
  /** Map the owned camelCase job-status envelope without copying unknown fields. */
57
60
  export declare const appRuntimeExecutionStatusFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeExecutionHttpResponse;
58
61
  export declare const invokeAppRuntime: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType, name: string, input?: unknown, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
59
- export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeExecutionStatus>;
60
- export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
62
+ export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeExecutionStatus>;
63
+ export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeInvocationResponse>;
61
64
  export {};