apify-client 3.0.0-beta.115 → 3.0.0-beta.116
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/dist/bundle.js +7 -7
- package/dist/bundle.js.map +1 -1
- package/dist/http_clients/axios.js +6 -4
- package/dist/http_clients/base.d.ts +13 -10
- package/dist/http_clients/base.js +20 -10
- package/dist/http_clients/fetch.d.ts +2 -1
- package/dist/http_clients/fetch.js +41 -5
- package/dist/resource_clients/actor.d.ts +2 -1
- package/dist/resource_clients/actor.js +3 -3
- package/dist/resource_clients/actor_server.d.ts +1 -1
- package/dist/resource_clients/key_value_store.d.ts +11 -9
- package/dist/resource_clients/key_value_store.js +10 -13
- package/dist/resource_clients/task.js +3 -3
- package/dist/runtime/node.js +3 -0
- package/dist/runtime/types.d.ts +7 -0
- package/dist/runtime/web.js +31 -0
- package/dist/utils.d.ts +6 -1
- package/dist/utils.js +8 -1
- package/package.json +2 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import axios, { AxiosError, AxiosHeaders } from 'axios';
|
|
2
2
|
import { runtime } from '#runtime';
|
|
3
3
|
import { ApifyClientError } from '../apify_client_error.js';
|
|
4
|
-
import {
|
|
4
|
+
import { isAnyStream, isWebStream } from '../utils.js';
|
|
5
5
|
import { HttpClient } from './base.js';
|
|
6
6
|
/**
|
|
7
7
|
* An HTTP client for {@link ApifyClient} built on [axios](https://axios-http.com), which was the transport of the
|
|
@@ -102,8 +102,10 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
102
102
|
*/
|
|
103
103
|
async sendRequest(request) {
|
|
104
104
|
await this.#ensureHttpAgents();
|
|
105
|
-
const { method, url, headers,
|
|
106
|
-
|
|
105
|
+
const { method, url, headers, timeoutMillis, stream, followRedirects, signal } = request;
|
|
106
|
+
// The Node.js adapter of axios refuses a web stream, and an XHR cannot send one either.
|
|
107
|
+
const body = runtime.isNode && isWebStream(request.body) ? runtime.openStreamBody(request.body) : request.body;
|
|
108
|
+
const useFetch = (!followRedirects || stream || isWebStream(body)) && !runtime.isNode;
|
|
107
109
|
// The fetch adapter keeps the axios timeout running until a streamed response is read to its end.
|
|
108
110
|
const headersTimeout = useFetch && stream && timeoutMillis !== undefined ? new AbortController() : undefined;
|
|
109
111
|
const headersTimer = headersTimeout &&
|
|
@@ -124,7 +126,7 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
124
126
|
responseType: stream ? 'stream' : 'arraybuffer',
|
|
125
127
|
// See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The fetch
|
|
126
128
|
// adapter turns this into `redirect: 'manual'`.
|
|
127
|
-
...(
|
|
129
|
+
...(isAnyStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
|
|
128
130
|
...(useFetch ? { adapter: 'fetch' } : {}),
|
|
129
131
|
})
|
|
130
132
|
.catch((error) => {
|
|
@@ -29,8 +29,10 @@ export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
|
|
|
29
29
|
* A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
|
|
30
30
|
* is passed through untouched and is only available in Node.js. A `Blob` body reaches a Node.js transport as a
|
|
31
31
|
* fresh `Readable` over its bytes for every attempt, and a transport in any other runtime as the `Blob` itself.
|
|
32
|
+
* A web `ReadableStream` body reaches a Node.js transport as a `Readable` too, and a transport in any other
|
|
33
|
+
* runtime as the stream itself.
|
|
32
34
|
*/
|
|
33
|
-
export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | Blob;
|
|
35
|
+
export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | ReadableStream<Uint8Array> | Blob;
|
|
34
36
|
/**
|
|
35
37
|
* A response body as the transport hands it back: the raw bytes, a web `ReadableStream` or a `Readable` when the
|
|
36
38
|
* request asked for a streamed response, or `undefined` when the response carried no body. The pipeline hands the bytes
|
|
@@ -65,10 +67,11 @@ export interface ApifyRequestConfig {
|
|
|
65
67
|
/**
|
|
66
68
|
* Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
|
|
67
69
|
* when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
|
|
68
|
-
* (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and
|
|
69
|
-
* form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed
|
|
70
|
-
* memory, under its own `type` when no `Content-Type` header is set. A `FormData`
|
|
71
|
-
* rejected with a `TypeError`, since serializing one would send an empty body
|
|
70
|
+
* (`Buffer`, `ArrayBuffer`, typed array) or stream (`Readable`, web `ReadableStream`) is sent as it is, and
|
|
71
|
+
* `URLSearchParams` is sent form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed
|
|
72
|
+
* without being held in memory, under its own `type` when no `Content-Type` header is set. A `FormData` is
|
|
73
|
+
* rejected with a `TypeError`, since serializing one would send an empty body, and so is a web `ReadableStream`
|
|
74
|
+
* in a browser that cannot send one.
|
|
72
75
|
*/
|
|
73
76
|
data?: unknown;
|
|
74
77
|
/**
|
|
@@ -347,11 +350,11 @@ export declare abstract class HttpClient {
|
|
|
347
350
|
* Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
|
|
348
351
|
* are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
|
|
349
352
|
* other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
|
|
350
|
-
* is `false`. A request whose body is a `Readable` is never retried, since part of the
|
|
351
|
-
* consumed by the time the failure shows. A `Blob` body is read again for every attempt,
|
|
352
|
-
* any other, unless reading the blob itself fails: that error is thrown right away, with
|
|
353
|
-
* as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
|
|
354
|
-
* skips the remaining retries and rejects the call with the signal's `reason`.
|
|
353
|
+
* is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
|
|
354
|
+
* stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
|
|
355
|
+
* so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
|
|
356
|
+
* the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
|
|
357
|
+
* attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
|
|
355
358
|
*
|
|
356
359
|
* @template T - Type of the parsed response body.
|
|
357
360
|
* @param config - The request to make.
|
|
@@ -8,7 +8,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
|
|
|
8
8
|
import { Statistics } from '../statistics.js';
|
|
9
9
|
import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
|
|
10
10
|
import { runtime } from '#runtime';
|
|
11
|
-
import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, isWebStream, 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';
|
|
12
12
|
export const DEFAULT_MAX_RETRIES = 8;
|
|
13
13
|
export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
|
|
14
14
|
const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
|
|
@@ -28,7 +28,7 @@ export const httpClientOptionsShape = {
|
|
|
28
28
|
};
|
|
29
29
|
const httpClientOptionsSchema = z.looseObject(httpClientOptionsShape).partial();
|
|
30
30
|
/** Objects whose payload does not live in their own enumerable keys, so JSON serialization loses it. */
|
|
31
|
-
const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData'
|
|
31
|
+
const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData']);
|
|
32
32
|
/**
|
|
33
33
|
* Base class for the HTTP clients used by {@link ApifyClient}.
|
|
34
34
|
*
|
|
@@ -195,11 +195,11 @@ export class HttpClient {
|
|
|
195
195
|
* Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
|
|
196
196
|
* are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
|
|
197
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` is never retried, since part of the
|
|
199
|
-
* consumed by the time the failure shows. A `Blob` body is read again for every attempt,
|
|
200
|
-
* any other, unless reading the blob itself fails: that error is thrown right away, with
|
|
201
|
-
* as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
|
|
202
|
-
* skips the remaining retries and rejects the call with the signal's `reason`.
|
|
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`.
|
|
203
203
|
*
|
|
204
204
|
* @template T - Type of the parsed response body.
|
|
205
205
|
* @param config - The request to make.
|
|
@@ -212,7 +212,15 @@ export class HttpClient {
|
|
|
212
212
|
this.stats.calls++;
|
|
213
213
|
const { headers, body } = await this.prepareRequest(config);
|
|
214
214
|
const url = this.buildUrl(config.url, config.params);
|
|
215
|
-
|
|
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
|
+
}
|
|
216
224
|
}
|
|
217
225
|
/**
|
|
218
226
|
* Prepares the headers and the body of a request.
|
|
@@ -326,7 +334,7 @@ export class HttpClient {
|
|
|
326
334
|
async #makeRequest(options) {
|
|
327
335
|
const { config, url, headers, body, attempt, stopRetrying } = options;
|
|
328
336
|
this.stats.requests++;
|
|
329
|
-
const requestIsStream =
|
|
337
|
+
const requestIsStream = isAnyStream(config.data);
|
|
330
338
|
// The transport reports a failure of the blob as an error of its own, which may pass as transient.
|
|
331
339
|
let sourceFailure;
|
|
332
340
|
const attemptBody = isBlob(body)
|
|
@@ -454,7 +462,7 @@ export class HttpClient {
|
|
|
454
462
|
stopRetrying();
|
|
455
463
|
return;
|
|
456
464
|
}
|
|
457
|
-
if (
|
|
465
|
+
if (isAnyStream(config.data)) {
|
|
458
466
|
this.#informAboutStreamNoRetry();
|
|
459
467
|
stopRetrying();
|
|
460
468
|
}
|
|
@@ -583,6 +591,8 @@ function serializeBody(data, headers, stringifyFunctions) {
|
|
|
583
591
|
return undefined;
|
|
584
592
|
if (isStream(data))
|
|
585
593
|
return data;
|
|
594
|
+
if (isWebStream(data))
|
|
595
|
+
return runtime.openStreamBody(data);
|
|
586
596
|
if (isBlob(data)) {
|
|
587
597
|
if (getHeader(headers, 'content-type') === undefined && data.type)
|
|
588
598
|
headers['Content-Type'] = data.type;
|
|
@@ -11,7 +11,8 @@ export interface FetchHttpClientOptions extends HttpClientOptions {
|
|
|
11
11
|
/**
|
|
12
12
|
* The `fetch` implementation the requests go through. Pass a wrapper around the global `fetch` to adjust every
|
|
13
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.
|
|
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.
|
|
15
16
|
* @default globalThis.fetch
|
|
16
17
|
*/
|
|
17
18
|
fetch?: FetchFunction;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { runtime } from '#runtime';
|
|
2
2
|
import { ApifyClientError } from '../apify_client_error.js';
|
|
3
|
-
import { isStream } from '../utils.js';
|
|
3
|
+
import { isAnyStream, isStream, isWebStream } from '../utils.js';
|
|
4
4
|
import { HttpClient } from './base.js';
|
|
5
5
|
/** Error codes of the timeouts that Node.js reports as the `cause` of a failed `fetch`. */
|
|
6
6
|
const TIMEOUT_ERROR_CODES = new Set([
|
|
@@ -81,21 +81,22 @@ export class FetchHttpClient extends HttpClient {
|
|
|
81
81
|
timer = setTimeout(() => timeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError')), timeoutMillis);
|
|
82
82
|
};
|
|
83
83
|
restartTimeout();
|
|
84
|
+
let sentBody;
|
|
84
85
|
try {
|
|
85
86
|
// Browsers and Deno reject an invalid URL with the same bare `TypeError` as a network failure.
|
|
86
87
|
const baseUrl = globalThis.location?.href;
|
|
87
88
|
if (!runtime.fetchFailsWithCause && !URL.canParse(url, baseUrl)) {
|
|
88
89
|
throw Object.assign(new TypeError(`Invalid URL: ${url}`), { code: 'ERR_INVALID_URL' });
|
|
89
90
|
}
|
|
91
|
+
sentBody = trackProgress(body, restartTimeout);
|
|
90
92
|
const response = await (this.#fetch ?? globalThis.fetch)(url, {
|
|
91
93
|
method,
|
|
92
94
|
headers,
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
redirect: followRedirects && !isStream(body) ? 'follow' : 'manual',
|
|
95
|
+
body: sentBody,
|
|
96
|
+
redirect: followRedirects && !isAnyStream(body) ? 'follow' : 'manual',
|
|
96
97
|
signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
|
|
97
98
|
// Required for a stream body, and ignored for any other.
|
|
98
|
-
...(
|
|
99
|
+
...(isAnyStream(body) ? { duplex: 'half' } : {}),
|
|
99
100
|
});
|
|
100
101
|
// `redirect: 'manual'` resolves to an opaque response with status 0 in a browser.
|
|
101
102
|
if (response.type === 'opaqueredirect') {
|
|
@@ -109,6 +110,9 @@ export class FetchHttpClient extends HttpClient {
|
|
|
109
110
|
};
|
|
110
111
|
}
|
|
111
112
|
catch (error) {
|
|
113
|
+
// A `fetch` that refused the request never took the body over, which keeps the caller's stream locked.
|
|
114
|
+
if (isWebStream(sentBody) && !sentBody.locked)
|
|
115
|
+
sentBody.cancel(error).catch(() => { });
|
|
112
116
|
if (!this.#fetch && this.isRetryableTransportError(error))
|
|
113
117
|
this.#warnAboutUnusedProxy();
|
|
114
118
|
throw error;
|
|
@@ -129,6 +133,15 @@ export class FetchHttpClient extends HttpClient {
|
|
|
129
133
|
const isBun = 'Bun' in globalThis;
|
|
130
134
|
/** A larger chunk of a stream body is passed on in pieces, since a `Blob` held in memory arrives as a single one. */
|
|
131
135
|
const MAX_BODY_CHUNK_BYTES = 64 * 1024;
|
|
136
|
+
/** Makes a stream body report every chunk that `fetch` reads from it, and leaves any other body as it is. */
|
|
137
|
+
function trackProgress(body, onChunk) {
|
|
138
|
+
if (isWebStream(body))
|
|
139
|
+
return withWebProgress(body, onChunk);
|
|
140
|
+
// Node.js reads an async iterable, which the DOM types do not know about.
|
|
141
|
+
if (isStream(body) && !isBun)
|
|
142
|
+
return withProgress(body, onChunk);
|
|
143
|
+
return body;
|
|
144
|
+
}
|
|
132
145
|
/** Passes a stream body on piece by piece, so that a large upload counts as alive for as long as it is being read. */
|
|
133
146
|
async function* withProgress(body, onChunk) {
|
|
134
147
|
for await (const chunk of body) {
|
|
@@ -145,6 +158,29 @@ async function* withProgress(body, onChunk) {
|
|
|
145
158
|
}
|
|
146
159
|
}
|
|
147
160
|
}
|
|
161
|
+
/** Does for a web stream body what {@link withProgress} does for an async iterable. */
|
|
162
|
+
function withWebProgress(body, onChunk) {
|
|
163
|
+
const reader = body.getReader();
|
|
164
|
+
let rest;
|
|
165
|
+
return new ReadableStream({
|
|
166
|
+
async pull(controller) {
|
|
167
|
+
if (!rest?.byteLength) {
|
|
168
|
+
const { done, value } = await reader.read();
|
|
169
|
+
if (done)
|
|
170
|
+
return controller.close();
|
|
171
|
+
rest = value;
|
|
172
|
+
}
|
|
173
|
+
onChunk();
|
|
174
|
+
controller.enqueue(rest.subarray(0, MAX_BODY_CHUNK_BYTES));
|
|
175
|
+
rest = rest.subarray(MAX_BODY_CHUNK_BYTES);
|
|
176
|
+
},
|
|
177
|
+
async cancel(reason) {
|
|
178
|
+
await reader.cancel(reason);
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
// Reads a piece only once `fetch` asks for it.
|
|
182
|
+
{ highWaterMark: 0 });
|
|
183
|
+
}
|
|
148
184
|
/**
|
|
149
185
|
* Reads the response body chunk by chunk, so that a large download counts as alive for as long as bytes arrive.
|
|
150
186
|
*/
|
|
@@ -413,7 +413,8 @@ export interface ActorStartOptions extends TimeoutOptions {
|
|
|
413
413
|
* A run that requests more memory than the whole memory limit of the account is rejected with
|
|
414
414
|
* `actor-memory-limit-exceeded` as well and never starts, so `true` retries it forever.
|
|
415
415
|
*
|
|
416
|
-
* A `Readable`
|
|
416
|
+
* A stream input (`Readable` or web `ReadableStream`) can't be sent twice, so its start is never retried and the
|
|
417
|
+
* first rejection is thrown.
|
|
417
418
|
*/
|
|
418
419
|
waitForResources?: boolean | number;
|
|
419
420
|
}
|
|
@@ -4,7 +4,7 @@ import { Log } from '@apify/log';
|
|
|
4
4
|
import { ResourceClient } from '../base/resource_client.js';
|
|
5
5
|
import * as schemas from '../schemas.js';
|
|
6
6
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
7
|
-
import { anyObjectSchema,
|
|
7
|
+
import { anyObjectSchema, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
|
|
8
8
|
import { startWaitingForResources } from '../wait_for_resources.js';
|
|
9
9
|
import { ActorServerClient } from './actor_server.js';
|
|
10
10
|
import { ActorVersionClient } from './actor_version.js';
|
|
@@ -196,8 +196,8 @@ export class ActorClient extends ResourceClient {
|
|
|
196
196
|
'content-type': parsed.contentType,
|
|
197
197
|
};
|
|
198
198
|
}
|
|
199
|
-
// A
|
|
200
|
-
const response = await startWaitingForResources(async () => this.httpClient.call(request),
|
|
199
|
+
// A stream input is consumed by the first attempt, so a retry would start the run with an empty input.
|
|
200
|
+
const response = await startWaitingForResources(async () => this.httpClient.call(request), isAnyStream(input) ? false : waitForResources, this.httpClient.logger, signal);
|
|
201
201
|
return parseResponse(response, schemas.Run());
|
|
202
202
|
}
|
|
203
203
|
/**
|
|
@@ -84,7 +84,7 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
84
84
|
* @param options.params - Query parameters of the request, converted the same way as for API calls.
|
|
85
85
|
* @param options.headers - Additional headers of the request.
|
|
86
86
|
* @param options.data - Request body, serialized the same way as for API calls: a plain object or array is sent
|
|
87
|
-
* as JSON, and a string
|
|
87
|
+
* as JSON, and a string, binary value or stream (`Readable`, web `ReadableStream`) as it is.
|
|
88
88
|
* @param options.parentRequestId - The `X-Actor-Request-ID` header of the request your Server Actor is handling,
|
|
89
89
|
* sent on as the same header so the called Actor charges at that request's pricing tier.
|
|
90
90
|
* @param options.compression - Compression algorithm for the request body, as a name or an {@link HttpCompressor}.
|
|
@@ -209,15 +209,17 @@ export declare class KeyValueStoreClient extends ResourceClient {
|
|
|
209
209
|
* A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
|
|
210
210
|
* to be valid JSON already, or {@link getRecord} fails to parse it back.
|
|
211
211
|
*
|
|
212
|
-
* **Note about streams:** If the value is a stream
|
|
213
|
-
* the
|
|
214
|
-
* pass a `Blob` from `fs.openAsBlob()`
|
|
215
|
-
* in memory whole.
|
|
212
|
+
* **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
|
|
213
|
+
* such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
|
|
214
|
+
* on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
|
|
215
|
+
* instead: it is read again for every attempt and never held in memory whole. A browser sends a web
|
|
216
|
+
* `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
|
|
217
|
+
* where it doesn't, the call throws a `TypeError`.
|
|
216
218
|
*
|
|
217
219
|
* @param record - The record to store
|
|
218
220
|
* @param record.key - Record key (unique identifier)
|
|
219
|
-
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
220
|
-
* Readable)
|
|
221
|
+
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
222
|
+
* Readable, or web ReadableStream)
|
|
221
223
|
* @param record.contentType - Optional MIME type. Auto-detected if not provided:
|
|
222
224
|
* - Objects: `'application/json; charset=utf-8'`
|
|
223
225
|
* - Strings: `'text/plain; charset=utf-8'`
|
|
@@ -352,10 +354,10 @@ export interface KeyValueClientGetRecordOptions extends TimeoutOptions {
|
|
|
352
354
|
* A value that `setRecord` accepts.
|
|
353
355
|
*
|
|
354
356
|
* Anything JSON-serializable, or binary content the client uploads as bytes instead of JSON-encoding
|
|
355
|
-
* it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`,
|
|
356
|
-
* `Uint8Array`, so `TypedArray` covers it.
|
|
357
|
+
* it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, a Node.js `Readable`, or a web `ReadableStream`.
|
|
358
|
+
* `Buffer` is a `Uint8Array`, so `TypedArray` covers it.
|
|
357
359
|
*/
|
|
358
|
-
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable
|
|
360
|
+
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable | ReadableStream<Uint8Array>;
|
|
359
361
|
/**
|
|
360
362
|
* Represents a record (key-value pair) in a Key-Value Store.
|
|
361
363
|
*
|
|
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
|
|
|
5
5
|
import * as schemas from '../schemas.js';
|
|
6
6
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
7
7
|
import { runtime } from '#runtime';
|
|
8
|
-
import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBlob, isBuffer,
|
|
8
|
+
import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isAnyStream, isBlob, isBuffer, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
|
|
9
9
|
const listKeysOptionsSchema = z.strictObject({
|
|
10
10
|
limit: z.number().min(0).optional(),
|
|
11
11
|
chunkSize: z.number().positive().optional(),
|
|
@@ -361,15 +361,17 @@ export class KeyValueStoreClient extends ResourceClient {
|
|
|
361
361
|
* A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
|
|
362
362
|
* to be valid JSON already, or {@link getRecord} fails to parse it back.
|
|
363
363
|
*
|
|
364
|
-
* **Note about streams:** If the value is a stream
|
|
365
|
-
* the
|
|
366
|
-
* pass a `Blob` from `fs.openAsBlob()`
|
|
367
|
-
* in memory whole.
|
|
364
|
+
* **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
|
|
365
|
+
* such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
|
|
366
|
+
* on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
|
|
367
|
+
* instead: it is read again for every attempt and never held in memory whole. A browser sends a web
|
|
368
|
+
* `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
|
|
369
|
+
* where it doesn't, the call throws a `TypeError`.
|
|
368
370
|
*
|
|
369
371
|
* @param record - The record to store
|
|
370
372
|
* @param record.key - Record key (unique identifier)
|
|
371
|
-
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
372
|
-
* Readable)
|
|
373
|
+
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
374
|
+
* Readable, or web ReadableStream)
|
|
373
375
|
* @param record.contentType - Optional MIME type. Auto-detected if not provided:
|
|
374
376
|
* - Objects: `'application/json; charset=utf-8'`
|
|
375
377
|
* - Strings: `'text/plain; charset=utf-8'`
|
|
@@ -436,12 +438,7 @@ export class KeyValueStoreClient extends ResourceClient {
|
|
|
436
438
|
if (contentEncoding !== undefined && !runtime.isNode) {
|
|
437
439
|
throw new Error('The contentEncoding option can only be used in Node.js environment.');
|
|
438
440
|
}
|
|
439
|
-
|
|
440
|
-
if (isWebStream(value)) {
|
|
441
|
-
throw new TypeError('A web ReadableStream cannot be stored as a record value. ' +
|
|
442
|
-
'Convert it with Readable.fromWeb() in Node.js, or read it into bytes first.');
|
|
443
|
-
}
|
|
444
|
-
const isBinaryValue = isStream(value) || isBuffer(value) || isBlob(value);
|
|
441
|
+
const isBinaryValue = isAnyStream(value) || isBuffer(value) || isBlob(value);
|
|
445
442
|
// The client forwards the header without inspecting the body, so a string or a value serialized to JSON, which
|
|
446
443
|
// cannot hold compressed bytes, would be stored under an encoding that misdescribes it.
|
|
447
444
|
const declaresCompression = contentEncoding !== undefined && contentEncoding.trim().toLowerCase() !== 'identity';
|
|
@@ -3,7 +3,7 @@ import { ACT_JOB_STATUSES, META_ORIGINS } from '@apify/consts';
|
|
|
3
3
|
import { ResourceClient } from '../base/resource_client.js';
|
|
4
4
|
import * as schemas from '../schemas.js';
|
|
5
5
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
6
|
-
import { anyObjectSchema, cast,
|
|
6
|
+
import { anyObjectSchema, cast, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64, } from '../utils.js';
|
|
7
7
|
import { startWaitingForResources } from '../wait_for_resources.js';
|
|
8
8
|
import { RunClient } from './run.js';
|
|
9
9
|
import { RunCollectionClient } from './run_collection.js';
|
|
@@ -186,8 +186,8 @@ export class TaskClient extends ResourceClient {
|
|
|
186
186
|
timeoutSecs: this.timeoutForWaitForFinish(timeoutSecs, 'medium', waitForFinish),
|
|
187
187
|
signal,
|
|
188
188
|
};
|
|
189
|
-
// A
|
|
190
|
-
const response = await startWaitingForResources(async () => this.httpClient.call(request),
|
|
189
|
+
// A stream input is consumed by the first attempt, so a retry would start the run with an empty input.
|
|
190
|
+
const response = await startWaitingForResources(async () => this.httpClient.call(request), isAnyStream(input) ? false : waitForResources, this.httpClient.logger, signal);
|
|
191
191
|
return parseResponse(response, schemas.Run());
|
|
192
192
|
}
|
|
193
193
|
/**
|
package/dist/runtime/node.js
CHANGED
|
@@ -78,6 +78,9 @@ export const runtime = {
|
|
|
78
78
|
openBlobBody(blob, onSourceError) {
|
|
79
79
|
return Readable.from(readBlob(blob, onSourceError), { objectMode: false });
|
|
80
80
|
},
|
|
81
|
+
openStreamBody(stream) {
|
|
82
|
+
return Readable.fromWeb(stream);
|
|
83
|
+
},
|
|
81
84
|
};
|
|
82
85
|
/**
|
|
83
86
|
* Yields the bytes of a blob. Ending the iteration early, which destroying the `Readable` around it does, cancels
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -72,4 +72,11 @@ export interface Runtime {
|
|
|
72
72
|
* which `fetch` and `XMLHttpRequest` read on their own, and never calls `onSourceError`.
|
|
73
73
|
*/
|
|
74
74
|
openBlobBody(blob: Blob, onSourceError: (error: unknown) => void): Readable | Blob;
|
|
75
|
+
/**
|
|
76
|
+
* Opens a web `ReadableStream` request body. The Node.js implementation wraps it in a `Readable`, the one
|
|
77
|
+
* stream type every Node.js transport sends. The Web API one returns the stream itself, and throws a
|
|
78
|
+
* `TypeError` where `fetch` cannot send a stream body: such a browser would send the text
|
|
79
|
+
* `[object ReadableStream]` instead.
|
|
80
|
+
*/
|
|
81
|
+
openStreamBody(stream: ReadableStream<Uint8Array>): Readable | ReadableStream<Uint8Array>;
|
|
75
82
|
}
|
package/dist/runtime/web.js
CHANGED
|
@@ -26,4 +26,35 @@ export const runtime = {
|
|
|
26
26
|
openBlobBody(blob) {
|
|
27
27
|
return blob;
|
|
28
28
|
},
|
|
29
|
+
openStreamBody(stream) {
|
|
30
|
+
if (!canSendStreamBody()) {
|
|
31
|
+
throw new TypeError('This runtime cannot send a ReadableStream as a request body. ' +
|
|
32
|
+
'Read it into a Blob or bytes first, for example with `await new Response(stream).blob()`.');
|
|
33
|
+
}
|
|
34
|
+
return stream;
|
|
35
|
+
},
|
|
29
36
|
};
|
|
37
|
+
/**
|
|
38
|
+
* Whether `fetch` sends a `ReadableStream` body as a stream. A runtime that does not, such as Firefox and Safari,
|
|
39
|
+
* never reads the `duplex` option and sends the stream converted to a string, under a text content type.
|
|
40
|
+
*/
|
|
41
|
+
function canSendStreamBody() {
|
|
42
|
+
// Cloudflare Workers, Deno and Bun stream such a body too, without ever reading `duplex`.
|
|
43
|
+
if (/^(Cloudflare-Workers$|Deno\/|Bun\/)/.test(globalThis.navigator?.userAgent ?? ''))
|
|
44
|
+
return true;
|
|
45
|
+
let duplexRead = false;
|
|
46
|
+
try {
|
|
47
|
+
const request = new Request('https://api.apify.com', {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
body: new ReadableStream(),
|
|
50
|
+
get duplex() {
|
|
51
|
+
duplexRead = true;
|
|
52
|
+
return 'half';
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
return duplexRead && !request.headers.has('content-type');
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
package/dist/utils.d.ts
CHANGED
|
@@ -106,10 +106,15 @@ export declare function isBuffer(value: unknown): value is Buffer | ArrayBuffer
|
|
|
106
106
|
*/
|
|
107
107
|
export declare function isBlob(value: unknown): value is Blob;
|
|
108
108
|
/**
|
|
109
|
-
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response
|
|
109
|
+
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response and may pass
|
|
110
|
+
* on as a request body.
|
|
110
111
|
*/
|
|
111
112
|
export declare function isWebStream(value: unknown): value is ReadableStream<Uint8Array>;
|
|
112
113
|
export declare function isStream(value: unknown): value is Readable;
|
|
114
|
+
/**
|
|
115
|
+
* Whether a value is a stream of either kind, which a request can send only once.
|
|
116
|
+
*/
|
|
117
|
+
export declare function isAnyStream(value: unknown): value is Readable | ReadableStream<Uint8Array>;
|
|
113
118
|
/**
|
|
114
119
|
* Helper class to create async iterators from paginated list endpoints.
|
|
115
120
|
*/
|
package/dist/utils.js
CHANGED
|
@@ -247,7 +247,8 @@ function isTagged(value, tag) {
|
|
|
247
247
|
return Object.prototype.toString.call(value) === `[object ${tag}]`;
|
|
248
248
|
}
|
|
249
249
|
/**
|
|
250
|
-
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response
|
|
250
|
+
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response and may pass
|
|
251
|
+
* on as a request body.
|
|
251
252
|
*/
|
|
252
253
|
export function isWebStream(value) {
|
|
253
254
|
return isTagged(value, 'ReadableStream');
|
|
@@ -258,6 +259,12 @@ export function isStream(value) {
|
|
|
258
259
|
const { on, pipe } = value;
|
|
259
260
|
return typeof on === 'function' && typeof pipe === 'function';
|
|
260
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Whether a value is a stream of either kind, which a request can send only once.
|
|
264
|
+
*/
|
|
265
|
+
export function isAnyStream(value) {
|
|
266
|
+
return isStream(value) || isWebStream(value);
|
|
267
|
+
}
|
|
261
268
|
/**
|
|
262
269
|
* Helper class to create async iterators from paginated list endpoints.
|
|
263
270
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apify-client",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.116",
|
|
4
4
|
"description": "Apify API client for JavaScript",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.15.0"
|
|
@@ -101,6 +101,7 @@
|
|
|
101
101
|
"compression": "^1.8.2",
|
|
102
102
|
"esbuild": "0.28.2",
|
|
103
103
|
"express": "^5.3.0",
|
|
104
|
+
"miniflare": "4.20260730.0",
|
|
104
105
|
"oxfmt": "0.80.0",
|
|
105
106
|
"oxlint": "1.93.0",
|
|
106
107
|
"oxlint-tsgolint": "7.0.2007",
|