@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 +171 -12
- package/dist/background-jobs.d.ts +7 -0
- package/dist/background-jobs.js +576 -0
- package/dist/dampers.d.ts +17 -1
- package/dist/dampers.js +3 -0
- package/dist/dataset-boundary.js +38 -1
- package/dist/dataset-row.d.ts +9 -0
- package/dist/dataset-row.js +11 -0
- package/dist/datasets.d.ts +2 -1
- package/dist/datasets.js +81 -28
- package/dist/errors.js +1 -0
- package/dist/files.js +4 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +20 -7
- package/dist/invocations.d.ts +1 -1
- package/dist/invocations.js +2 -2
- package/dist/job-run.d.ts +90 -0
- package/dist/job-run.js +229 -0
- package/dist/jobs.d.ts +3 -3
- package/dist/jobs.js +37 -11
- package/dist/transport-deadline.d.ts +0 -1
- package/dist/transport-deadline.js +0 -27
- package/dist/transport-invocation.d.ts +21 -4
- package/dist/transport-invocation.js +110 -29
- package/dist/transport-retry.d.ts +57 -0
- package/dist/transport-retry.js +154 -0
- package/dist/transport.d.ts +4 -1
- package/dist/transport.js +53 -32
- package/dist/types.d.ts +183 -3
- package/package.json +3 -3
package/dist/jobs.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment } from './types.js';
|
|
1
|
+
import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment, UruServerContext } from './types.js';
|
|
3
2
|
export declare const createJobProgress: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (progress: UruJobProgress) => Promise<void>;
|
|
4
|
-
export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) =>
|
|
3
|
+
export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => UruServerContext['jobs']['checkpoint'];
|
|
4
|
+
export declare const createJobStep: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => UruServerContext['jobs']['step'];
|
package/dist/jobs.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { resolveDamperConfig } from './dampers.js';
|
|
1
2
|
import { UruAppRuntimeError } from './errors.js';
|
|
3
|
+
import { jobAttemptFor, runJobStep, saveJobCheckpoint, setJobCheckpoint } from './job-run.js';
|
|
2
4
|
import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash } from './runtime.js';
|
|
5
|
+
import { postWithResends } from './transport-retry.js';
|
|
3
6
|
import { isRuntimeJsonObject } from './transport-json.js';
|
|
4
|
-
const postJobUpdate = async (options, env, operation,
|
|
7
|
+
const postJobUpdate = async (options, env, operation, body) => {
|
|
5
8
|
const runId = Object.hasOwn(env, 'URU_JOB_RUN_ID') ? env['URU_JOB_RUN_ID']?.trim() : undefined;
|
|
6
9
|
const attemptId = Object.hasOwn(env, 'URU_JOB_ATTEMPT_ID') ? env['URU_JOB_ATTEMPT_ID']?.trim() : undefined;
|
|
7
10
|
if (!runId || !attemptId) {
|
|
@@ -10,26 +13,49 @@ const postJobUpdate = async (options, env, operation, payload) => {
|
|
|
10
13
|
const headers = new Headers(await resolveHeaders(options.headers));
|
|
11
14
|
headers.set('content-type', 'application/json');
|
|
12
15
|
const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
|
|
13
|
-
|
|
14
|
-
|
|
16
|
+
// Progress and a checkpoint replace the attempt's saved value, so the same
|
|
17
|
+
// body is always safe to send again after a restarting server. Each one also
|
|
18
|
+
// keeps the attempt's lease: it proves the job is alive.
|
|
19
|
+
const { response } = await postWithResends({
|
|
20
|
+
body,
|
|
21
|
+
config: resolveDamperConfig(options.dampers),
|
|
22
|
+
headers,
|
|
23
|
+
resendLost: true,
|
|
24
|
+
runtimeFetch: resolveRuntimeFetch(options),
|
|
25
|
+
sendTimeoutMs: 30_000,
|
|
26
|
+
url,
|
|
15
27
|
});
|
|
16
28
|
if (!response.ok) {
|
|
17
|
-
await response.body?.cancel();
|
|
18
29
|
throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
|
|
19
30
|
}
|
|
20
|
-
await response.body?.cancel();
|
|
21
31
|
};
|
|
32
|
+
const noJobAttempt = () => new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
|
|
22
33
|
export const createJobProgress = (options, env) => async (progress) => {
|
|
23
34
|
if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
|
|
24
35
|
(progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
|
|
25
36
|
(progress.message !== undefined && typeof progress.message !== 'string')) {
|
|
26
37
|
throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
|
|
27
38
|
}
|
|
28
|
-
await postJobUpdate(options, env, 'progress', progress);
|
|
39
|
+
await postJobUpdate(options, env, 'progress', JSON.stringify(progress));
|
|
29
40
|
};
|
|
30
|
-
export const createJobCheckpoint = (options, env) =>
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
41
|
+
export const createJobCheckpoint = (options, env) => {
|
|
42
|
+
const attempt = jobAttemptFor(env);
|
|
43
|
+
return async (value) => {
|
|
44
|
+
if (!isRuntimeJsonObject(value)) {
|
|
45
|
+
throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
|
|
46
|
+
}
|
|
47
|
+
if (attempt === null)
|
|
48
|
+
throw noJobAttempt();
|
|
49
|
+
setJobCheckpoint(attempt, value);
|
|
50
|
+
await saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body));
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
export const createJobStep = (options, env) => {
|
|
54
|
+
const attempt = jobAttemptFor(env);
|
|
55
|
+
return async (name, run) => {
|
|
56
|
+
if (attempt === null) {
|
|
57
|
+
throw new UruAppRuntimeError('Job steps require an active job attempt.', { status: 0, body: null });
|
|
58
|
+
}
|
|
59
|
+
return await runJobStep(attempt, name, run, () => saveJobCheckpoint(attempt, body => postJobUpdate(options, env, 'checkpoint', body)));
|
|
60
|
+
};
|
|
35
61
|
};
|
|
@@ -5,4 +5,3 @@ export declare const withRuntimeRequestSignal: <T>(options: UruAppRuntimeInvocat
|
|
|
5
5
|
export declare const abortReason: (signal: AbortSignal) => unknown;
|
|
6
6
|
/** Race a fetch, body read, or retry wait against the same request signal. */
|
|
7
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>;
|
|
@@ -22,7 +22,6 @@ export const validateRuntimeInvocationOptions = (options) => {
|
|
|
22
22
|
assertRuntimeTimeout(options.timeoutMs);
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
const runtimeSignalIsAborted = (signal) => signal?.aborted === true;
|
|
26
25
|
/**
|
|
27
26
|
* Make one deadline for the whole network operation. The regular timer keeps
|
|
28
27
|
* the deadline live even when the caller has no other active event-loop work.
|
|
@@ -79,29 +78,3 @@ export const awaitWithAbort = async (promise, signal) => {
|
|
|
79
78
|
});
|
|
80
79
|
});
|
|
81
80
|
};
|
|
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
|
-
};
|
|
@@ -8,8 +8,11 @@ export interface InvocationFetchArguments {
|
|
|
8
8
|
deploymentId: string;
|
|
9
9
|
emit: (event: UruAppRuntimeEvent) => void;
|
|
10
10
|
headers: Headers;
|
|
11
|
-
|
|
11
|
+
/** The body for one send; `resend` counts the sends before it. */
|
|
12
|
+
requestBody: (resend: number) => string;
|
|
12
13
|
requestId: string;
|
|
14
|
+
/** Whether a lost response may be sent again. */
|
|
15
|
+
resendLost: boolean;
|
|
13
16
|
runtimeFetch: RuntimeFetch;
|
|
14
17
|
signal?: AbortSignal;
|
|
15
18
|
url: string;
|
|
@@ -18,7 +21,12 @@ export interface RuntimeFetchResult {
|
|
|
18
21
|
body: unknown;
|
|
19
22
|
response: Response;
|
|
20
23
|
}
|
|
21
|
-
|
|
24
|
+
interface SendCounts {
|
|
25
|
+
readonly rateLimited: number;
|
|
26
|
+
readonly resent: number;
|
|
27
|
+
}
|
|
28
|
+
export declare const fetchInvocation: (args: InvocationFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
|
|
29
|
+
/** One job execution call: a status read or a cancel. */
|
|
22
30
|
export interface JobStatusFetchArguments {
|
|
23
31
|
damper: DamperRuntime;
|
|
24
32
|
deploymentId: string;
|
|
@@ -30,5 +38,14 @@ export interface JobStatusFetchArguments {
|
|
|
30
38
|
signal?: AbortSignal;
|
|
31
39
|
url: string;
|
|
32
40
|
}
|
|
33
|
-
/**
|
|
34
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Fetch one accepted execution's status with bounded, same-identity retries.
|
|
43
|
+
* A status read changes nothing, so a lost response is always read again.
|
|
44
|
+
*/
|
|
45
|
+
export declare const fetchJobStatus: (args: JobStatusFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
|
|
46
|
+
/**
|
|
47
|
+
* Ask for one execution to stop. A cancel names its execution and asks for
|
|
48
|
+
* the same end state every time, so a lost response is sent again.
|
|
49
|
+
*/
|
|
50
|
+
export declare const fetchJobCancel: (args: JobStatusFetchArguments, resent?: number) => Promise<RuntimeFetchResult>;
|
|
51
|
+
export {};
|
|
@@ -1,29 +1,75 @@
|
|
|
1
1
|
import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, } from "./dampers.js";
|
|
2
|
-
import { awaitWithAbort
|
|
3
|
-
|
|
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.
|
|
9
|
-
|
|
10
|
-
args.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
}
|
|
18
|
-
|
|
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
|
-
|
|
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,
|
|
95
|
+
return await fetchInvocation(args, {
|
|
96
|
+
...counts,
|
|
97
|
+
rateLimited: counts.rateLimited + 1,
|
|
98
|
+
});
|
|
50
99
|
};
|
|
51
|
-
|
|
52
|
-
|
|
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
|
|
55
|
-
|
|
56
|
-
args.signal
|
|
57
|
-
return
|
|
58
|
-
|
|
59
|
-
|
|
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
|
-
}
|
|
63
|
-
|
|
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
|
-
|
|
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,23 @@ 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,
|
|
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;
|
|
93
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
|
+
};
|
package/dist/transport.d.ts
CHANGED
|
@@ -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;
|
|
@@ -57,5 +60,5 @@ export declare const appRuntimeInvocationResponseFromHttp: (value: unknown, deco
|
|
|
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
62
|
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
|
|
63
|
+
export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeInvocationResponse>;
|
|
61
64
|
export {};
|