@uru-intelligence/app 2.1.6 → 2.2.4

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.
Files changed (43) hide show
  1. package/README.md +463 -14
  2. package/dist/background-jobs.d.ts +11 -0
  3. package/dist/background-jobs.js +571 -0
  4. package/dist/dampers.d.ts +24 -1
  5. package/dist/dampers.js +3 -0
  6. package/dist/dataset-boundary.js +38 -1
  7. package/dist/dataset-row.d.ts +9 -0
  8. package/dist/dataset-row.js +11 -0
  9. package/dist/datasets.d.ts +2 -1
  10. package/dist/datasets.js +82 -28
  11. package/dist/errors.js +5 -4
  12. package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
  13. package/dist/examples/customer-workflows/approved-external-write.js +162 -0
  14. package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
  15. package/dist/examples/customer-workflows/file-processor.js +53 -0
  16. package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
  17. package/dist/examples/customer-workflows/job-coordinator.js +1 -0
  18. package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
  19. package/dist/examples/customer-workflows/review-only-draft.js +48 -0
  20. package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
  21. package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
  22. package/dist/files.js +4 -1
  23. package/dist/index.d.ts +6 -3
  24. package/dist/index.js +20 -7
  25. package/dist/invocations.d.ts +11 -1
  26. package/dist/invocations.js +72 -4
  27. package/dist/job-run.d.ts +90 -0
  28. package/dist/job-run.js +229 -0
  29. package/dist/jobs.d.ts +3 -3
  30. package/dist/jobs.js +39 -11
  31. package/dist/runtime.d.ts +8 -4
  32. package/dist/runtime.js +27 -7
  33. package/dist/transport-deadline.d.ts +0 -1
  34. package/dist/transport-deadline.js +0 -27
  35. package/dist/transport-invocation.d.ts +23 -4
  36. package/dist/transport-invocation.js +114 -29
  37. package/dist/transport-retry.d.ts +68 -0
  38. package/dist/transport-retry.js +245 -0
  39. package/dist/transport.d.ts +5 -20
  40. package/dist/transport.js +54 -33
  41. package/dist/types.d.ts +203 -4
  42. package/dist/uploads.js +158 -19
  43. package/package.json +34 -9
@@ -1,29 +1,75 @@
1
1
  import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, } from "./dampers.js";
2
- import { awaitWithAbort, readRuntimeResponseBody, } from "./transport-deadline.js";
3
- export const fetchInvocation = async (args, attempt = 0) => {
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);
61
+ }
62
+ if (outcome.kind === "lost")
63
+ throw outcome.error;
64
+ const { body, response } = outcome.result;
19
65
  const shouldRetry = response.status === 429 &&
20
66
  parseRetryable(body) !== false &&
21
- attempt < args.damper.config.maxRateLimitRetries;
67
+ counts.rateLimited < args.damper.config.maxRateLimitRetries;
22
68
  if (!shouldRetry) {
23
69
  return { body, response };
24
70
  }
