@deliverd/sdk 0.8.0 → 0.8.2

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/src/http.ts CHANGED
@@ -1,217 +1,217 @@
1
- import { randomUUID } from "node:crypto";
2
- import { DeliverdError } from "./errors.js";
3
-
4
- /**
5
- * The one place a request is made.
6
- *
7
- * No dependencies: Node 20 has `fetch`, and an SDK that drags a request
8
- * library into every agent runtime for the sake of four verbs is a tax on
9
- * everyone who installs it.
10
- *
11
- * Retries are deliberately narrow. A 429 or a 5xx or a dropped connection is
12
- * worth repeating; a 4xx is the API saying the request itself is wrong, and it
13
- * will be just as wrong in a second. `Retry-After` is honoured when the server
14
- * sends one, because guessing against a server that has told you the answer is
15
- * how a client turns a rate limit into an outage.
16
- */
17
-
18
- export interface ClientOptions {
19
- /** A `dlv_` key from Settings → API tokens, or an OAuth access token. */
20
- apiKey: string;
21
- /** Override for self-hosted or preview deployments. */
22
- baseUrl?: string;
23
- /** Attempts for a retryable failure, the first included. Default 3. */
24
- maxRetries?: number;
25
- /** Per-request timeout in milliseconds. Default 30000. */
26
- timeout?: number;
27
- /** Swapped in tests; defaults to the global. */
28
- fetch?: typeof globalThis.fetch;
29
- }
30
-
31
- export const DEFAULT_BASE_URL = "https://deliverd.dev";
32
-
33
- interface RequestOptions {
34
- method: string;
35
- path: string;
36
- body?: unknown;
37
- query?: Record<string, string | number | undefined>;
38
- signal?: AbortSignal;
39
- /**
40
- * Overrides the key generated for this call. Pass one when the *caller's*
41
- * own retry should be recognised too — a job that reruns from the start
42
- * after a crash wants the key its first run used, which only the caller
43
- * knows how to derive.
44
- */
45
- idempotencyKey?: string;
46
- }
47
-
48
- const sleep = (ms: number, signal?: AbortSignal) =>
49
- new Promise<void>((resolve, reject) => {
50
- if (signal?.aborted) return reject(abortError(signal));
51
- const timer = setTimeout(() => {
52
- signal?.removeEventListener("abort", onAbort);
53
- resolve();
54
- }, ms);
55
- const onAbort = () => {
56
- clearTimeout(timer);
57
- reject(abortError(signal!));
58
- };
59
- signal?.addEventListener("abort", onAbort, { once: true });
60
- });
61
-
62
- function abortError(signal: AbortSignal): DeliverdError {
63
- return new DeliverdError(0, "aborted", "The request was aborted.", undefined, {
64
- cause: signal.reason,
65
- });
66
- }
67
-
68
- /** Exponential from 500ms with jitter, so a fleet of agents does not resonate. */
69
- function backoffMs(attempt: number): number {
70
- const base = Math.min(8000, 500 * 2 ** (attempt - 1));
71
- return base / 2 + Math.random() * (base / 2);
72
- }
73
-
74
- export class HttpClient {
75
- readonly baseUrl: string;
76
- private readonly apiKey: string;
77
- private readonly maxRetries: number;
78
- private readonly timeout: number;
79
- private readonly doFetch: typeof globalThis.fetch;
80
-
81
- constructor(options: ClientOptions) {
82
- if (!options.apiKey) {
83
- throw new DeliverdError(0, "no_api_key", "An apiKey is required.");
84
- }
85
- this.apiKey = options.apiKey;
86
- this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
87
- this.maxRetries = Math.max(1, options.maxRetries ?? 3);
88
- this.timeout = options.timeout ?? 30_000;
89
- this.doFetch = options.fetch ?? globalThis.fetch;
90
- }
91
-
92
- async request<T>(options: RequestOptions): Promise<T> {
93
- const url = new URL(`${this.baseUrl}/api/v1${options.path}`);
94
- for (const [key, value] of Object.entries(options.query ?? {})) {
95
- if (value !== undefined) url.searchParams.set(key, String(value));
96
- }
97
-
98
- const correlationId = randomUUID();
99
- /*
100
- * One key per logical request, held across every attempt below — which is
101
- * the whole point. These retries are why the server needs replay
102
- * protection at all: a POST that arrived and lost its response on the way
103
- * back used to be retried as a second create, and for an approval that
104
- * means two people asked to authorise one act.
105
- *
106
- * Only on POST: nothing else here creates anything.
107
- */
108
- const idempotencyKey =
109
- options.method === "POST" ? (options.idempotencyKey ?? randomUUID()) : undefined;
110
- let lastError: DeliverdError | undefined;
111
- for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
112
- if (attempt > 1) await sleep(lastError ? retryDelay(lastError, attempt) : backoffMs(attempt), options.signal);
113
-
114
- // The caller's signal and our own timeout, whichever fires first.
115
- const timer = AbortSignal.timeout(this.timeout);
116
- const signal = options.signal ? AbortSignal.any([options.signal, timer]) : timer;
117
-
118
- let response: Response;
119
- try {
120
- response = await this.doFetch(url, {
121
- method: options.method,
122
- headers: {
123
- Authorization: `Bearer ${this.apiKey}`,
124
- Accept: "application/json",
125
- "User-Agent": USER_AGENT,
126
- // One id per logical request, kept across retries: it is the
127
- // thing to quote when something went wrong, and generating it
128
- // here means nobody has to remember to.
129
- "deliverd-correlation-id": correlationId,
130
- ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
131
- ...(options.body !== undefined ? { "Content-Type": "application/json" } : {}),
132
- },
133
- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
134
- signal,
135
- });
136
- } catch (cause) {
137
- if (options.signal?.aborted) throw abortError(options.signal);
138
- lastError = new DeliverdError(0, "network_error", describeNetworkError(cause), undefined, { cause });
139
- if (attempt === this.maxRetries) throw lastError;
140
- continue;
141
- }
142
-
143
- if (response.status === 204) return undefined as T;
144
-
145
- const text = await response.text();
146
- let json: unknown;
147
- try {
148
- json = text ? JSON.parse(text) : {};
149
- } catch {
150
- lastError = new DeliverdError(
151
- response.status,
152
- "invalid_response",
153
- `Expected JSON from ${url.pathname} and got ${text.slice(0, 120)}`
154
- );
155
- if (isRetryable(response.status) && attempt < this.maxRetries) continue;
156
- throw lastError;
157
- }
158
-
159
- if (response.ok) return json as T;
160
-
161
- const envelope = (json as { error?: { code?: string; message?: string; details?: unknown } }).error;
162
- lastError = new DeliverdError(
163
- response.status,
164
- envelope?.code ?? "error",
165
- envelope?.message ?? `Request failed (${response.status})`,
166
- envelope?.details
167
- );
168
- (lastError as { retryAfter?: number }).retryAfter = parseRetryAfter(response.headers.get("retry-after"));
169
- if (isRetryable(response.status) && attempt < this.maxRetries) continue;
170
- throw lastError;
171
- }
172
- throw lastError ?? new DeliverdError(0, "error", "Request failed.");
173
- }
174
- }
175
-
176
- export const USER_AGENT = "deliverd-sdk";
177
-
178
- /**
179
- * A 5xx the server might get right next time. 501 is not one of them: it means
180
- * the call is not built, which is a fact about the server rather than about
181
- * this moment — the same argument as a 4xx.
182
- *
183
- * Ported from the Python SDK, which found it first and where the symptom was a
184
- * development-mode call taking two and a half seconds to say three times that
185
- * it is not implemented. The fix was never brought back here, and nothing
186
- * compared the two until `packages/conformance/cases.json` existed.
187
- */
188
- const RETRYABLE_5XX_EXCEPTIONS = new Set([501]);
189
-
190
- /** 429 and most 5xx: a 4xx will be just as wrong on the next attempt. */
191
- function isRetryable(status: number): boolean {
192
- if (status === 429) return true;
193
- return status >= 500 && !RETRYABLE_5XX_EXCEPTIONS.has(status);
194
- }
195
-
196
- function parseRetryAfter(header: string | null): number | undefined {
197
- if (!header) return undefined;
198
- const seconds = Number(header);
199
- if (Number.isFinite(seconds)) return seconds * 1000;
200
- const date = Date.parse(header);
201
- return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
202
- }
203
-
204
- function retryDelay(error: DeliverdError, attempt: number): number {
205
- const after = (error as { retryAfter?: number }).retryAfter;
206
- return after !== undefined ? after : backoffMs(attempt);
207
- }
208
-
209
- /**
210
- * A dropped connection says nothing useful on its own, and the first thing
211
- * anyone wonders is whether they typed the host wrong.
212
- */
213
- function describeNetworkError(cause: unknown): string {
214
- const message = cause instanceof Error ? cause.message : String(cause);
215
- if (/timed? ?out|TimeoutError/i.test(message)) return `The request timed out: ${message}`;
216
- return `Could not reach Deliverd: ${message}`;
217
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { DeliverdError } from "./errors.js";
3
+
4
+ /**
5
+ * The one place a request is made.
6
+ *
7
+ * No dependencies: Node 20 has `fetch`, and an SDK that drags a request
8
+ * library into every agent runtime for the sake of four verbs is a tax on
9
+ * everyone who installs it.
10
+ *
11
+ * Retries are deliberately narrow. A 429 or a 5xx or a dropped connection is
12
+ * worth repeating; a 4xx is the API saying the request itself is wrong, and it
13
+ * will be just as wrong in a second. `Retry-After` is honoured when the server
14
+ * sends one, because guessing against a server that has told you the answer is
15
+ * how a client turns a rate limit into an outage.
16
+ */
17
+
18
+ export interface ClientOptions {
19
+ /** A `dlv_` key from Settings → API tokens, or an OAuth access token. */
20
+ apiKey: string;
21
+ /** Override for self-hosted or preview deployments. */
22
+ baseUrl?: string;
23
+ /** Attempts for a retryable failure, the first included. Default 3. */
24
+ maxRetries?: number;
25
+ /** Per-request timeout in milliseconds. Default 30000. */
26
+ timeout?: number;
27
+ /** Swapped in tests; defaults to the global. */
28
+ fetch?: typeof globalThis.fetch;
29
+ }
30
+
31
+ export const DEFAULT_BASE_URL = "https://deliverd.dev";
32
+
33
+ interface RequestOptions {
34
+ method: string;
35
+ path: string;
36
+ body?: unknown;
37
+ query?: Record<string, string | number | undefined>;
38
+ signal?: AbortSignal;
39
+ /**
40
+ * Overrides the key generated for this call. Pass one when the *caller's*
41
+ * own retry should be recognised too — a job that reruns from the start
42
+ * after a crash wants the key its first run used, which only the caller
43
+ * knows how to derive.
44
+ */
45
+ idempotencyKey?: string;
46
+ }
47
+
48
+ const sleep = (ms: number, signal?: AbortSignal) =>
49
+ new Promise<void>((resolve, reject) => {
50
+ if (signal?.aborted) return reject(abortError(signal));
51
+ const timer = setTimeout(() => {
52
+ signal?.removeEventListener("abort", onAbort);
53
+ resolve();
54
+ }, ms);
55
+ const onAbort = () => {
56
+ clearTimeout(timer);
57
+ reject(abortError(signal!));
58
+ };
59
+ signal?.addEventListener("abort", onAbort, { once: true });
60
+ });
61
+
62
+ function abortError(signal: AbortSignal): DeliverdError {
63
+ return new DeliverdError(0, "aborted", "The request was aborted.", undefined, {
64
+ cause: signal.reason,
65
+ });
66
+ }
67
+
68
+ /** Exponential from 500ms with jitter, so a fleet of agents does not resonate. */
69
+ function backoffMs(attempt: number): number {
70
+ const base = Math.min(8000, 500 * 2 ** (attempt - 1));
71
+ return base / 2 + Math.random() * (base / 2);
72
+ }
73
+
74
+ export class HttpClient {
75
+ readonly baseUrl: string;
76
+ private readonly apiKey: string;
77
+ private readonly maxRetries: number;
78
+ private readonly timeout: number;
79
+ private readonly doFetch: typeof globalThis.fetch;
80
+
81
+ constructor(options: ClientOptions) {
82
+ if (!options.apiKey) {
83
+ throw new DeliverdError(0, "no_api_key", "An apiKey is required.");
84
+ }
85
+ this.apiKey = options.apiKey;
86
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
87
+ this.maxRetries = Math.max(1, options.maxRetries ?? 3);
88
+ this.timeout = options.timeout ?? 30_000;
89
+ this.doFetch = options.fetch ?? globalThis.fetch;
90
+ }
91
+
92
+ async request<T>(options: RequestOptions): Promise<T> {
93
+ const url = new URL(`${this.baseUrl}/api/v1${options.path}`);
94
+ for (const [key, value] of Object.entries(options.query ?? {})) {
95
+ if (value !== undefined) url.searchParams.set(key, String(value));
96
+ }
97
+
98
+ const correlationId = randomUUID();
99
+ /*
100
+ * One key per logical request, held across every attempt below — which is
101
+ * the whole point. These retries are why the server needs replay
102
+ * protection at all: a POST that arrived and lost its response on the way
103
+ * back used to be retried as a second create, and for an approval that
104
+ * means two people asked to authorise one act.
105
+ *
106
+ * Only on POST: nothing else here creates anything.
107
+ */
108
+ const idempotencyKey =
109
+ options.method === "POST" ? (options.idempotencyKey ?? randomUUID()) : undefined;
110
+ let lastError: DeliverdError | undefined;
111
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
112
+ if (attempt > 1) await sleep(lastError ? retryDelay(lastError, attempt) : backoffMs(attempt), options.signal);
113
+
114
+ // The caller's signal and our own timeout, whichever fires first.
115
+ const timer = AbortSignal.timeout(this.timeout);
116
+ const signal = options.signal ? AbortSignal.any([options.signal, timer]) : timer;
117
+
118
+ let response: Response;
119
+ try {
120
+ response = await this.doFetch(url, {
121
+ method: options.method,
122
+ headers: {
123
+ Authorization: `Bearer ${this.apiKey}`,
124
+ Accept: "application/json",
125
+ "User-Agent": USER_AGENT,
126
+ // One id per logical request, kept across retries: it is the
127
+ // thing to quote when something went wrong, and generating it
128
+ // here means nobody has to remember to.
129
+ "deliverd-correlation-id": correlationId,
130
+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
131
+ ...(options.body !== undefined ? { "Content-Type": "application/json" } : {}),
132
+ },
133
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
134
+ signal,
135
+ });
136
+ } catch (cause) {
137
+ if (options.signal?.aborted) throw abortError(options.signal);
138
+ lastError = new DeliverdError(0, "network_error", describeNetworkError(cause), undefined, { cause });
139
+ if (attempt === this.maxRetries) throw lastError;
140
+ continue;
141
+ }
142
+
143
+ if (response.status === 204) return undefined as T;
144
+
145
+ const text = await response.text();
146
+ let json: unknown;
147
+ try {
148
+ json = text ? JSON.parse(text) : {};
149
+ } catch {
150
+ lastError = new DeliverdError(
151
+ response.status,
152
+ "invalid_response",
153
+ `Expected JSON from ${url.pathname} and got ${text.slice(0, 120)}`
154
+ );
155
+ if (isRetryable(response.status) && attempt < this.maxRetries) continue;
156
+ throw lastError;
157
+ }
158
+
159
+ if (response.ok) return json as T;
160
+
161
+ const envelope = (json as { error?: { code?: string; message?: string; details?: unknown } }).error;
162
+ lastError = new DeliverdError(
163
+ response.status,
164
+ envelope?.code ?? "error",
165
+ envelope?.message ?? `Request failed (${response.status})`,
166
+ envelope?.details
167
+ );
168
+ (lastError as { retryAfter?: number }).retryAfter = parseRetryAfter(response.headers.get("retry-after"));
169
+ if (isRetryable(response.status) && attempt < this.maxRetries) continue;
170
+ throw lastError;
171
+ }
172
+ throw lastError ?? new DeliverdError(0, "error", "Request failed.");
173
+ }
174
+ }
175
+
176
+ export const USER_AGENT = "deliverd-sdk";
177
+
178
+ /**
179
+ * A 5xx the server might get right next time. 501 is not one of them: it means
180
+ * the call is not built, which is a fact about the server rather than about
181
+ * this moment — the same argument as a 4xx.
182
+ *
183
+ * Ported from the Python SDK, which found it first and where the symptom was a
184
+ * development-mode call taking two and a half seconds to say three times that
185
+ * it is not implemented. The fix was never brought back here, and nothing
186
+ * compared the two until `packages/conformance/cases.json` existed.
187
+ */
188
+ const RETRYABLE_5XX_EXCEPTIONS = new Set([501]);
189
+
190
+ /** 429 and most 5xx: a 4xx will be just as wrong on the next attempt. */
191
+ function isRetryable(status: number): boolean {
192
+ if (status === 429) return true;
193
+ return status >= 500 && !RETRYABLE_5XX_EXCEPTIONS.has(status);
194
+ }
195
+
196
+ function parseRetryAfter(header: string | null): number | undefined {
197
+ if (!header) return undefined;
198
+ const seconds = Number(header);
199
+ if (Number.isFinite(seconds)) return seconds * 1000;
200
+ const date = Date.parse(header);
201
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
202
+ }
203
+
204
+ function retryDelay(error: DeliverdError, attempt: number): number {
205
+ const after = (error as { retryAfter?: number }).retryAfter;
206
+ return after !== undefined ? after : backoffMs(attempt);
207
+ }
208
+
209
+ /**
210
+ * A dropped connection says nothing useful on its own, and the first thing
211
+ * anyone wonders is whether they typed the host wrong.
212
+ */
213
+ function describeNetworkError(cause: unknown): string {
214
+ const message = cause instanceof Error ? cause.message : String(cause);
215
+ if (/timed? ?out|TimeoutError/i.test(message)) return `The request timed out: ${message}`;
216
+ return `Could not reach Deliverd: ${message}`;
217
+ }