apify-client 3.0.0-rc.0 → 3.0.0-rc.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/README.md +10 -2
- package/dist/apify_api_error.d.ts +4 -3
- package/dist/apify_api_error.js +2 -1
- package/dist/apify_client.d.ts +8 -8
- package/dist/apify_client.js +10 -10
- package/dist/apify_client_error.d.ts +10 -0
- package/dist/apify_client_error.js +10 -0
- package/dist/axios.d.ts +2 -0
- package/dist/axios.js +1 -0
- package/dist/base/api_client.js +8 -20
- package/dist/base/resource_client.js +8 -8
- package/dist/body_parser.d.ts +1 -1
- package/dist/bundle.js +31 -30
- package/dist/bundle.js.map +1 -1
- package/dist/generated/api.d.ts +2427 -725
- package/dist/generated/schemas.d.ts +1868 -274
- package/dist/generated/schemas.js +437 -79
- package/dist/http_clients/axios.d.ts +35 -15
- package/dist/http_clients/axios.js +80 -32
- package/dist/http_clients/base.d.ts +105 -34
- package/dist/http_clients/base.js +169 -52
- package/dist/http_clients/fetch.d.ts +53 -0
- package/dist/http_clients/fetch.js +219 -0
- package/dist/http_clients/index.d.ts +2 -2
- package/dist/http_clients/index.js +1 -1
- package/dist/http_compressors/index.d.ts +2 -0
- package/dist/http_compressors/index.js +1 -0
- package/dist/http_compressors/resolve.d.ts +4 -3
- package/dist/http_compressors/resolve.js +4 -1
- package/dist/http_compressors/zstd.d.ts +34 -0
- package/dist/http_compressors/zstd.js +43 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/invalid_response_body_error.d.ts +5 -4
- package/dist/invalid_response_body_error.js +5 -4
- package/dist/models.d.ts +30 -61
- package/dist/resource_clients/actor.d.ts +33 -2
- package/dist/resource_clients/actor.js +46 -3
- package/dist/resource_clients/actor_server.d.ts +149 -0
- package/dist/resource_clients/actor_server.js +195 -0
- package/dist/resource_clients/actor_version.d.ts +7 -1
- package/dist/resource_clients/actor_version.js +3 -2
- package/dist/resource_clients/actor_version_collection.d.ts +2 -1
- package/dist/resource_clients/actor_version_collection.js +3 -2
- package/dist/resource_clients/dataset.d.ts +33 -5
- package/dist/resource_clients/dataset.js +12 -54
- package/dist/resource_clients/key_value_store.d.ts +63 -22
- package/dist/resource_clients/key_value_store.js +62 -19
- package/dist/resource_clients/log.d.ts +32 -7
- package/dist/resource_clients/log.js +11 -14
- package/dist/resource_clients/request_queue.d.ts +9 -0
- package/dist/resource_clients/request_queue.js +9 -6
- package/dist/resource_clients/run.d.ts +15 -2
- package/dist/resource_clients/run.js +12 -5
- package/dist/resource_clients/store_collection.d.ts +4 -0
- package/dist/resource_clients/task.js +3 -3
- package/dist/response_validation_error.d.ts +2 -1
- package/dist/response_validation_error.js +2 -1
- package/dist/runtime/node.js +79 -17
- package/dist/runtime/types.d.ts +35 -5
- package/dist/runtime/web.js +43 -1
- package/dist/schemas.d.ts +369 -3
- package/dist/schemas.js +25 -3
- package/dist/utils.d.ts +52 -27
- package/dist/utils.js +45 -25
- package/package.json +42 -30
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { APIFY_ENV_VARS } from '@apify/consts';
|
|
3
3
|
import log from '@apify/log';
|
|
4
|
-
import { concatStreamToBuffer } from '@apify/utilities';
|
|
5
4
|
import { ApifyApiError } from '../apify_api_error.js';
|
|
6
5
|
import { maybeParseBody } from '../body_parser.js';
|
|
7
6
|
import { resolveCompressor } from '../http_compressors/resolve.js';
|
|
@@ -9,7 +8,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
|
|
|
9
8
|
import { Statistics } from '../statistics.js';
|
|
10
9
|
import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
|
|
11
10
|
import { runtime } from '#runtime';
|
|
12
|
-
import { asArray, getEnv, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
|
|
11
|
+
import { asArray, getEnv, isAnyStream, isBlob, isBuffer, isCompressibleContentType, isStream, isWebStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
|
|
13
12
|
export const DEFAULT_MAX_RETRIES = 8;
|
|
14
13
|
export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
|
|
15
14
|
const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
|
|
@@ -29,7 +28,7 @@ export const httpClientOptionsShape = {
|
|
|
29
28
|
};
|
|
30
29
|
const httpClientOptionsSchema = z.looseObject(httpClientOptionsShape).partial();
|
|
31
30
|
/** Objects whose payload does not live in their own enumerable keys, so JSON serialization loses it. */
|
|
32
|
-
const UNSERIALIZABLE_OBJECT_TAGS = new Set(['
|
|
31
|
+
const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData']);
|
|
33
32
|
/**
|
|
34
33
|
* Base class for the HTTP clients used by {@link ApifyClient}.
|
|
35
34
|
*
|
|
@@ -42,22 +41,33 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['Blob', 'File', 'FormData', 'Readabl
|
|
|
42
41
|
*
|
|
43
42
|
* Overriding {@link call} itself is also supported and bypasses the transport hooks entirely. Such a client has
|
|
44
43
|
* to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never
|
|
45
|
-
* reaches the API.
|
|
46
|
-
*
|
|
44
|
+
* reaches the API. It also has to honor the per-request options {@link ApifyRequestConfig.compression},
|
|
45
|
+
* {@link ApifyRequestConfig.authorizationHeader}, {@link ApifyRequestConfig.throwOnErrorStatus},
|
|
46
|
+
* {@link ApifyRequestConfig.retryStatusCodes}, {@link ApifyRequestConfig.retryTransportErrors} and
|
|
47
|
+
* {@link ApifyRequestConfig.followRedirects}.
|
|
48
|
+
* {@link ActorServerClient.request} relies on them to keep the token away from the Actor's code, to return the
|
|
49
|
+
* server's error responses and to avoid sending a request to the Actor twice. The protected helpers
|
|
50
|
+
* `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay available to it.
|
|
47
51
|
*
|
|
48
52
|
* @example
|
|
49
53
|
* ```javascript
|
|
50
54
|
* import { ApifyClient, HttpClient } from 'apify-client';
|
|
51
55
|
*
|
|
52
|
-
* class
|
|
53
|
-
* async sendRequest({ method, url, headers, body, timeoutMillis, signal }) {
|
|
56
|
+
* class MyFetchHttpClient extends HttpClient {
|
|
57
|
+
* async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
|
|
54
58
|
* const signals = signal ? [signal] : [];
|
|
55
59
|
* if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
|
|
56
|
-
* const response = await fetch(url, {
|
|
60
|
+
* const response = await fetch(url, {
|
|
61
|
+
* method,
|
|
62
|
+
* headers,
|
|
63
|
+
* body,
|
|
64
|
+
* redirect: followRedirects ? 'follow' : 'manual',
|
|
65
|
+
* signal: AbortSignal.any(signals),
|
|
66
|
+
* });
|
|
57
67
|
* return {
|
|
58
68
|
* status: response.status,
|
|
59
69
|
* headers: Object.fromEntries(response.headers),
|
|
60
|
-
* body:
|
|
70
|
+
* body: await response.arrayBuffer(),
|
|
61
71
|
* };
|
|
62
72
|
* }
|
|
63
73
|
*
|
|
@@ -67,7 +77,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['Blob', 'File', 'FormData', 'Readabl
|
|
|
67
77
|
* }
|
|
68
78
|
* }
|
|
69
79
|
*
|
|
70
|
-
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new
|
|
80
|
+
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
|
|
71
81
|
* ```
|
|
72
82
|
*/
|
|
73
83
|
export class HttpClient {
|
|
@@ -169,7 +179,9 @@ export class HttpClient {
|
|
|
169
179
|
* The inherited {@link call} needs it, so every transport has to implement it. Let the library's errors
|
|
170
180
|
* propagate unwrapped: {@link call} classifies them through {@link isRetryableTransportError} and
|
|
171
181
|
* {@link isTimeoutError}. Return error responses as they are too, the pipeline turns them into
|
|
172
|
-
* {@link ApifyApiError} and decides whether to retry.
|
|
182
|
+
* {@link ApifyApiError} and decides whether to retry. Reject when the connection drops before the body is
|
|
183
|
+
* complete: the pipeline takes a returned body as whole and does not retry one that fails to parse. When
|
|
184
|
+
* `request.followRedirects` is `false`, return a redirect response as it is, since the request carries a token.
|
|
173
185
|
*
|
|
174
186
|
* @param request - The request to send, with the headers merged, the body serialized and the query encoded.
|
|
175
187
|
* @returns The response, with the body unread when `request.stream` is set and as raw bytes otherwise.
|
|
@@ -181,44 +193,64 @@ export class HttpClient {
|
|
|
181
193
|
* Makes an API request with automatic retries and exponential backoff.
|
|
182
194
|
*
|
|
183
195
|
* Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
|
|
184
|
-
* are retried up to {@link maxRetries} times.
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
196
|
+
* are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
|
|
197
|
+
* other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
|
|
198
|
+
* is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
|
|
199
|
+
* stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
|
|
200
|
+
* so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
|
|
201
|
+
* the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
|
|
202
|
+
* attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
|
|
188
203
|
*
|
|
189
204
|
* @template T - Type of the parsed response body.
|
|
190
205
|
* @param config - The request to make.
|
|
191
|
-
* @returns The successful response.
|
|
192
|
-
* @throws {ApifyApiError} When the API responds with an error status the retries could not fix
|
|
206
|
+
* @returns The successful response, or the error response when `config.throwOnErrorStatus` is `false`.
|
|
207
|
+
* @throws {ApifyApiError} When the API responds with an error status the retries could not fix, unless
|
|
208
|
+
* `config.throwOnErrorStatus` is `false`.
|
|
193
209
|
*/
|
|
194
210
|
async call(config) {
|
|
195
211
|
config.signal?.throwIfAborted();
|
|
196
212
|
this.stats.calls++;
|
|
197
213
|
const { headers, body } = await this.prepareRequest(config);
|
|
198
214
|
const url = this.buildUrl(config.url, config.params);
|
|
199
|
-
|
|
215
|
+
try {
|
|
216
|
+
return await this.#retryWithExpBackoff(async (stopRetrying, attempt) => this.#makeRequest({ config, url, headers, body, attempt, stopRetrying }), config.signal);
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
// A transport may leave the `Readable` opened over a web stream unread, and the stream locked for good.
|
|
220
|
+
if (isWebStream(config.data) && isStream(body))
|
|
221
|
+
body.destroy();
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
200
224
|
}
|
|
201
225
|
/**
|
|
202
226
|
* Prepares the headers and the body of a request.
|
|
203
227
|
*
|
|
204
|
-
* Merges the client's default headers with the per-request ones, header names compared case-insensitively and
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
* `Content-
|
|
208
|
-
*
|
|
209
|
-
* body is
|
|
228
|
+
* Merges the client's default headers with the per-request ones, header names compared case-insensitively and the
|
|
229
|
+
* per-request values winning, after moving the default `Authorization` header to `X-Apify-Authorization` when
|
|
230
|
+
* `config.authorizationHeader` asks for it. Serializes an object body to JSON, setting
|
|
231
|
+
* `Content-Type: application/json` unless the caller supplied a content type. Runs the body through
|
|
232
|
+
* {@link httpCompressor}, or the compressor in `config.compression`, unless `config.compression` is `false`, a
|
|
233
|
+
* `Content-Encoding` header is already set, the body is too small, or its content type says the payload is already
|
|
234
|
+
* compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded body is
|
|
235
|
+
* uploaded, and `Content-Encoding: identity` opts a single request out of compression.
|
|
210
236
|
*/
|
|
211
237
|
async prepareRequest(config) {
|
|
212
|
-
let headers = mergeHeaders(this.defaultHeaders, config.headers);
|
|
238
|
+
let headers = mergeHeaders(withAuthorizationHeader(this.defaultHeaders, config.authorizationHeader), config.headers);
|
|
213
239
|
let body = serializeBody(config.data, headers, config.stringifyFunctions);
|
|
214
|
-
const
|
|
240
|
+
const compressor = config.compression ?? this.httpCompressor;
|
|
241
|
+
const bytes = compressor && compressibleBytes(body, headers);
|
|
215
242
|
if (bytes) {
|
|
216
|
-
body = await
|
|
243
|
+
body = await compressor.compress(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
217
244
|
// Compressing changes the body length, so a `Content-Length` the caller set describes the wrong body
|
|
218
245
|
// and would leave the server waiting for bytes that never arrive.
|
|
219
|
-
headers = mergeHeaders(headers, { 'Content-Encoding':
|
|
246
|
+
headers = mergeHeaders(headers, { 'Content-Encoding': compressor.contentEncoding });
|
|
220
247
|
deleteHeader(headers, 'content-length');
|
|
221
248
|
}
|
|
249
|
+
// A blob reaches a Node.js transport as a stream, which would go out chunked without a known length.
|
|
250
|
+
// Browsers set the header themselves and refuse to let a page set it.
|
|
251
|
+
if (isBlob(body) && runtime.isNode) {
|
|
252
|
+
headers = mergeHeaders(headers, { 'Content-Length': String(body.size) });
|
|
253
|
+
}
|
|
222
254
|
return { headers, body };
|
|
223
255
|
}
|
|
224
256
|
/**
|
|
@@ -296,48 +328,80 @@ export class HttpClient {
|
|
|
296
328
|
}
|
|
297
329
|
/**
|
|
298
330
|
* Executes one attempt: sends the request, decodes the body and turns an error status into {@link ApifyApiError}.
|
|
299
|
-
* Throws for anything that is not a success,
|
|
300
|
-
* retry could not fix it.
|
|
331
|
+
* Throws for anything that is not a success, unless `config.throwOnErrorStatus` is `false` and no retry follows,
|
|
332
|
+
* and flags the failure as final through `stopRetrying()` when a retry could not fix it.
|
|
301
333
|
*/
|
|
302
334
|
async #makeRequest(options) {
|
|
303
335
|
const { config, url, headers, body, attempt, stopRetrying } = options;
|
|
304
336
|
this.stats.requests++;
|
|
305
|
-
const requestIsStream =
|
|
337
|
+
const requestIsStream = isAnyStream(config.data);
|
|
338
|
+
// The transport reports a failure of the blob as an error of its own, which may pass as transient.
|
|
339
|
+
let sourceFailure;
|
|
340
|
+
const attemptBody = isBlob(body)
|
|
341
|
+
? runtime.openBlobBody(body, (error) => {
|
|
342
|
+
sourceFailure = { error };
|
|
343
|
+
})
|
|
344
|
+
: body;
|
|
306
345
|
let response;
|
|
307
346
|
try {
|
|
308
347
|
response = await this.sendRequest({
|
|
309
348
|
method: config.method,
|
|
310
349
|
url,
|
|
311
350
|
headers,
|
|
312
|
-
body,
|
|
351
|
+
body: attemptBody,
|
|
313
352
|
timeoutMillis: this.computeTimeoutMillis(attempt, config.timeoutSecs),
|
|
314
353
|
stream: config.responseType === 'stream',
|
|
354
|
+
followRedirects: config.followRedirects ?? true,
|
|
315
355
|
signal: config.signal,
|
|
316
356
|
});
|
|
317
357
|
}
|
|
318
358
|
catch (err) {
|
|
319
359
|
// Every HTTP library reports an abort with an error of its own, so the caller gets the reason instead.
|
|
320
360
|
config.signal?.throwIfAborted();
|
|
361
|
+
if (sourceFailure) {
|
|
362
|
+
// Sending the body again cannot fix its source.
|
|
363
|
+
stopRetrying();
|
|
364
|
+
throw withCause(sourceFailure.error, err);
|
|
365
|
+
}
|
|
321
366
|
this.#handleRequestError(err, config, stopRetrying);
|
|
322
367
|
throw err;
|
|
323
368
|
}
|
|
369
|
+
finally {
|
|
370
|
+
// A transport may stop reading the body early, for example on an error response sent before the whole
|
|
371
|
+
// body arrived, which would leave the blob's file open.
|
|
372
|
+
if (attemptBody !== body && isStream(attemptBody))
|
|
373
|
+
attemptBody.destroy();
|
|
374
|
+
}
|
|
375
|
+
const isError = response.status >= 300;
|
|
376
|
+
const isRetryable = isError && this.#isStatusCodeRetryable(response.status, config.retryStatusCodes);
|
|
377
|
+
// An error response goes back to the caller as it is once no retry follows, which a stream body rules out.
|
|
378
|
+
const shouldReturnError = isError &&
|
|
379
|
+
config.throwOnErrorStatus === false &&
|
|
380
|
+
(!isRetryable || requestIsStream || attempt > this.maxRetries);
|
|
381
|
+
// Transports return whichever stream and binary type their HTTP library has, and callers get the web ones.
|
|
382
|
+
if (isStream(response.body))
|
|
383
|
+
response.body = runtime.streamToWeb(response.body);
|
|
324
384
|
// A failed streaming request carries the API error body in the stream, so read it and let
|
|
325
385
|
// `ApifyApiError` parse it like any other error body. A body that cannot be read leaves the error
|
|
326
386
|
// without a message, which beats losing the status code to a stream error.
|
|
327
|
-
if (
|
|
328
|
-
response.body = await
|
|
387
|
+
if (isError && !shouldReturnError && isWebStream(response.body)) {
|
|
388
|
+
response.body = await new Response(response.body).arrayBuffer().catch(() => undefined);
|
|
329
389
|
}
|
|
390
|
+
if (isBuffer(response.body))
|
|
391
|
+
response.body = toResponseBytes(response.body);
|
|
330
392
|
let data;
|
|
331
393
|
try {
|
|
332
394
|
data = this.#parseResponseBody(response, config);
|
|
333
395
|
}
|
|
334
396
|
catch (err) {
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
|
|
397
|
+
// The body of a success arrived in full, since a transfer cut short fails in `sendRequest()`, so a
|
|
398
|
+
// retry would get the same body back.
|
|
399
|
+
if (!isError) {
|
|
338
400
|
stopRetrying();
|
|
401
|
+
throw err;
|
|
339
402
|
}
|
|
340
|
-
|
|
403
|
+
// An error status is reported by its code, and `ApifyApiError` makes what it can of the raw body.
|
|
404
|
+
data = response.body;
|
|
341
405
|
}
|
|
342
406
|
const apifyResponse = {
|
|
343
407
|
status: response.status,
|
|
@@ -345,13 +409,17 @@ export class HttpClient {
|
|
|
345
409
|
data: data,
|
|
346
410
|
config,
|
|
347
411
|
};
|
|
348
|
-
if (
|
|
412
|
+
if (!isError)
|
|
349
413
|
return apifyResponse;
|
|
350
|
-
|
|
414
|
+
// The statistics track the API's rate limits. Only API calls throw on an error status, so a call with
|
|
415
|
+
// `throwOnErrorStatus: false` is taken for a non-API one and its 429s stay out of the statistics.
|
|
416
|
+
if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE && config.throwOnErrorStatus !== false) {
|
|
351
417
|
this.stats.addRateLimitError(attempt);
|
|
352
418
|
}
|
|
419
|
+
if (shouldReturnError)
|
|
420
|
+
return apifyResponse;
|
|
353
421
|
const apiError = ApifyApiError.fromResponse(apifyResponse, attempt);
|
|
354
|
-
if (!
|
|
422
|
+
if (!isRetryable) {
|
|
355
423
|
stopRetrying();
|
|
356
424
|
}
|
|
357
425
|
else if (requestIsStream) {
|
|
@@ -369,7 +437,7 @@ export class HttpClient {
|
|
|
369
437
|
const { body } = response;
|
|
370
438
|
if (config.responseType === 'stream' || config.responseType === 'buffer')
|
|
371
439
|
return body;
|
|
372
|
-
if (body === undefined ||
|
|
440
|
+
if (body === undefined || !isBuffer(body))
|
|
373
441
|
return body;
|
|
374
442
|
if (body.byteLength === 0)
|
|
375
443
|
return undefined;
|
|
@@ -381,28 +449,32 @@ export class HttpClient {
|
|
|
381
449
|
}
|
|
382
450
|
}
|
|
383
451
|
/**
|
|
384
|
-
* Decides whether a transport error ends the call. Timeouts the request opted out of retrying
|
|
385
|
-
* transport does not classify as retryable
|
|
452
|
+
* Decides whether a transport error ends the call. Timeouts the request opted out of retrying, any error on a
|
|
453
|
+
* request that retries no transport errors, errors the transport does not classify as retryable and any error on
|
|
454
|
+
* a request with a stream body are final.
|
|
386
455
|
*/
|
|
387
456
|
#handleRequestError(err, config, stopRetrying) {
|
|
388
457
|
if (config.doNotRetryTimeouts && this.isTimeoutError(err)) {
|
|
389
458
|
stopRetrying();
|
|
390
459
|
return;
|
|
391
460
|
}
|
|
392
|
-
if (!this.isRetryableTransportError(err)) {
|
|
461
|
+
if (config.retryTransportErrors === false || !this.isRetryableTransportError(err)) {
|
|
393
462
|
stopRetrying();
|
|
394
463
|
return;
|
|
395
464
|
}
|
|
396
|
-
if (
|
|
465
|
+
if (isAnyStream(config.data)) {
|
|
397
466
|
this.#informAboutStreamNoRetry();
|
|
398
467
|
stopRetrying();
|
|
399
468
|
}
|
|
400
469
|
}
|
|
401
470
|
/**
|
|
402
|
-
* Rate limits (429) and server errors (500+) are retried
|
|
403
|
-
* cannot follow or invalid input, which repeating the request
|
|
471
|
+
* Rate limits (429) and server errors (500+) are retried, unless the request lists its own `retryStatusCodes`.
|
|
472
|
+
* Anything else in 300-499 is a redirect the client cannot follow or invalid input, which repeating the request
|
|
473
|
+
* cannot fix.
|
|
404
474
|
*/
|
|
405
|
-
#isStatusCodeRetryable(statusCode) {
|
|
475
|
+
#isStatusCodeRetryable(statusCode, retryStatusCodes) {
|
|
476
|
+
if (retryStatusCodes)
|
|
477
|
+
return retryStatusCodes.includes(statusCode);
|
|
406
478
|
return statusCode === RATE_LIMIT_EXCEEDED_STATUS_CODE || statusCode >= 500;
|
|
407
479
|
}
|
|
408
480
|
#informAboutStreamNoRetry() {
|
|
@@ -411,7 +483,10 @@ export class HttpClient {
|
|
|
411
483
|
}
|
|
412
484
|
#onRequestRetry(error, attempt) {
|
|
413
485
|
if (attempt === Math.round(this.maxRetries / 2)) {
|
|
414
|
-
|
|
486
|
+
// A failed `fetch` names the network error only in its `cause`, and Bun gives its errors no stack.
|
|
487
|
+
const { stack, cause } = error;
|
|
488
|
+
const causedBy = cause instanceof Error ? `\nCaused by: ${cause.stack ?? cause}` : '';
|
|
489
|
+
this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${stack ?? error}${causedBy}`);
|
|
415
490
|
}
|
|
416
491
|
}
|
|
417
492
|
}
|
|
@@ -427,7 +502,7 @@ function getHeader(headers, name) {
|
|
|
427
502
|
* Merges two header records, header names compared case-insensitively. A header from `override` replaces a
|
|
428
503
|
* same-named header in `base` whatever the casing of either, and keeps the casing it was passed with.
|
|
429
504
|
*/
|
|
430
|
-
function mergeHeaders(base, override) {
|
|
505
|
+
export function mergeHeaders(base, override) {
|
|
431
506
|
const merged = { ...base };
|
|
432
507
|
for (const [key, value] of Object.entries(override ?? {})) {
|
|
433
508
|
for (const existing of Object.keys(merged)) {
|
|
@@ -438,6 +513,18 @@ function mergeHeaders(base, override) {
|
|
|
438
513
|
}
|
|
439
514
|
return merged;
|
|
440
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Moves the `Authorization` header of `headers` to the header named `name`, or returns `headers` unchanged when
|
|
518
|
+
* `name` is `Authorization`.
|
|
519
|
+
*/
|
|
520
|
+
function withAuthorizationHeader(headers, name = 'Authorization') {
|
|
521
|
+
const authorization = getHeader(headers, 'authorization');
|
|
522
|
+
if (name === 'Authorization' || authorization === undefined)
|
|
523
|
+
return headers;
|
|
524
|
+
const moved = { ...headers };
|
|
525
|
+
deleteHeader(moved, 'authorization');
|
|
526
|
+
return mergeHeaders(moved, { [name]: authorization });
|
|
527
|
+
}
|
|
441
528
|
/**
|
|
442
529
|
* Removes a header by name, compared case-insensitively.
|
|
443
530
|
*/
|
|
@@ -451,7 +538,7 @@ function deleteHeader(headers, name) {
|
|
|
451
538
|
/**
|
|
452
539
|
* Views a serialized body as the bytes to compress, or `undefined` when compressing it would not pay off: the
|
|
453
540
|
* caller already labeled the body with a `Content-Encoding`, its content type carries its own compression, it is
|
|
454
|
-
* a stream or smaller than {@link MIN_COMPRESS_BYTES}, or the runtime has no compression to offer.
|
|
541
|
+
* a stream or a blob, it is smaller than {@link MIN_COMPRESS_BYTES}, or the runtime has no compression to offer.
|
|
455
542
|
*/
|
|
456
543
|
function compressibleBytes(body, headers) {
|
|
457
544
|
if (body === undefined || !runtime.isNode)
|
|
@@ -463,6 +550,29 @@ function compressibleBytes(body, headers) {
|
|
|
463
550
|
const bytes = toBytes(body);
|
|
464
551
|
return bytes && bytes.byteLength >= MIN_COMPRESS_BYTES ? bytes : undefined;
|
|
465
552
|
}
|
|
553
|
+
/**
|
|
554
|
+
* Sets `cause` on an error that has none, and returns the error. A `cause` that already wraps the error, as an axios
|
|
555
|
+
* error wraps the error of its request body, is left out, since linking it would make the chain circular.
|
|
556
|
+
*/
|
|
557
|
+
function withCause(error, cause) {
|
|
558
|
+
if (!(error instanceof Error) || error.cause !== undefined)
|
|
559
|
+
return error;
|
|
560
|
+
const seen = new Set();
|
|
561
|
+
for (let link = cause; link instanceof Error && !seen.has(link); link = link.cause) {
|
|
562
|
+
if (link === error)
|
|
563
|
+
return error;
|
|
564
|
+
seen.add(link);
|
|
565
|
+
}
|
|
566
|
+
error.cause = cause;
|
|
567
|
+
return error;
|
|
568
|
+
}
|
|
569
|
+
/** Views response bytes as a `Uint8Array` without copying them: a `Buffer` in Node.js, which v2 callers rely on. */
|
|
570
|
+
function toResponseBytes(body) {
|
|
571
|
+
if (runtime.isNode && Buffer.isBuffer(body))
|
|
572
|
+
return body;
|
|
573
|
+
const bytes = toBytes(body);
|
|
574
|
+
return runtime.isNode ? Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) : bytes;
|
|
575
|
+
}
|
|
466
576
|
function headerValue(value) {
|
|
467
577
|
return Array.isArray(value) ? value[0] : value;
|
|
468
578
|
}
|
|
@@ -481,6 +591,13 @@ function serializeBody(data, headers, stringifyFunctions) {
|
|
|
481
591
|
return undefined;
|
|
482
592
|
if (isStream(data))
|
|
483
593
|
return data;
|
|
594
|
+
if (isWebStream(data))
|
|
595
|
+
return runtime.openStreamBody(data);
|
|
596
|
+
if (isBlob(data)) {
|
|
597
|
+
if (getHeader(headers, 'content-type') === undefined && data.type)
|
|
598
|
+
headers['Content-Type'] = data.type;
|
|
599
|
+
return data;
|
|
600
|
+
}
|
|
484
601
|
if (isBuffer(data)) {
|
|
485
602
|
// The axios Node.js adapter refuses a body that is neither a `Buffer`, an `ArrayBuffer` nor a string.
|
|
486
603
|
if (!runtime.isNode || Buffer.isBuffer(data))
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { HttpClientOptions, HttpRequest, HttpResponse } from './base.js';
|
|
2
|
+
import { HttpClient } from './base.js';
|
|
3
|
+
/**
|
|
4
|
+
* A function with the signature of the global [`fetch`](https://developer.mozilla.org/docs/Web/API/Window/fetch).
|
|
5
|
+
*/
|
|
6
|
+
export type FetchFunction = typeof globalThis.fetch;
|
|
7
|
+
/**
|
|
8
|
+
* Configuration of {@link FetchHttpClient}.
|
|
9
|
+
*/
|
|
10
|
+
export interface FetchHttpClientOptions extends HttpClientOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The `fetch` implementation the requests go through. Pass a wrapper around the global `fetch` to adjust every
|
|
13
|
+
* request, or the `fetch` of another library, such as `undici` with a dispatcher of your own, to control the
|
|
14
|
+
* connections. A stream body reaches it as an async iterable of byte chunks, or as the stream itself in Bun. In a
|
|
15
|
+
* browser or an edge runtime, a web `ReadableStream` body reaches it as a web stream.
|
|
16
|
+
* @default globalThis.fetch
|
|
17
|
+
*/
|
|
18
|
+
fetch?: FetchFunction;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The default HTTP client of {@link ApifyClient}, built on the `fetch` of the runtime, so it works the same way in
|
|
22
|
+
* Node.js, browsers and edge runtimes and brings no dependency of its own.
|
|
23
|
+
*
|
|
24
|
+
* It inherits the request pipeline from {@link HttpClient} and adds the transport. Network errors are retried,
|
|
25
|
+
* timeouts included, and a stream body is sent without following redirects, since the part of it already sent could
|
|
26
|
+
* not be replayed. The timeout of a request runs until the response headers arrive and starts over with every chunk
|
|
27
|
+
* of the response body and of a stream body, so a large download or upload does not time out while it makes progress.
|
|
28
|
+
*
|
|
29
|
+
* In Node.js, `fetch` keeps connections alive on its own, and goes through a proxy only when Node.js is told to
|
|
30
|
+
* read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables: start it with `NODE_USE_ENV_PROXY=1`
|
|
31
|
+
* (Node.js 22.21 and 24.0) or `--use-env-proxy` (Node.js 22.21 and 24.5).
|
|
32
|
+
*/
|
|
33
|
+
export declare class FetchHttpClient extends HttpClient {
|
|
34
|
+
#private;
|
|
35
|
+
constructor(options?: FetchHttpClientOptions);
|
|
36
|
+
/**
|
|
37
|
+
* A timeout is the `TimeoutError` this client aborts a late request with, or a `fetch` failure caused by one of
|
|
38
|
+
* the connection, headers and body timeouts of Node.js.
|
|
39
|
+
*/
|
|
40
|
+
isTimeoutError(error: unknown): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* A network failure is the `TypeError` that `fetch` rejects with: a connection that could not be made, dropped
|
|
43
|
+
* mid-way or timed out. In Node.js it carries the failure as its `cause`, which tells it apart from a request
|
|
44
|
+
* that was never sent, such as one with an invalid URL. Bun rejects with an `Error` that has a `code` instead.
|
|
45
|
+
*/
|
|
46
|
+
isRetryableTransportError(error: unknown): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Sends the request through `fetch` and hands the raw response back. A stream body is sent without following
|
|
49
|
+
* redirects, and so is a request with `followRedirects: false`. A browser hides such a redirect response from
|
|
50
|
+
* the page, so there it fails the request.
|
|
51
|
+
*/
|
|
52
|
+
sendRequest(request: HttpRequest): Promise<HttpResponse>;
|
|
53
|
+
}
|