25
71
  const delayMs = computeRateLimitRetryDelayMs({
26
- attempt,
72
+ attempt: counts.rateLimited,
27
73
  baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
28
74
  maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
29
75
  retryAfterSeconds: parseRetryAfterSeconds({
@@ -46,24 +92,41 @@ export const fetchInvocation = async (args, attempt = 0) => {
46
92
  ? args.damper.config.sleep(delayMs)
47
93
  : args.damper.config.sleep(delayMs, args.signal);
48
94
  await awaitWithAbort(sleepPromise, args.signal);
49
- return await fetchInvocation(args, attempt + 1);
95
+ return await fetchInvocation(args, {
96
+ ...counts,
97
+ rateLimited: counts.rateLimited + 1,
98
+ });
50
99
  };
51
- /** Fetch one accepted execution's status with bounded, same-identity retries. */
52
- export const fetchJobStatus = async (args, attempt = 0) => {
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) => {
53
115
  const { runtimeFetch } = args;
54
- args.signal?.throwIfAborted();
55
- const response = await awaitWithAbort(Promise.resolve().then(() => {
56
- args.signal?.throwIfAborted();
57
- return runtimeFetch(args.url, {
58
- headers: args.headers,
59
- method: "GET",
60
- ...(args.signal === undefined ? {} : { signal: args.signal }),
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,
61
122
  });
62
- }), args.signal);
63
- const body = await readRuntimeResponseBody(response, args.signal);
123
+ }
124
+ if (outcome.kind === "lost")
125
+ throw outcome.error;
126
+ const { body, response } = outcome.result;
64
127
  const shouldRetry = response.status === 429 &&
65
128
  parseRetryable(body) !== false &&
66
- attempt < args.damper.config.maxRateLimitRetries;
129
+ counts.rateLimited < args.damper.config.maxRateLimitRetries;
67
130
  if (!shouldRetry) {
68
131
  return { body, response };
69
132
  }
@@ -72,7 +135,7 @@ export const fetchJobStatus = async (args, attempt = 0) => {
72
135
  header: response.headers.get("retry-after"),
73
136
  });
74
137
  const delayMs = computeRateLimitRetryDelayMs({
75
- attempt,
138
+ attempt: counts.rateLimited,
76
139
  baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
77
140
  maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
78
141
  retryAfterSeconds,
@@ -89,5 +152,27 @@ export const fetchJobStatus = async (args, attempt = 0) => {
89
152
  type: "status",
90
153
  });
91
154
  await awaitWithAbort(args.damper.config.sleep(delayMs, args.signal), args.signal);
92
- return await fetchJobStatus(args, attempt + 1);
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. The route
163
+ * takes no body, but the job gateway accepts only a JSON POST, so the cancel
164
+ * sends an empty JSON object.
165
+ */
166
+ export const fetchJobCancel = async (args, resent = 0) => {
167
+ const { runtimeFetch } = args;
168
+ const headers = new Headers(args.headers);
169
+ headers.set("content-type", "application/json");
170
+ const outcome = await sendOnce(runtimeFetch, args.url, { body: "{}", headers, method: "POST" }, args.signal);
171
+ if (isLost(outcome) && canResend(args.damper.config, resent)) {
172
+ await reconnect(args.damper, resent, args.signal, retryAfterSeconds => args.emit(jobReconnectingEvent(args, retryAfterSeconds)));
173
+ return await fetchJobCancel(args, resent + 1);
174
+ }
175
+ if (outcome.kind === "lost")
176
+ throw outcome.error;
177
+ return outcome.result;
93
178
  };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Resends for a response the platform never gave, and for a temporary answer.
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. 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.
13
+ */
14
+ import type { ResolvedDamperConfig } from "./dampers.js";
15
+ import type { RuntimeFetch } from "./runtime.js";
16
+ /** A status the edge gives when no replica answered. */
17
+ export declare const isLostResponse: (status: number, body: unknown) => boolean;
18
+ /** A fetch that failed before a response, and not because the caller stopped it. */
19
+ export declare const isLostRequest: (error: unknown, signal: AbortSignal | undefined) => boolean;
20
+ /** One response body, and whether the connection broke before all of it arrived. */
21
+ export interface RuntimeResponseBody {
22
+ /** The parsed JSON body, or null when the body is not JSON. */
23
+ readonly body: unknown;
24
+ /**
25
+ * The connection broke while the body was arriving: the replica died after
26
+ * it sent the headers. The answer never arrived, so a call that may be sent
27
+ * again treats it as lost.
28
+ */
29
+ readonly cut: boolean;
30
+ }
31
+ /** Read one JSON body. The request signal (caller signal or deadline) ends the read. */
32
+ export declare const readRuntimeResponseBody: (response: Response, signal: AbortSignal | undefined) => Promise<RuntimeResponseBody>;
33
+ /** The jittered wait before resend `resend` (0-based): base to twice base. */
34
+ export declare const resendDelayMs: (resend: number, random: () => number) => number;
35
+ /** Whether one more resend is allowed after `resend` earlier ones. */
36
+ export declare const canResend: (config: ResolvedDamperConfig, resend: number) => boolean;
37
+ /** Wait before a resend. The request signal (caller signal or deadline) ends the wait. */
38
+ export declare const waitBeforeResend: (config: ResolvedDamperConfig, delayMs: number, signal: AbortSignal | undefined) => Promise<void>;
39
+ export interface PostWithResendsArguments {
40
+ readonly body: string;
41
+ readonly config: ResolvedDamperConfig;
42
+ readonly headers: Headers;
43
+ /**
44
+ * Whether the same body is safe to send again: the server answers a keyed
45
+ * 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.
49
+ */
50
+ readonly repeatable: boolean;
51
+ readonly runtimeFetch: RuntimeFetch;
52
+ /** The limit for one send. A send that reaches it counts as lost. */
53
+ readonly sendTimeoutMs: number;
54
+ readonly url: string;
55
+ }
56
+ export interface PostWithResendsResult {
57
+ /** The parsed JSON body, or null when the body is not JSON. */
58
+ readonly body: unknown;
59
+ readonly response: Response;
60
+ }
61
+ /**
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.
67
+ */
68
+ export declare const postWithResends: (args: PostWithResendsArguments, resent?: number, waitedMs?: number) => Promise<PostWithResendsResult>;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Resends for a response the platform never gave, and for a temporary answer.
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. 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.
13
+ */
14
+ import { parseRetryable, parseRetryAfterSeconds } from "./dampers.js";
15
+ import { abortReason, awaitWithAbort } from "./transport-deadline.js";
16
+ /** Waits before jitter. With jitter the whole schedule lasts about a minute. */
17
+ const RESEND_BASE_DELAYS_MS = [
18
+ 500, 1000, 2000, 4000, 8000, 8000, 8000,
19
+ ];
20
+ /**
21
+ * Error codes that Bun and Node attach to a failed connection. Browsers,
22
+ * Workers and Node's fetch raise a `TypeError` instead.
23
+ */
24
+ const NETWORK_ERROR_CODES = new Set([
25
+ "ConnectionClosed",
26
+ "ConnectionRefused",
27
+ "ECONNREFUSED",
28
+ "ECONNRESET",
29
+ "EPIPE",
30
+ "ETIMEDOUT",
31
+ "UND_ERR_CLOSED",
32
+ "UND_ERR_SOCKET",
33
+ ]);
34
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
35
+ const safeRecordValue = (record, field) => {
36
+ try {
37
+ return record[field];
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ };
43
+ const codeOf = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
44
+ /**
45
+ * The code of a JSON error body: the backend's `{ error: { code } }`
46
+ * envelope, the Gem dispatcher's `{ error: "gem_unavailable" }`, or
47
+ * `{ code }`. Uru wrote such a body, so the answer is Uru's. An edge with no
48
+ * replica answers with text.
49
+ */
50
+ const ownedErrorCode = (body) => {
51
+ if (!isRecord(body))
52
+ return null;
53
+ const error = safeRecordValue(body, "error");
54
+ return (codeOf(error) ??
55
+ codeOf(safeRecordValue(body, "code")) ??
56
+ (isRecord(error) ? codeOf(safeRecordValue(error, "code")) : null));
57
+ };
58
+ /** A status the edge gives when no replica answered. */
59
+ export const isLostResponse = (status, body) => status === 502 ||
60
+ status === 504 ||
61
+ (status === 503 && ownedErrorCode(body) === null);
62
+ /** The statuses Uru gives when it cannot serve a call now but can soon. */
63
+ const TEMPORARY_STATUSES = new Set([408, 429, 503]);
64
+ /**
65
+ * 503 codes for a missing setup, which a resend cannot fix. The provider
66
+ * gateway answers this one before any API replica sees the call.
67
+ */
68
+ const SETUP_FAILURE_CODES = new Set([
69
+ "provider_gateway_limiter_unavailable",
70
+ ]);
71
+ /**
72
+ * An answer from Uru that it cannot serve the call now but can soon: a 408,
73
+ * 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.
78
+ */
79
+ const isTemporaryAnswer = (status, body) => {
80
+ if (!TEMPORARY_STATUSES.has(status))
81
+ return false;
82
+ if (parseRetryable(body) === false)
83
+ return false;
84
+ const code = ownedErrorCode(body);
85
+ return code === null || !SETUP_FAILURE_CODES.has(code);
86
+ };
87
+ /**
88
+ * The request header that tells the provider gateway this client sends a
89
+ * temporary answer again itself, so the gateway passes it straight back
90
+ * instead of sending the call again too. Without it, one call could reach
91
+ * the API once for each SDK send times each gateway send.
92
+ */
93
+ const SDK_RESENDS_HEADER = "x-uru-sdk-resends";
94
+ /** A fetch that failed before a response, and not because the caller stopped it. */
95
+ export const isLostRequest = (error, signal) => {
96
+ if (signal?.aborted === true)
97
+ return false;
98
+ if (error instanceof TypeError)
99
+ return true;
100
+ if (!(error instanceof Error) || !("code" in error))
101
+ return false;
102
+ const { code } = error;
103
+ return typeof code === "string" && NETWORK_ERROR_CODES.has(code);
104
+ };
105
+ /** The request signal when it has stopped the call, else null. */
106
+ const stoppedSignal = (signal) => signal !== undefined && signal.aborted ? signal : null;
107
+ /** Read one JSON body. The request signal (caller signal or deadline) ends the read. */
108
+ export const readRuntimeResponseBody = async (response, signal) => {
109
+ const stopReading = (stopped) => {
110
+ void response.body?.cancel().catch(() => undefined);
111
+ throw abortReason(stopped);
112
+ };
113
+ const stoppedBefore = stoppedSignal(signal);
114
+ if (stoppedBefore !== null)
115
+ return stopReading(stoppedBefore);
116
+ let text;
117
+ try {
118
+ text = await awaitWithAbort(response.text(), signal);
119
+ }
120
+ catch (error) {
121
+ const stoppedDuring = stoppedSignal(signal);
122
+ if (stoppedDuring !== null)
123
+ return stopReading(stoppedDuring);
124
+ return { body: null, cut: isLostRequest(error, signal) };
125
+ }
126
+ try {
127
+ const body = JSON.parse(text);
128
+ return { body, cut: false };
129
+ }
130
+ catch {
131
+ return { body: null, cut: false };
132
+ }
133
+ };
134
+ /** The jittered wait before resend `resend` (0-based): base to twice base. */
135
+ export const resendDelayMs = (resend, random) => {
136
+ const base = RESEND_BASE_DELAYS_MS[Math.min(resend, RESEND_BASE_DELAYS_MS.length - 1)] ??
137
+ 500;
138
+ const sample = random();
139
+ const jitter = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1) : 0;
140
+ return Math.round(base * (1 + jitter));
141
+ };
142
+ /** Whether one more resend is allowed after `resend` earlier ones. */
143
+ export const canResend = (config, resend) => resend < config.maxTransportRetries;
144
+ /**
145
+ * The most that all the waits of one call may add up to: every allowed
146
+ * resend at its longest jittered wait, 63 seconds by default. A temporary
147
+ * answer's `Retry-After` can make one wait longer than the schedule gives it.
148
+ * A `Retry-After` longer than what is left of this budget ends the resends.
149
+ */
150
+ const resendBudgetMs = (config) => {
151
+ const resends = Math.ceil(config.maxTransportRetries);
152
+ const listed = RESEND_BASE_DELAYS_MS.slice(0, resends).reduce((sum, delay) => sum + delay, 0);
153
+ const lastBase = RESEND_BASE_DELAYS_MS.at(-1) ?? 0;
154
+ const beyond = Math.max(0, resends - RESEND_BASE_DELAYS_MS.length) * lastBase;
155
+ return 2 * (listed + beyond);
156
+ };
157
+ /** Wait before a resend. The request signal (caller signal or deadline) ends the wait. */
158
+ export const waitBeforeResend = async (config, delayMs, signal) => {
159
+ signal?.throwIfAborted();
160
+ await awaitWithAbort(signal === undefined
161
+ ? config.sleep(delayMs)
162
+ : config.sleep(delayMs, signal), signal);
163
+ };
164
+ const reachedSendLimit = (error, sendSignal) => sendSignal.aborted && error === sendSignal.reason;
165
+ /** The server's `Retry-After` (header or envelope) in milliseconds, else 0. */
166
+ const retryAfterMs = (outcome) => {
167
+ const seconds = parseRetryAfterSeconds({
168
+ body: outcome.body,
169
+ header: outcome.response.headers.get("retry-after"),
170
+ });
171
+ return seconds === null ? 0 : Math.ceil(seconds * 1000);
172
+ };
173
+ /**
174
+ * How long to wait before resend `resent`, or null when the call is not sent
175
+ * again: it is not repeatable, it used its resends, the wait budget is spent,
176
+ * or a temporary answer's `Retry-After` is longer than what is left of the
177
+ * budget. The server's limit wins, so the call never goes out before the
178
+ * time it names. Otherwise the wait is the jittered schedule, or the
179
+ * `Retry-After` when that is longer. A lost response (`temporary` null) keeps
180
+ * the schedule as before, because no API replica wrote its headers. A
181
+ * scheduled wait is cut to what is left of the budget.
182
+ */
183
+ const resendWaitMs = (args, resent, waitedMs, temporary) => {
184
+ if (!args.repeatable || !canResend(args.config, resent))
185
+ return null;
186
+ const left = resendBudgetMs(args.config) - waitedMs;
187
+ if (left <= 0)
188
+ return null;
189
+ const retryAfter = temporary === null ? 0 : retryAfterMs(temporary);
190
+ if (retryAfter > left)
191
+ return null;
192
+ return Math.min(Math.max(resendDelayMs(resent, args.config.random), retryAfter), left);
193
+ };
194
+ /**
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.
200
+ */
201
+ export const postWithResends = async (args, resent = 0, waitedMs = 0) => {
202
+ // Read the fetch out of `args` so it is not called with `args` as `this`.
203
+ const { runtimeFetch } = args;
204
+ const sendSignal = AbortSignal.timeout(args.sendTimeoutMs);
205
+ const headers = new Headers(args.headers);
206
+ if (args.repeatable)
207
+ headers.set(SDK_RESENDS_HEADER, "temporary");
208
+ let outcome = null;
209
+ let cut = false;
210
+ let lostError = null;
211
+ try {
212
+ const response = await runtimeFetch(args.url, {
213
+ body: args.body,
214
+ headers,
215
+ method: "POST",
216
+ signal: sendSignal,
217
+ });
218
+ const read = await readRuntimeResponseBody(response, sendSignal);
219
+ outcome = { body: read.body, response };
220
+ cut = read.cut;
221
+ }
222
+ catch (error) {
223
+ if (!isLostRequest(error, undefined) && !reachedSendLimit(error, sendSignal)) {
224
+ throw error;
225
+ }
226
+ lostError = error;
227
+ }
228
+ let temporary = null;
229
+ if (outcome !== null &&
230
+ !cut &&
231
+ !isLostResponse(outcome.response.status, outcome.body)) {
232
+ if (!isTemporaryAnswer(outcome.response.status, outcome.body)) {
233
+ return outcome;
234
+ }
235
+ temporary = outcome;
236
+ }
237
+ const delayMs = resendWaitMs(args, resent, waitedMs, temporary);
238
+ if (delayMs === null) {
239
+ if (outcome === null)
240
+ throw lostError;
241
+ return outcome;
242
+ }
243
+ await waitBeforeResend(args.config, delayMs, undefined);
244
+ return await postWithResends(args, resent + 1, waitedMs + delayMs);
245
+ };
@@ -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
- import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeCapabilityType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruResultDecoder } from "./types.js";
21
+ import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeCapabilityType, 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;
@@ -35,27 +38,9 @@ interface AppRuntimeInvocationHttpResponse {
35
38
  pending: boolean;
36
39
  diagnostics?: RuntimeJsonObject;
37
40
  }
38
- interface AppRuntimeExecutionHttpResponse {
39
- success?: boolean;
40
- pending?: boolean;
41
- result?: unknown;
42
- error?: string | null;
43
- state?: string;
44
- status?: string | null;
45
- executionId?: string | null;
46
- statusUrl?: string | null;
47
- retryAfterSeconds?: number | null;
48
- cacheStatus?: string | null;
49
- executor?: string | null;
50
- executorKind?: string | null;
51
- code?: string | null;
52
- diagnostics?: UruAppRuntimeExecutionDiagnostics;
53
- }
54
41
  /** Map the owned camelCase HTTP envelope without copying unknown fields. */
55
42
  export declare const appRuntimeInvocationResponseFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeInvocationHttpResponse;
56
- /** Map the owned camelCase job-status envelope without copying unknown fields. */
57
- export declare const appRuntimeExecutionStatusFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeExecutionHttpResponse;
58
43
  export declare const invokeAppRuntime: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType, name: string, input?: unknown, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
59
44
  export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeExecutionStatus>;
60
- export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
45
+ export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeInvocationResponse>;
61
46
  export {};