@colixsystems/actions-client 0.4.1 → 0.4.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 +4 -0
- package/dist/client.js +26 -59
- package/dist/client.test.js +30 -0
- package/dist/connectors.js +21 -10
- package/dist/connectors.test.js +12 -2
- package/dist/transport.js +95 -38
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,6 +10,10 @@ An Action is a server-side script the workspace owns. The app may run one only w
|
|
|
10
10
|
|
|
11
11
|
## Status
|
|
12
12
|
|
|
13
|
+
`v0.4.3` — internal: requests now go through the transport the clients share. A run, a status read and a connector call are still never retried and never cut short by a client timer, and a call that gets no answer still rejects `ACTION_FAILED` or `CONNECTOR_FAILED` with the underlying error as `cause`. No export, error class or request shape changed.
|
|
14
|
+
|
|
15
|
+
`v0.4.2` — internal: carries the newer transport the clients share, which gained options other clients use. This client's requests, retries and errors are unchanged.
|
|
16
|
+
|
|
13
17
|
`v0.4.1` — the factory option checks, URL joining and request headers now come from the transport the clients share. Two small changes: a `getRequestHeaders` value of `null` or `undefined` is no longer sent as the text "null", and a `multipartFetchImpl` option that is not a function is now refused with a `TypeError`, as in the other clients. No export or request shape changed.
|
|
14
18
|
|
|
15
19
|
`v0.4.0` — adds `enqueue`, which queues an Action run instead of waiting for it. `v0.3.0` added `createConnectorsClient`, which calls a workspace's REST connectors through the operations it listed for apps.
|
package/dist/client.js
CHANGED
|
@@ -9,9 +9,24 @@
|
|
|
9
9
|
// opt-in of the Action for apps. This client only carries the id and input.
|
|
10
10
|
|
|
11
11
|
import { ActionError, errorFromResponse } from "./errors.js";
|
|
12
|
-
import {
|
|
12
|
+
import { createRequester, defineTransportPolicy } from "./transport.js";
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// No HTTP answer (offline, or no session to send) keeps the generic code.
|
|
15
|
+
const requestFailed = (cause) =>
|
|
16
|
+
new ActionError(`Action request failed: ${cause?.message || cause}`, {
|
|
17
|
+
code: "ACTION_FAILED",
|
|
18
|
+
status: 0,
|
|
19
|
+
cause,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// A run can have side effects: never retried, and never cut short by a timer.
|
|
23
|
+
const policy = defineTransportPolicy({
|
|
24
|
+
BaseError: ActionError,
|
|
25
|
+
fromResponse: errorFromResponse,
|
|
26
|
+
retryVerbs: [],
|
|
27
|
+
timeoutMs: null,
|
|
28
|
+
networkError: requestFailed,
|
|
29
|
+
});
|
|
15
30
|
|
|
16
31
|
/**
|
|
17
32
|
* @param {object} opts
|
|
@@ -21,46 +36,9 @@ const NAMESPACE = "actions";
|
|
|
21
36
|
* @param {(ctx: { namespace: string, operation: string }) => object | Promise<object>} [opts.getRequestHeaders]
|
|
22
37
|
* Optional extra headers merged per request.
|
|
23
38
|
* @param {typeof fetch} [opts.fetchImpl] Defaults to globalThis.fetch.
|
|
24
|
-
* @param {string} factory the public factory's name, for its error messages.
|
|
25
|
-
* @param {string} namespace passed to getRequestHeaders.
|
|
26
|
-
* @param {(status: number, body: unknown) => Error} toError maps a refusal.
|
|
27
|
-
* @returns the `send(method, path, body, operation)` both clients use.
|
|
28
39
|
*/
|
|
29
|
-
export function createSender(opts, factory, namespace, toError) {
|
|
30
|
-
const { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl } = readClientOptions(
|
|
31
|
-
factory,
|
|
32
|
-
opts,
|
|
33
|
-
);
|
|
34
|
-
|
|
35
|
-
async function send(method, path, body, operation) {
|
|
36
|
-
const headers = await buildHeaders(
|
|
37
|
-
{ getToken, getTenantId, getRequestHeaders },
|
|
38
|
-
{ json: body !== undefined, namespace, operation },
|
|
39
|
-
);
|
|
40
|
-
|
|
41
|
-
const res = await fetchImpl(joinUrl(baseUrl, path), {
|
|
42
|
-
method,
|
|
43
|
-
headers,
|
|
44
|
-
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
45
|
-
});
|
|
46
|
-
const text = await res.text();
|
|
47
|
-
let parsed = null;
|
|
48
|
-
if (text.length > 0) {
|
|
49
|
-
try {
|
|
50
|
-
parsed = JSON.parse(text);
|
|
51
|
-
} catch {
|
|
52
|
-
parsed = { raw: text };
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
if (!res.ok) throw toError(res.status, parsed);
|
|
56
|
-
return parsed;
|
|
57
|
-
}
|
|
58
|
-
return send;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** Takes the providers createSender documents. */
|
|
62
40
|
export function createActionsClient(opts) {
|
|
63
|
-
const
|
|
41
|
+
const { request } = createRequester("createActionsClient", opts, policy, { namespace: "actions" });
|
|
64
42
|
|
|
65
43
|
function assertActionId(actionId, operation) {
|
|
66
44
|
// "." and ".." survive encodeURIComponent and fetch would resolve them.
|
|
@@ -77,20 +55,12 @@ export function createActionsClient(opts) {
|
|
|
77
55
|
async function post(actionId, operation, input) {
|
|
78
56
|
assertActionId(actionId, operation);
|
|
79
57
|
try {
|
|
80
|
-
return await
|
|
81
|
-
|
|
82
|
-
`/app-actions/${encodeURIComponent(actionId)}/${operation}`,
|
|
83
|
-
input == null ? undefined : { input },
|
|
58
|
+
return await request("POST", `/app-actions/${encodeURIComponent(actionId)}/${operation}`, {
|
|
59
|
+
body: input == null ? undefined : { input },
|
|
84
60
|
operation,
|
|
85
|
-
);
|
|
86
|
-
} catch (err) {
|
|
87
|
-
if (err instanceof ActionError) throw err;
|
|
88
|
-
// No HTTP answer (offline, or no session to send) keeps the generic code.
|
|
89
|
-
throw new ActionError(`Action request failed: ${err?.message || err}`, {
|
|
90
|
-
code: "ACTION_FAILED",
|
|
91
|
-
status: 0,
|
|
92
|
-
cause: err,
|
|
93
61
|
});
|
|
62
|
+
} catch (err) {
|
|
63
|
+
throw err instanceof ActionError ? err : requestFailed(err);
|
|
94
64
|
}
|
|
95
65
|
}
|
|
96
66
|
|
|
@@ -105,19 +75,16 @@ export function createActionsClient(opts) {
|
|
|
105
75
|
async status(actionId) {
|
|
106
76
|
assertActionId(actionId, "status");
|
|
107
77
|
try {
|
|
108
|
-
const body = await
|
|
78
|
+
const body = await request("GET", `/app-actions/${encodeURIComponent(actionId)}`, {
|
|
79
|
+
operation: "status",
|
|
80
|
+
});
|
|
109
81
|
const available = body?.available === true;
|
|
110
82
|
return { available, reason: available ? null : (body?.reason ?? "ACTION_FAILED") };
|
|
111
83
|
} catch (err) {
|
|
112
84
|
if (err instanceof ActionError && [401, 403, 404].includes(err.status)) {
|
|
113
85
|
return { available: false, reason: err.code };
|
|
114
86
|
}
|
|
115
|
-
|
|
116
|
-
throw new ActionError(`Action request failed: ${err?.message || err}`, {
|
|
117
|
-
code: "ACTION_FAILED",
|
|
118
|
-
status: 0,
|
|
119
|
-
cause: err,
|
|
120
|
-
});
|
|
87
|
+
throw err instanceof ActionError ? err : requestFailed(err);
|
|
121
88
|
}
|
|
122
89
|
},
|
|
123
90
|
|
package/dist/client.test.js
CHANGED
|
@@ -191,6 +191,36 @@ test("a failed run is never retried", async () => {
|
|
|
191
191
|
assert.equal(calls.length, 1);
|
|
192
192
|
});
|
|
193
193
|
|
|
194
|
+
test("a failed status read is never retried, and a body that breaks off is ACTION_FAILED", async () => {
|
|
195
|
+
const { fetchImpl, calls } = makeFetch({ status: 503 });
|
|
196
|
+
await assert.rejects(makeClient(fetchImpl).status("act-1"), { status: 503 });
|
|
197
|
+
assert.equal(calls.length, 1);
|
|
198
|
+
|
|
199
|
+
const broken = new TypeError("body stream broke");
|
|
200
|
+
const brokenBody = async () => ({ ok: true, status: 200, text: async () => Promise.reject(broken) });
|
|
201
|
+
await assert.rejects(makeClient(brokenBody).run("act-1"), (err) => {
|
|
202
|
+
assert.ok(err instanceof ActionError);
|
|
203
|
+
assert.equal(err.code, "ACTION_FAILED");
|
|
204
|
+
assert.equal(err.cause, broken);
|
|
205
|
+
return true;
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("a long run is not cut short by a client timer", async (t) => {
|
|
210
|
+
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
211
|
+
const fetchImpl = (url, init) =>
|
|
212
|
+
new Promise((resolve, reject) => {
|
|
213
|
+
init.signal?.addEventListener("abort", () => reject(new Error("aborted")));
|
|
214
|
+
setTimeout(() => resolve({ ok: true, status: 200, text: async () => '{"ok":true,"result":1}' }), 120_000);
|
|
215
|
+
});
|
|
216
|
+
const pending = makeClient(fetchImpl).run("act-1");
|
|
217
|
+
for (let i = 0; i < 13; i++) {
|
|
218
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
219
|
+
t.mock.timers.tick(10_000);
|
|
220
|
+
}
|
|
221
|
+
assert.deepEqual(await pending, { ok: true, result: 1 });
|
|
222
|
+
});
|
|
223
|
+
|
|
194
224
|
test("the factory validates its providers", () => {
|
|
195
225
|
assert.throws(() => createActionsClient(), TypeError);
|
|
196
226
|
assert.throws(
|
package/dist/connectors.js
CHANGED
|
@@ -7,11 +7,25 @@
|
|
|
7
7
|
// connector's credential is added on the server and never reaches the app.
|
|
8
8
|
|
|
9
9
|
import { ConnectorError, connectorErrorFromResponse } from "./errors.js";
|
|
10
|
-
import {
|
|
10
|
+
import { createRequester, defineTransportPolicy } from "./transport.js";
|
|
11
|
+
|
|
12
|
+
const requestFailed = (cause) =>
|
|
13
|
+
new ConnectorError(`Connector request failed: ${cause?.message || cause}`, { cause });
|
|
14
|
+
|
|
15
|
+
// An operation can change data upstream: never retried, and no timer.
|
|
16
|
+
const policy = defineTransportPolicy({
|
|
17
|
+
BaseError: ConnectorError,
|
|
18
|
+
fromResponse: connectorErrorFromResponse,
|
|
19
|
+
retryVerbs: [],
|
|
20
|
+
timeoutMs: null,
|
|
21
|
+
networkError: requestFailed,
|
|
22
|
+
});
|
|
11
23
|
|
|
12
24
|
/** Takes the same providers as createActionsClient. */
|
|
13
25
|
export function createConnectorsClient(opts) {
|
|
14
|
-
const
|
|
26
|
+
const { request } = createRequester("createConnectorsClient", opts, policy, {
|
|
27
|
+
namespace: "connectors",
|
|
28
|
+
});
|
|
15
29
|
|
|
16
30
|
return {
|
|
17
31
|
/**
|
|
@@ -30,15 +44,12 @@ export function createConnectorsClient(opts) {
|
|
|
30
44
|
}
|
|
31
45
|
let answer;
|
|
32
46
|
try {
|
|
33
|
-
answer = await
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"call",
|
|
38
|
-
);
|
|
47
|
+
answer = await request("POST", `/app-connectors/${encodeURIComponent(connectorId)}/call`, {
|
|
48
|
+
body: { operation, params: params ?? {}, query: query ?? {}, body: body ?? null },
|
|
49
|
+
operation: "call",
|
|
50
|
+
});
|
|
39
51
|
} catch (err) {
|
|
40
|
-
|
|
41
|
-
throw new ConnectorError(`Connector request failed: ${err?.message || err}`, { cause: err });
|
|
52
|
+
throw err instanceof ConnectorError ? err : requestFailed(err);
|
|
42
53
|
}
|
|
43
54
|
const src = answer && typeof answer === "object" ? answer : {};
|
|
44
55
|
return {
|
package/dist/connectors.test.js
CHANGED
|
@@ -50,10 +50,20 @@ for (const [status, envelope, code] of [
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
test("no answer rejects with CONNECTOR_FAILED and status 0", async () => {
|
|
53
|
+
const offline = new Error("offline");
|
|
53
54
|
const client = base(async () => {
|
|
54
|
-
throw
|
|
55
|
+
throw offline;
|
|
55
56
|
});
|
|
56
|
-
await assert.rejects(
|
|
57
|
+
await assert.rejects(
|
|
58
|
+
client.call("c1", "op"),
|
|
59
|
+
(err) => err instanceof ConnectorError && err.code === "CONNECTOR_FAILED" && err.status === 0 && err.cause === offline,
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("a refused call is never retried", async () => {
|
|
64
|
+
const { calls, fetchImpl } = stubFetch(500, { message: "down" });
|
|
65
|
+
await assert.rejects(base(fetchImpl).call("c1", "op"), (err) => err.status === 500);
|
|
66
|
+
assert.equal(calls.length, 1);
|
|
57
67
|
});
|
|
58
68
|
|
|
59
69
|
test("a dot id or an empty operation is refused before any request", async () => {
|
package/dist/transport.js
CHANGED
|
@@ -13,7 +13,7 @@ const DEFAULT_TIMEOUT_MS = 10_000;
|
|
|
13
13
|
// An upload lasts as long as the file takes to cross a mobile link.
|
|
14
14
|
const MULTIPART_TIMEOUT_MS = 5 * 60_000;
|
|
15
15
|
const BACKOFF_MS = [200, 400, 800];
|
|
16
|
-
const RETRY_VERBS =
|
|
16
|
+
const RETRY_VERBS = ["GET", "HEAD"];
|
|
17
17
|
// A longer server hint surfaces the 429 at once instead of hanging a widget.
|
|
18
18
|
const MAX_RETRY_AFTER_MS = DEFAULT_TIMEOUT_MS;
|
|
19
19
|
|
|
@@ -30,7 +30,7 @@ export function joinUrl(base, path) {
|
|
|
30
30
|
* Today's `createXClient` option checks, each message prefixed `${factory}: `.
|
|
31
31
|
* `multipartFetchImpl` defaults to `fetchImpl` and is checked only when given.
|
|
32
32
|
*/
|
|
33
|
-
|
|
33
|
+
function readClientOptions(factory, opts) {
|
|
34
34
|
if (!opts || typeof opts !== "object") {
|
|
35
35
|
throw new TypeError(`${factory}: opts is required`);
|
|
36
36
|
}
|
|
@@ -60,8 +60,17 @@ export function readClientOptions(factory, opts) {
|
|
|
60
60
|
return { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl, multipartFetchImpl };
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
// Ends early when `signal` aborts, so a stop never waits out a backoff.
|
|
64
|
+
function sleep(ms, signal) {
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
const done = () => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
signal?.removeEventListener("abort", done);
|
|
69
|
+
resolve();
|
|
70
|
+
};
|
|
71
|
+
const timer = setTimeout(done, ms);
|
|
72
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
73
|
+
});
|
|
65
74
|
}
|
|
66
75
|
|
|
67
76
|
function secondsToMs(value) {
|
|
@@ -82,8 +91,8 @@ function retryAfterMs(body, header) {
|
|
|
82
91
|
return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
|
|
83
92
|
}
|
|
84
93
|
|
|
85
|
-
function isRetryable(err) {
|
|
86
|
-
if (!err) return false;
|
|
94
|
+
function isRetryable(err, neverRetryCodes) {
|
|
95
|
+
if (!err || neverRetryCodes.includes(err.code)) return false;
|
|
87
96
|
if (err.code === "NETWORK" || err.status === 429 || err.status >= 500) return true;
|
|
88
97
|
// A caller's own `withRetry` attempt may reject with fetch's raw TypeError.
|
|
89
98
|
// A raw AbortError is a caller's cancel, which must stay final.
|
|
@@ -95,7 +104,7 @@ function isRetryable(err) {
|
|
|
95
104
|
* the tenant when there are any, JSON content-type, the call's own headers,
|
|
96
105
|
* then the host's `getRequestHeaders` result without null or undefined values.
|
|
97
106
|
*/
|
|
98
|
-
|
|
107
|
+
async function buildHeaders(
|
|
99
108
|
{ getToken, getTenantId, getRequestHeaders },
|
|
100
109
|
{ json = false, headers: callHeaders, namespace, operation } = {},
|
|
101
110
|
) {
|
|
@@ -116,17 +125,20 @@ export async function buildHeaders(
|
|
|
116
125
|
return headers;
|
|
117
126
|
}
|
|
118
127
|
|
|
119
|
-
// One attempt under its own timer
|
|
120
|
-
//
|
|
121
|
-
async function timedAttempt(attempt, timeoutMs) {
|
|
128
|
+
// One attempt under its own timer (none when `timeoutMs` is null), also
|
|
129
|
+
// ended by the caller's signal. `timedOut` says our timer ended it.
|
|
130
|
+
async function timedAttempt(attempt, timeoutMs, callerSignal) {
|
|
122
131
|
const controller = new AbortController();
|
|
123
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
132
|
+
const timer = timeoutMs == null ? null : setTimeout(() => controller.abort(), timeoutMs);
|
|
133
|
+
const relay = () => controller.abort();
|
|
134
|
+
callerSignal?.addEventListener("abort", relay, { once: true });
|
|
124
135
|
try {
|
|
125
136
|
return { ok: true, value: await attempt(controller.signal) };
|
|
126
137
|
} catch (error) {
|
|
127
|
-
return { ok: false, error, timedOut: controller.signal.aborted };
|
|
138
|
+
return { ok: false, error, timedOut: controller.signal.aborted && !callerSignal?.aborted };
|
|
128
139
|
} finally {
|
|
129
140
|
clearTimeout(timer);
|
|
141
|
+
callerSignal?.removeEventListener("abort", relay);
|
|
130
142
|
}
|
|
131
143
|
}
|
|
132
144
|
|
|
@@ -143,35 +155,69 @@ function parseBody(text) {
|
|
|
143
155
|
* One client's retry contract.
|
|
144
156
|
*
|
|
145
157
|
* @param {{ BaseError: new (message: string, init: { code: string, status: number }) => Error,
|
|
146
|
-
* fromResponse: (status: number, body: unknown) => Error
|
|
147
|
-
*
|
|
158
|
+
* fromResponse: (status: number, body: unknown, retryAfterHeader: string | null) => Error,
|
|
159
|
+
* retryVerbs?: string[] | "all",
|
|
160
|
+
* neverRetryCodes?: string[],
|
|
161
|
+
* backoffMs?: number[],
|
|
162
|
+
* timeoutMs?: number | null,
|
|
163
|
+
* networkError?: (cause: unknown) => Error,
|
|
164
|
+
* timeoutError?: () => Error,
|
|
165
|
+
* cancelledError?: () => Error }} policy
|
|
166
|
+
* `retryVerbs` defaults to GET and HEAD, `backoffMs` to 200/400/800 ms
|
|
167
|
+
* (one retry per entry) and `timeoutMs` to 10 s; null sets no timer. An
|
|
168
|
+
* error whose `code` is in `neverRetryCodes` is final. The three error
|
|
169
|
+
* factories build what a request rejects with when no answer came, when our
|
|
170
|
+
* timer ended it, and when the caller's signal did.
|
|
171
|
+
* @returns The policy, with `withRetry`: the client's public export.
|
|
148
172
|
*/
|
|
149
|
-
export function defineTransportPolicy({
|
|
173
|
+
export function defineTransportPolicy({
|
|
174
|
+
BaseError,
|
|
175
|
+
fromResponse,
|
|
176
|
+
retryVerbs = RETRY_VERBS,
|
|
177
|
+
neverRetryCodes = [],
|
|
178
|
+
backoffMs = BACKOFF_MS,
|
|
179
|
+
timeoutMs: defaultTimeoutMs = DEFAULT_TIMEOUT_MS,
|
|
180
|
+
networkError = (cause) =>
|
|
181
|
+
new BaseError(`Network failure: ${cause?.message}`, { code: "NETWORK", status: 0 }),
|
|
182
|
+
timeoutError = () =>
|
|
183
|
+
new BaseError("Network failure: request timed out", { code: "NETWORK", status: 0 }),
|
|
184
|
+
cancelledError = () =>
|
|
185
|
+
new BaseError("The request was cancelled", { code: "CANCELLED", status: 0 }),
|
|
186
|
+
}) {
|
|
150
187
|
/**
|
|
151
|
-
* Run `attempt` with retries:
|
|
152
|
-
* failure, a 429 or a 5xx; other
|
|
153
|
-
*
|
|
154
|
-
*
|
|
188
|
+
* Run `attempt` with retries: a retried verb up to `retries` (default one
|
|
189
|
+
* per backoff step) more times on a network failure, a 429 or a 5xx; other
|
|
190
|
+
* verbs once. Each attempt gets its own AbortSignal, aborted by the timer or
|
|
191
|
+
* the caller's `signal`; an attempt either ended is not resent, and an
|
|
192
|
+
* aborted `signal` rejects with `cancelledError()` before any attempt.
|
|
155
193
|
*
|
|
156
|
-
* @param {{ method?: string, timeoutMs?: number }} opts
|
|
194
|
+
* @param {{ method?: string, timeoutMs?: number, retries?: number, signal?: AbortSignal }} opts
|
|
157
195
|
* @param {(signal: AbortSignal) => Promise<any>} attempt
|
|
158
196
|
*/
|
|
159
197
|
async function withRetry(opts, attempt) {
|
|
160
198
|
const method = (opts?.method || "GET").toUpperCase();
|
|
161
|
-
const timeoutMs = opts?.timeoutMs ??
|
|
162
|
-
const
|
|
199
|
+
const timeoutMs = opts?.timeoutMs ?? defaultTimeoutMs;
|
|
200
|
+
const callerSignal = opts?.signal ?? null;
|
|
201
|
+
const retries = Number.isInteger(opts?.retries) ? Math.max(0, opts.retries) : backoffMs.length;
|
|
202
|
+
const retried = retryVerbs === "all" || retryVerbs.includes(method);
|
|
203
|
+
const maxAttempts = retried ? retries + 1 : 1;
|
|
163
204
|
for (let i = 0; ; i++) {
|
|
164
|
-
|
|
205
|
+
if (callerSignal?.aborted) throw cancelledError();
|
|
206
|
+
const outcome = await timedAttempt(attempt, timeoutMs, callerSignal);
|
|
165
207
|
if (outcome.ok) return outcome.value;
|
|
166
208
|
const { error } = outcome;
|
|
167
209
|
const hintMs = retryAfterMsByError.get(error) ?? 0;
|
|
168
210
|
// The server may still be working on a request we timed out.
|
|
169
|
-
const final =
|
|
170
|
-
|
|
171
|
-
|
|
211
|
+
const final =
|
|
212
|
+
i === maxAttempts - 1 ||
|
|
213
|
+
outcome.timedOut ||
|
|
214
|
+
callerSignal?.aborted ||
|
|
215
|
+
hintMs > MAX_RETRY_AFTER_MS;
|
|
216
|
+
if (final || !isRetryable(error, neverRetryCodes)) throw error;
|
|
217
|
+
await sleep(Math.max(backoffMs[Math.min(i, backoffMs.length - 1)], hintMs), callerSignal);
|
|
172
218
|
}
|
|
173
219
|
}
|
|
174
|
-
return {
|
|
220
|
+
return { fromResponse, networkError, timeoutError, cancelledError, withRetry };
|
|
175
221
|
}
|
|
176
222
|
|
|
177
223
|
/**
|
|
@@ -185,11 +231,14 @@ export function defineTransportPolicy({ BaseError, fromResponse }) {
|
|
|
185
231
|
export function createRequester(factory, opts, policy, { namespace: defaultNamespace } = {}) {
|
|
186
232
|
const options = readClientOptions(factory, opts);
|
|
187
233
|
const { baseUrl, fetchImpl, multipartFetchImpl } = options;
|
|
188
|
-
const {
|
|
234
|
+
const { fromResponse, networkError, timeoutError, cancelledError, withRetry } = policy;
|
|
189
235
|
|
|
190
236
|
/**
|
|
191
237
|
* `body` is sent as JSON; `formData` verbatim over `multipartFetchImpl`, with
|
|
192
238
|
* no content-type so the runtime sets the multipart boundary.
|
|
239
|
+
* `responseType: "arrayBuffer"` resolves a successful response to its bytes.
|
|
240
|
+
* `accept` replaces the accept header after the host's headers. `signal`
|
|
241
|
+
* is the caller's cancel.
|
|
193
242
|
*/
|
|
194
243
|
async function request(
|
|
195
244
|
method,
|
|
@@ -201,6 +250,9 @@ export function createRequester(factory, opts, policy, { namespace: defaultNames
|
|
|
201
250
|
namespace = defaultNamespace,
|
|
202
251
|
operation,
|
|
203
252
|
timeoutMs,
|
|
253
|
+
responseType = "json",
|
|
254
|
+
accept,
|
|
255
|
+
signal: callerSignal,
|
|
204
256
|
onResponse,
|
|
205
257
|
} = {},
|
|
206
258
|
) {
|
|
@@ -211,33 +263,38 @@ export function createRequester(factory, opts, policy, { namespace: defaultNames
|
|
|
211
263
|
namespace,
|
|
212
264
|
operation,
|
|
213
265
|
});
|
|
266
|
+
// The format this call parses outranks a host's accept header.
|
|
267
|
+
if (accept) headers.accept = accept;
|
|
214
268
|
|
|
215
269
|
const isMultipart = formData !== undefined;
|
|
216
270
|
const send = isMultipart ? multipartFetchImpl : fetchImpl;
|
|
217
271
|
const payload = isMultipart ? formData : body === undefined ? undefined : JSON.stringify(body);
|
|
218
272
|
const deadline = timeoutMs ?? (isMultipart ? MULTIPART_TIMEOUT_MS : undefined);
|
|
219
273
|
|
|
220
|
-
return withRetry({ method, timeoutMs: deadline }, async (signal) => {
|
|
274
|
+
return withRetry({ method, timeoutMs: deadline, signal: callerSignal }, async (signal) => {
|
|
221
275
|
let res;
|
|
222
|
-
let
|
|
276
|
+
let content;
|
|
223
277
|
// The body read can fail like the fetch, so both are classified here.
|
|
224
278
|
try {
|
|
225
279
|
res = await send(url, { method, headers, body: payload, signal });
|
|
226
|
-
|
|
280
|
+
// An error still comes back as the JSON envelope.
|
|
281
|
+
content =
|
|
282
|
+
res.ok && responseType === "arrayBuffer"
|
|
283
|
+
? await res.arrayBuffer()
|
|
284
|
+
: parseBody(await res.text());
|
|
227
285
|
} catch (err) {
|
|
228
|
-
|
|
229
|
-
throw
|
|
286
|
+
if (callerSignal?.aborted) throw cancelledError();
|
|
287
|
+
throw signal.aborted ? timeoutError() : networkError(err);
|
|
230
288
|
}
|
|
231
|
-
const parsed = parseBody(text);
|
|
232
289
|
if (!res.ok) {
|
|
233
|
-
const
|
|
234
|
-
const
|
|
235
|
-
|
|
290
|
+
const retryAfterHeader = res.headers?.get?.("retry-after") ?? null;
|
|
291
|
+
const err = fromResponse(res.status, content, retryAfterHeader);
|
|
292
|
+
const hintMs = res.status === 429 ? retryAfterMs(content, retryAfterHeader) : null;
|
|
236
293
|
if (hintMs != null) retryAfterMsByError.set(err, hintMs);
|
|
237
294
|
throw err;
|
|
238
295
|
}
|
|
239
296
|
onResponse?.(res);
|
|
240
|
-
return
|
|
297
|
+
return content;
|
|
241
298
|
});
|
|
242
299
|
}
|
|
243
300
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@colixsystems/actions-client",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Scoped clients for running a workspace's Actions and calling its REST connectors from an AppStudio app. Used by widgets through the injected WidgetContext.actions and WidgetContext.connectors.",
|
|
5
5
|
"homepage": "https://github.com/Colix-AB/AppStudio",
|
|
6
6
|
"type": "module",
|