apify 4.0.0-beta.13 → 4.0.0-beta.131
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 +24 -2
- package/dist/actor.d.ts +391 -279
- package/dist/actor.js +732 -415
- package/dist/apify_dataset_backend.d.ts +19 -0
- package/dist/apify_dataset_backend.js +77 -0
- package/dist/apify_file_system_storage_backend.d.ts +34 -0
- package/dist/apify_file_system_storage_backend.js +41 -0
- package/dist/apify_key_value_store_backend.d.ts +23 -0
- package/dist/apify_key_value_store_backend.js +56 -0
- package/dist/apify_request_queue_backend.d.ts +78 -0
- package/dist/apify_request_queue_backend.js +114 -0
- package/dist/apify_request_queue_shared_backend.d.ts +31 -0
- package/dist/apify_request_queue_shared_backend.js +193 -0
- package/dist/apify_request_queue_single_backend.d.ts +43 -0
- package/dist/apify_request_queue_single_backend.js +256 -0
- package/dist/apify_storage_backend.d.ts +90 -0
- package/dist/apify_storage_backend.js +210 -0
- package/dist/charging.d.ts +69 -46
- package/dist/charging.js +326 -208
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +109 -0
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +49 -28
- package/dist/configuration.js +67 -12
- package/dist/enqueue_links_filters.d.ts +29 -0
- package/dist/enqueue_links_filters.js +52 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +22 -0
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +11 -4
- package/dist/index.js +8 -3
- package/dist/input-schemas.d.ts +1 -1
- package/dist/platform_event_manager.d.ts +15 -5
- package/dist/platform_event_manager.js +185 -39
- package/dist/proxy_configuration.d.ts +31 -21
- package/dist/proxy_configuration.js +136 -79
- package/dist/smart_apify_storage_backend.d.ts +52 -0
- package/dist/smart_apify_storage_backend.js +73 -0
- package/dist/storage.d.ts +6 -26
- package/dist/storage.js +1 -79
- package/dist/utils.d.ts +28 -3
- package/dist/utils.js +59 -17
- package/package.json +38 -44
- package/dist/apify_storage_client.d.ts +0 -54
- package/dist/apify_storage_client.js +0 -152
- package/dist/key_value_store.d.ts +0 -21
- package/dist/key_value_store.js +0 -41
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { json } from 'node:stream/consumers';
|
|
1
4
|
import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
|
|
2
|
-
import {
|
|
3
|
-
import ow from 'ow';
|
|
5
|
+
import { z } from 'zod';
|
|
4
6
|
import { APIFY_ENV_VARS, APIFY_PROXY_VALUE_REGEX } from '@apify/consts';
|
|
7
|
+
import defaultLog from '@apify/log';
|
|
5
8
|
import { cryptoRandomObjectId } from '@apify/utilities';
|
|
9
|
+
import { parseArgument } from '@apify/validations';
|
|
6
10
|
import { Actor } from './actor.js';
|
|
7
11
|
import { Configuration } from './configuration.js';
|
|
8
12
|
const CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS = 4_000;
|
|
@@ -14,6 +18,7 @@ const SUBDIVISION_CODE_REGEX = /^[A-Z0-9]{1,3}$/;
|
|
|
14
18
|
// users; a fresh one is minted for every URL the SDK hands out so that the
|
|
15
19
|
// returned proxy URLs are independent.
|
|
16
20
|
const SESSION_ID_LENGTH = 12;
|
|
21
|
+
const SESSION_USERNAME_REGEX = /(?:^|,)session-[^,]+/;
|
|
17
22
|
/**
|
|
18
23
|
* Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
|
|
19
24
|
* your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
|
|
@@ -48,40 +53,45 @@ const SESSION_ID_LENGTH = 12;
|
|
|
48
53
|
* @category Scaling
|
|
49
54
|
*/
|
|
50
55
|
export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
51
|
-
|
|
52
|
-
groups;
|
|
53
|
-
countryCode;
|
|
54
|
-
subdivisionCode;
|
|
55
|
-
password;
|
|
56
|
-
hostname;
|
|
57
|
-
port;
|
|
58
|
-
usesApifyProxy;
|
|
56
|
+
configuration;
|
|
57
|
+
#groups;
|
|
58
|
+
#countryCode;
|
|
59
|
+
#subdivisionCode;
|
|
60
|
+
#password;
|
|
61
|
+
#hostname;
|
|
62
|
+
#port;
|
|
63
|
+
#usesApifyProxy;
|
|
64
|
+
#checkAccess;
|
|
65
|
+
log = defaultLog.child({ prefix: 'ProxyConfiguration' });
|
|
59
66
|
/**
|
|
60
67
|
* @internal
|
|
61
68
|
*/
|
|
62
|
-
constructor(options = {},
|
|
69
|
+
constructor(options = {}, configuration = Configuration.getGlobalConfiguration()) {
|
|
63
70
|
const { proxyUrls, newUrlFunction, ...rest } = options;
|
|
64
71
|
super({
|
|
65
72
|
proxyUrls,
|
|
66
73
|
newUrlFunction,
|
|
67
74
|
['validateRequired']: false,
|
|
68
75
|
});
|
|
69
|
-
this.
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
76
|
+
this.configuration = configuration;
|
|
77
|
+
parseArgument(rest, z
|
|
78
|
+
.object({
|
|
79
|
+
groups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
|
|
80
|
+
apifyProxyGroups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
|
|
81
|
+
countryCode: z.string().regex(COUNTRY_CODE_REGEX).optional(),
|
|
82
|
+
apifyProxyCountry: z.string().regex(COUNTRY_CODE_REGEX).optional(),
|
|
83
|
+
subdivisionCode: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
|
|
84
|
+
apifyProxySubdivision: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
|
|
85
|
+
password: z.string().optional(),
|
|
86
|
+
checkAccess: z.boolean().optional(),
|
|
87
|
+
})
|
|
88
|
+
.strict());
|
|
89
|
+
const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = configuration.proxyPassword, } = options;
|
|
80
90
|
const groupsToUse = groups.length ? groups : apifyProxyGroups;
|
|
81
91
|
const countryCodeToUse = countryCode || apifyProxyCountry;
|
|
82
92
|
const subdivisionCodeToUse = subdivisionCode || apifyProxySubdivision;
|
|
83
|
-
const hostname =
|
|
84
|
-
const port =
|
|
93
|
+
const hostname = configuration.proxyHostname;
|
|
94
|
+
const port = configuration.proxyPort;
|
|
85
95
|
// The Apify Proxy subdivision is expressed as part of the country
|
|
86
96
|
// username parameter (`country-US_CA`), so a country is required.
|
|
87
97
|
if (subdivisionCodeToUse && !countryCodeToUse) {
|
|
@@ -89,17 +99,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
89
99
|
}
|
|
90
100
|
// Validation
|
|
91
101
|
if ((proxyUrls || newUrlFunction) && (groupsToUse.length || countryCodeToUse || subdivisionCodeToUse)) {
|
|
92
|
-
this.
|
|
102
|
+
this.throwCannotCombineCustomWithApify();
|
|
93
103
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
this
|
|
97
|
-
this
|
|
98
|
-
this
|
|
99
|
-
this
|
|
100
|
-
this
|
|
101
|
-
this
|
|
102
|
-
this.usesApifyProxy = !this.proxyUrls && !this.newUrlFunction;
|
|
104
|
+
this.#groups = groupsToUse;
|
|
105
|
+
this.#countryCode = countryCodeToUse;
|
|
106
|
+
this.#subdivisionCode = subdivisionCodeToUse;
|
|
107
|
+
this.#password = password;
|
|
108
|
+
this.#hostname = hostname;
|
|
109
|
+
this.#port = port;
|
|
110
|
+
this.#usesApifyProxy = !proxyUrls && !newUrlFunction;
|
|
111
|
+
this.#checkAccess = options.checkAccess;
|
|
103
112
|
if (proxyUrls && proxyUrls.some((url) => url?.includes('apify.com'))) {
|
|
104
113
|
this.log.warning('Some Apify proxy features may work incorrectly. Please consider setting up Apify properties instead of `proxyUrls`.\n' +
|
|
105
114
|
'See https://docs.apify.com/sdk/js/docs/concepts/proxy-management#apify-proxy-configuration');
|
|
@@ -114,11 +123,11 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
114
123
|
* `ProxyConfiguration` instance instead of calling this manually.
|
|
115
124
|
*/
|
|
116
125
|
async initialize(options) {
|
|
117
|
-
if (this
|
|
118
|
-
if (!this
|
|
119
|
-
await this.
|
|
126
|
+
if (this.#usesApifyProxy) {
|
|
127
|
+
if (!this.#password) {
|
|
128
|
+
await this.setPasswordIfToken();
|
|
120
129
|
}
|
|
121
|
-
if (!this
|
|
130
|
+
if (!this.#password) {
|
|
122
131
|
if (Actor.isAtHome()) {
|
|
123
132
|
throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
|
|
124
133
|
`You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
|
|
@@ -129,10 +138,11 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
129
138
|
`provide options.password or "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
|
|
130
139
|
`You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
|
|
131
140
|
`so that the SDK can fetch the proxy password from Apify API, when ${APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
|
|
141
|
+
return false;
|
|
132
142
|
}
|
|
133
143
|
}
|
|
134
|
-
if (options?.checkAccess !== false) {
|
|
135
|
-
return this.
|
|
144
|
+
if ((options?.checkAccess ?? this.#checkAccess) !== false) {
|
|
145
|
+
return this.checkAccess();
|
|
136
146
|
}
|
|
137
147
|
}
|
|
138
148
|
return true;
|
|
@@ -141,9 +151,18 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
141
151
|
* Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
|
|
142
152
|
* independent URL; for Apify Proxy a random session id is embedded so consecutive
|
|
143
153
|
* calls resolve to different IPs.
|
|
154
|
+
*
|
|
155
|
+
* A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
|
|
156
|
+
* Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
|
|
157
|
+
* username and with it the proxy session.
|
|
144
158
|
*/
|
|
145
|
-
async newProxyInfo(
|
|
146
|
-
|
|
159
|
+
async newProxyInfo(proxyInfo) {
|
|
160
|
+
// Only Apify Proxy infos carry `groups` and a proxy session in the username.
|
|
161
|
+
if (proxyInfo &&
|
|
162
|
+
!(this.#usesApifyProxy && 'groups' in proxyInfo && SESSION_USERNAME_REGEX.test(proxyInfo.username ?? ''))) {
|
|
163
|
+
return proxyInfo;
|
|
164
|
+
}
|
|
165
|
+
const url = proxyInfo?.username ? this.composeUrl(proxyInfo.username) : await this.newUrl();
|
|
147
166
|
if (!url)
|
|
148
167
|
return undefined;
|
|
149
168
|
const parsed = new URL(url);
|
|
@@ -154,12 +173,15 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
154
173
|
hostname: parsed.hostname,
|
|
155
174
|
port: parsed.port,
|
|
156
175
|
};
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
176
|
+
// A refreshed info keeps its own groups/country, which match its username rather than this config.
|
|
177
|
+
if (proxyInfo)
|
|
178
|
+
return { ...proxyInfo, ...result };
|
|
179
|
+
if (this.#usesApifyProxy) {
|
|
180
|
+
result.groups = this.#groups;
|
|
181
|
+
if (this.#countryCode !== undefined)
|
|
182
|
+
result.countryCode = this.#countryCode;
|
|
183
|
+
if (this.#subdivisionCode !== undefined)
|
|
184
|
+
result.subdivisionCode = this.#subdivisionCode;
|
|
163
185
|
}
|
|
164
186
|
return result;
|
|
165
187
|
}
|
|
@@ -168,49 +190,49 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
168
190
|
* random session id, so consecutive calls return independent URLs. For custom
|
|
169
191
|
* `proxyUrls`, the URLs are rotated round-robin.
|
|
170
192
|
*/
|
|
171
|
-
async newUrl(
|
|
172
|
-
if (this
|
|
173
|
-
return super.newUrl(
|
|
193
|
+
async newUrl() {
|
|
194
|
+
if (!this.#usesApifyProxy) {
|
|
195
|
+
return super.newUrl();
|
|
174
196
|
}
|
|
175
197
|
return this.composeDefaultUrl(cryptoRandomObjectId(SESSION_ID_LENGTH));
|
|
176
198
|
}
|
|
177
199
|
/**
|
|
178
200
|
* Returns proxy username.
|
|
179
201
|
*/
|
|
180
|
-
|
|
181
|
-
const { groups, countryCode, subdivisionCode } = this;
|
|
202
|
+
getUsername(sessionId) {
|
|
182
203
|
const parts = [];
|
|
183
|
-
if (groups && groups.length) {
|
|
184
|
-
parts.push(`groups-${groups.join('+')}`);
|
|
204
|
+
if (this.#groups && this.#groups.length) {
|
|
205
|
+
parts.push(`groups-${this.#groups.join('+')}`);
|
|
185
206
|
}
|
|
186
207
|
parts.push(`session-${sessionId}`);
|
|
187
|
-
if (subdivisionCode) {
|
|
188
|
-
parts.push(`country-${countryCode}_${subdivisionCode}`);
|
|
208
|
+
if (this.#subdivisionCode) {
|
|
209
|
+
parts.push(`country-${this.#countryCode}_${this.#subdivisionCode}`);
|
|
189
210
|
}
|
|
190
|
-
else if (countryCode) {
|
|
191
|
-
parts.push(`country-${countryCode}`);
|
|
211
|
+
else if (this.#countryCode) {
|
|
212
|
+
parts.push(`country-${this.#countryCode}`);
|
|
192
213
|
}
|
|
193
214
|
return parts.join(',');
|
|
194
215
|
}
|
|
195
216
|
composeDefaultUrl(sessionId) {
|
|
196
|
-
|
|
197
|
-
|
|
217
|
+
return this.composeUrl(this.getUsername(sessionId));
|
|
218
|
+
}
|
|
219
|
+
composeUrl(username) {
|
|
220
|
+
const url = new URL(`http://${this.#hostname}:${this.#port}`);
|
|
198
221
|
url.username = `${username}`;
|
|
199
|
-
url.password = `${this
|
|
222
|
+
url.password = `${this.#password}`;
|
|
200
223
|
const urlString = url.toString();
|
|
201
224
|
return urlString.substring(0, urlString.length - 1);
|
|
202
225
|
}
|
|
203
226
|
/**
|
|
204
227
|
* Fetch & set the proxy password from Apify API if an Apify token is provided.
|
|
205
228
|
*/
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
const { token } = this.config;
|
|
229
|
+
async setPasswordIfToken() {
|
|
230
|
+
const { token } = this.configuration;
|
|
209
231
|
if (!token)
|
|
210
232
|
return;
|
|
211
233
|
try {
|
|
212
234
|
const user = await Actor.apifyClient.user().get();
|
|
213
|
-
this
|
|
235
|
+
this.#password = user?.proxy?.password ?? undefined;
|
|
214
236
|
}
|
|
215
237
|
catch (error) {
|
|
216
238
|
if (Actor.isAtHome()) {
|
|
@@ -228,14 +250,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
228
250
|
* If the check can not be made, it only prints a warning and allows the program to continue. This is to
|
|
229
251
|
* prevent program crashes caused by short downtimes of Proxy.
|
|
230
252
|
*/
|
|
231
|
-
async
|
|
232
|
-
const status = await this.
|
|
253
|
+
async checkAccess() {
|
|
254
|
+
const status = await this.fetchStatus();
|
|
233
255
|
if (!status) {
|
|
234
256
|
this.log.warning('Apify Proxy access check timed out. Watch out for errors with status code 407. ' +
|
|
235
257
|
"If you see some, it most likely means you don't have access to either all or some of the proxies you're trying to use.");
|
|
236
258
|
return true;
|
|
237
259
|
}
|
|
238
260
|
const { connected, connectionError, isManInTheMiddle } = status;
|
|
261
|
+
// Declared `readonly false` on the base class; the status check is the one place that
|
|
262
|
+
// learns the actual value, so bypass the readonly marker.
|
|
239
263
|
this.isManInTheMiddle = isManInTheMiddle;
|
|
240
264
|
if (connected) {
|
|
241
265
|
return true;
|
|
@@ -252,18 +276,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
252
276
|
/**
|
|
253
277
|
* Apify Proxy can be down for a second or a minute, but this should not crash processes.
|
|
254
278
|
*/
|
|
255
|
-
async
|
|
256
|
-
const { proxyStatusUrl } = this.
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
};
|
|
279
|
+
async fetchStatus() {
|
|
280
|
+
const { proxyStatusUrl } = this.configuration;
|
|
281
|
+
const statusUrl = `${proxyStatusUrl}/?format=json`;
|
|
282
|
+
const proxyUrl = await this.newUrl();
|
|
283
|
+
// Without a proxy URL we can't perform the (proxied) status check.
|
|
284
|
+
if (!proxyUrl)
|
|
285
|
+
return undefined;
|
|
263
286
|
for (let attempt = 1; attempt <= CHECK_ACCESS_MAX_ATTEMPTS; attempt++) {
|
|
264
287
|
try {
|
|
265
|
-
|
|
266
|
-
return response.body;
|
|
288
|
+
return await this.requestStatus(statusUrl, proxyUrl);
|
|
267
289
|
}
|
|
268
290
|
catch {
|
|
269
291
|
// retry connection errors
|
|
@@ -271,11 +293,46 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
271
293
|
}
|
|
272
294
|
return undefined;
|
|
273
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
|
|
298
|
+
* response reports on this exact connection (auth + man-in-the-middle).
|
|
299
|
+
*
|
|
300
|
+
* Uses a native `node:http` forward-proxy request — an absolute request URL
|
|
301
|
+
* plus a `Proxy-Authorization` header — so no proxy-agent dependency is
|
|
302
|
+
* needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
|
|
303
|
+
*/
|
|
304
|
+
async requestStatus(statusUrl, proxyUrl) {
|
|
305
|
+
const target = new URL(statusUrl);
|
|
306
|
+
const proxy = new URL(proxyUrl);
|
|
307
|
+
const headers = { host: target.host };
|
|
308
|
+
if (proxy.username) {
|
|
309
|
+
const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
|
|
310
|
+
headers['proxy-authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`;
|
|
311
|
+
}
|
|
312
|
+
const request = httpRequest({
|
|
313
|
+
host: proxy.hostname,
|
|
314
|
+
port: proxy.port,
|
|
315
|
+
// Absolute-form request URI tells the proxy to forward the request.
|
|
316
|
+
path: target.href,
|
|
317
|
+
headers,
|
|
318
|
+
signal: AbortSignal.timeout(CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS),
|
|
319
|
+
});
|
|
320
|
+
request.end();
|
|
321
|
+
// `once` rejects if the request emits `error` first (connection refused,
|
|
322
|
+
// timeout/abort), so failures propagate to the retry loop in `fetchStatus`.
|
|
323
|
+
const [response] = (await once(request, 'response'));
|
|
324
|
+
const statusCode = response.statusCode ?? 0;
|
|
325
|
+
if (statusCode < 200 || statusCode >= 300) {
|
|
326
|
+
response.resume(); // drain so the socket can be freed
|
|
327
|
+
throw new Error(`Apify Proxy status check responded with status code ${statusCode}.`);
|
|
328
|
+
}
|
|
329
|
+
return (await json(response));
|
|
330
|
+
}
|
|
274
331
|
/**
|
|
275
332
|
* Throws cannot combine custom proxies with Apify Proxy
|
|
276
333
|
* @internal
|
|
277
334
|
*/
|
|
278
|
-
|
|
335
|
+
throwCannotCombineCustomWithApify() {
|
|
279
336
|
throw new Error('Cannot combine custom proxies with Apify Proxy! ' +
|
|
280
337
|
'It is not allowed to set "options.proxyUrls" or "options.newUrlFunction" combined with ' +
|
|
281
338
|
'"options.groups", "options.apifyProxyGroups", "options.countryCode", "options.apifyProxyCountry", ' +
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { DatasetBackend, KeyValueStoreBackend, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
|
|
2
|
+
import type { StorageType } from './apify_storage_backend.js';
|
|
3
|
+
import type { Configuration } from './configuration.js';
|
|
4
|
+
import type { OpenStorageOptions } from './storage.js';
|
|
5
|
+
export interface SmartApifyStorageBackendOptions {
|
|
6
|
+
/** Used on the Apify platform, and locally for `forceCloud` storages. */
|
|
7
|
+
cloudStorageBackend: StorageBackend;
|
|
8
|
+
/** Used outside of the Apify platform, except for `forceCloud` storages. */
|
|
9
|
+
localStorageBackend: StorageBackend;
|
|
10
|
+
/** Supplies `isAtHome` and the token that cloud storage needs. */
|
|
11
|
+
configuration: Configuration;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
|
|
15
|
+
*
|
|
16
|
+
* On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
|
|
17
|
+
* opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
|
|
18
|
+
* asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
|
|
19
|
+
* backend to `Actor.init({ storage })` instead.
|
|
20
|
+
*
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
export declare class SmartApifyStorageBackend implements StorageBackend {
|
|
24
|
+
#private;
|
|
25
|
+
constructor(options: SmartApifyStorageBackendOptions);
|
|
26
|
+
/**
|
|
27
|
+
* The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
|
|
28
|
+
* the local one otherwise.
|
|
29
|
+
*
|
|
30
|
+
* Exposed so that `forceCloud` storages can be opened through the very same cloud backend
|
|
31
|
+
* instance this one delegates to — two instances would resolve run-scoped aliases to two
|
|
32
|
+
* separate storages.
|
|
33
|
+
*/
|
|
34
|
+
getSuitableStorageBackend(options?: OpenStorageOptions): StorageBackend;
|
|
35
|
+
get stats(): {
|
|
36
|
+
rateLimitErrors: number[];
|
|
37
|
+
} | undefined;
|
|
38
|
+
/** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
|
|
39
|
+
getStorageBackendCacheKey(): string;
|
|
40
|
+
createDatasetBackend(options?: StorageIdentifier): Promise<DatasetBackend>;
|
|
41
|
+
createKeyValueStoreBackend(options?: StorageIdentifier): Promise<KeyValueStoreBackend>;
|
|
42
|
+
createRequestQueueBackend(options?: StorageIdentifier): Promise<RequestQueueBackend>;
|
|
43
|
+
/**
|
|
44
|
+
* Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
|
|
45
|
+
* the presence of the three methods below, and delegating to a backend that lacks one is
|
|
46
|
+
* indistinguishable from not having it — a `false` from `storageExists` means the same as its
|
|
47
|
+
* absence (crawlee falls through to a name lookup), and the other two have no return value.
|
|
48
|
+
*/
|
|
49
|
+
storageExists(id: string, type: StorageType): Promise<boolean>;
|
|
50
|
+
purge(): Promise<void>;
|
|
51
|
+
teardown(): Promise<void>;
|
|
52
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
|
|
3
|
+
*
|
|
4
|
+
* On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
|
|
5
|
+
* opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
|
|
6
|
+
* asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
|
|
7
|
+
* backend to `Actor.init({ storage })` instead.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
export class SmartApifyStorageBackend {
|
|
12
|
+
#cloudStorageBackend;
|
|
13
|
+
#localStorageBackend;
|
|
14
|
+
#configuration;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.#cloudStorageBackend = options.cloudStorageBackend;
|
|
17
|
+
this.#localStorageBackend = options.localStorageBackend;
|
|
18
|
+
this.#configuration = options.configuration;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
|
|
22
|
+
* the local one otherwise.
|
|
23
|
+
*
|
|
24
|
+
* Exposed so that `forceCloud` storages can be opened through the very same cloud backend
|
|
25
|
+
* instance this one delegates to — two instances would resolve run-scoped aliases to two
|
|
26
|
+
* separate storages.
|
|
27
|
+
*/
|
|
28
|
+
getSuitableStorageBackend(options = {}) {
|
|
29
|
+
if (this.#configuration.isAtHome) {
|
|
30
|
+
return this.#cloudStorageBackend;
|
|
31
|
+
}
|
|
32
|
+
if (!options.forceCloud) {
|
|
33
|
+
return this.#localStorageBackend;
|
|
34
|
+
}
|
|
35
|
+
if (!this.#configuration.token) {
|
|
36
|
+
throw new Error('In order to use the Apify cloud storage from your computer, you need to provide an Apify token ' +
|
|
37
|
+
'using the APIFY_TOKEN environment variable.');
|
|
38
|
+
}
|
|
39
|
+
return this.#cloudStorageBackend;
|
|
40
|
+
}
|
|
41
|
+
get stats() {
|
|
42
|
+
return this.getSuitableStorageBackend().stats;
|
|
43
|
+
}
|
|
44
|
+
/** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
|
|
45
|
+
getStorageBackendCacheKey() {
|
|
46
|
+
const backend = this.getSuitableStorageBackend();
|
|
47
|
+
return backend.getStorageBackendCacheKey?.() ?? backend.constructor.name;
|
|
48
|
+
}
|
|
49
|
+
async createDatasetBackend(options) {
|
|
50
|
+
return await this.getSuitableStorageBackend().createDatasetBackend(options);
|
|
51
|
+
}
|
|
52
|
+
async createKeyValueStoreBackend(options) {
|
|
53
|
+
return await this.getSuitableStorageBackend().createKeyValueStoreBackend(options);
|
|
54
|
+
}
|
|
55
|
+
async createRequestQueueBackend(options) {
|
|
56
|
+
return await this.getSuitableStorageBackend().createRequestQueueBackend(options);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
|
|
60
|
+
* the presence of the three methods below, and delegating to a backend that lacks one is
|
|
61
|
+
* indistinguishable from not having it — a `false` from `storageExists` means the same as its
|
|
62
|
+
* absence (crawlee falls through to a name lookup), and the other two have no return value.
|
|
63
|
+
*/
|
|
64
|
+
async storageExists(id, type) {
|
|
65
|
+
return (await this.getSuitableStorageBackend().storageExists?.(id, type)) ?? false;
|
|
66
|
+
}
|
|
67
|
+
async purge() {
|
|
68
|
+
await this.getSuitableStorageBackend().purge?.();
|
|
69
|
+
}
|
|
70
|
+
async teardown() {
|
|
71
|
+
await this.getSuitableStorageBackend().teardown?.();
|
|
72
|
+
}
|
|
73
|
+
}
|
package/dist/storage.d.ts
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import type { Constructor, IStorage, StorageOpenOptions } from '@crawlee/core';
|
|
2
|
-
import type { StorageClient } from '@crawlee/types';
|
|
3
|
-
import type { Configuration } from './configuration.js';
|
|
4
1
|
export interface OpenStorageOptions {
|
|
5
2
|
/**
|
|
6
3
|
* If set to `true` then the cloud storage is used even if the `CRAWLEE_STORAGE_DIR`
|
|
@@ -10,8 +7,11 @@ export interface OpenStorageOptions {
|
|
|
10
7
|
forceCloud?: boolean;
|
|
11
8
|
}
|
|
12
9
|
/**
|
|
13
|
-
* Identifies a storage by its alias
|
|
14
|
-
*
|
|
10
|
+
* Identifies a run-scoped storage by its alias.
|
|
11
|
+
*
|
|
12
|
+
* An alias declared in the Actor's schema storages (the `ACTOR_STORAGES_JSON` environment variable)
|
|
13
|
+
* resolves to the storage the platform created for it; any other alias gets an unnamed storage of
|
|
14
|
+
* its own, for this run only.
|
|
15
15
|
*/
|
|
16
16
|
export interface StorageAlias {
|
|
17
17
|
alias: string;
|
|
@@ -31,28 +31,8 @@ export interface StorageName {
|
|
|
31
31
|
/**
|
|
32
32
|
* Identifies a storage to open. Can be:
|
|
33
33
|
* - A plain `string` for backward compatibility (treated as ID or name)
|
|
34
|
-
* - `{ alias: string }` to
|
|
34
|
+
* - `{ alias: string }` to open a run-scoped storage — see {@link StorageAlias}
|
|
35
35
|
* - `{ id: string }` to open by explicit platform ID
|
|
36
36
|
* - `{ name: string }` to open by explicit name
|
|
37
37
|
*/
|
|
38
38
|
export type StorageIdentifier = string | StorageAlias | StorageId | StorageName;
|
|
39
|
-
/**
|
|
40
|
-
* Identifies a storage to open, without alias support.
|
|
41
|
-
* Used for key-value stores and request queues, which do not support aliases.
|
|
42
|
-
* Can be:
|
|
43
|
-
* - A plain `string` for backward compatibility (treated as ID or name)
|
|
44
|
-
* - `{ id: string }` to open by explicit platform ID
|
|
45
|
-
* - `{ name: string }` to open by explicit name
|
|
46
|
-
*/
|
|
47
|
-
export type StorageIdentifierWithoutAlias = string | StorageId | StorageName;
|
|
48
|
-
export interface OpenStorageContext {
|
|
49
|
-
config: Configuration;
|
|
50
|
-
client?: StorageClient;
|
|
51
|
-
purgedStorageAliases: Set<string>;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Opens a storage by its identifier, handling Apify alias resolution and local purging.
|
|
55
|
-
*/
|
|
56
|
-
export declare function openStorage<T extends IStorage>(storageClass: Constructor<T> & {
|
|
57
|
-
open(id?: string | null, options?: StorageOpenOptions): Promise<T>;
|
|
58
|
-
}, identifier: StorageIdentifier | null | undefined, context: OpenStorageContext): Promise<T>;
|
package/dist/storage.js
CHANGED
|
@@ -1,79 +1 @@
|
|
|
1
|
-
|
|
2
|
-
const STORAGE_TYPE_KEYS = {
|
|
3
|
-
Dataset: 'datasets',
|
|
4
|
-
KeyValueStore: 'keyValueStores',
|
|
5
|
-
RequestQueue: 'requestQueues',
|
|
6
|
-
};
|
|
7
|
-
const parsedStoragesJson = new Map();
|
|
8
|
-
/**
|
|
9
|
-
* Resolves a {@link StorageIdentifier} to a plain string ID or name
|
|
10
|
-
* that can be passed to crawlee v4's `<Storage>.open()`.
|
|
11
|
-
*/
|
|
12
|
-
function resolveStorageIdentifier(storageType, identifier, config) {
|
|
13
|
-
if (identifier === null || identifier === undefined) {
|
|
14
|
-
return undefined;
|
|
15
|
-
}
|
|
16
|
-
if (typeof identifier === 'string') {
|
|
17
|
-
return identifier;
|
|
18
|
-
}
|
|
19
|
-
if ('id' in identifier) {
|
|
20
|
-
return identifier.id;
|
|
21
|
-
}
|
|
22
|
-
if ('name' in identifier) {
|
|
23
|
-
return identifier.name;
|
|
24
|
-
}
|
|
25
|
-
// { alias: string }
|
|
26
|
-
const storagesJson = config.actorStoragesJson;
|
|
27
|
-
if (config.isAtHome && storagesJson) {
|
|
28
|
-
let storages;
|
|
29
|
-
try {
|
|
30
|
-
if (!parsedStoragesJson.has(storagesJson)) {
|
|
31
|
-
parsedStoragesJson.set(storagesJson, JSON.parse(storagesJson));
|
|
32
|
-
}
|
|
33
|
-
storages = parsedStoragesJson.get(storagesJson);
|
|
34
|
-
}
|
|
35
|
-
catch {
|
|
36
|
-
throw new Error(`Failed to parse ACTOR_STORAGES_JSON environment variable: ${storagesJson}`);
|
|
37
|
-
}
|
|
38
|
-
const typeKey = STORAGE_TYPE_KEYS[storageType];
|
|
39
|
-
const resolvedId = storages[typeKey]?.[identifier.alias];
|
|
40
|
-
if (resolvedId) {
|
|
41
|
-
return resolvedId;
|
|
42
|
-
}
|
|
43
|
-
throw new Error(`Storage alias "${identifier.alias}" not found in ACTOR_STORAGES_JSON for storage type "${storageType}". ` +
|
|
44
|
-
`Available aliases: ${Object.keys(storages[typeKey] ?? {}).join(', ') || '(none)'}`);
|
|
45
|
-
}
|
|
46
|
-
// When using local storage, just use the alias as a name.
|
|
47
|
-
// When using platform storage, we can't just make up a name — the alias must be
|
|
48
|
-
// in ACTOR_STORAGES_JSON.
|
|
49
|
-
if (config.isAtHome) {
|
|
50
|
-
throw new Error(`Storage alias "${identifier.alias}" cannot be resolved because ACTOR_STORAGES_JSON is not set. ` +
|
|
51
|
-
`Aliases are only available for storages declared in the Actor's schema.`);
|
|
52
|
-
}
|
|
53
|
-
return identifier.alias;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Opens a storage by its identifier, handling Apify alias resolution and local purging.
|
|
57
|
-
*/
|
|
58
|
-
export async function openStorage(storageClass, identifier, context) {
|
|
59
|
-
const isAlias = identifier !== null && identifier !== undefined && typeof identifier === 'object' && 'alias' in identifier;
|
|
60
|
-
if (isAlias && !context.config.isAtHome && context.client instanceof ApifyStorageClient) {
|
|
61
|
-
throw new Error('The `alias` option is not allowed for Apify-based storages running outside of Apify');
|
|
62
|
-
}
|
|
63
|
-
const resolvedIdOrName = resolveStorageIdentifier(storageClass.name, identifier, context.config);
|
|
64
|
-
// When running locally, purge aliased storages on first open
|
|
65
|
-
// (similar to how crawlee purges default storages on start).
|
|
66
|
-
if (isAlias &&
|
|
67
|
-
!context.config.isAtHome &&
|
|
68
|
-
context.config.purgeOnStart &&
|
|
69
|
-
!context.purgedStorageAliases.has(identifier.alias)) {
|
|
70
|
-
context.purgedStorageAliases.add(identifier.alias);
|
|
71
|
-
const existingStorage = await storageClass.open(resolvedIdOrName ?? null, {
|
|
72
|
-
storageClient: context.client,
|
|
73
|
-
});
|
|
74
|
-
await existingStorage.drop();
|
|
75
|
-
}
|
|
76
|
-
return storageClass.open(resolvedIdOrName ?? null, {
|
|
77
|
-
storageClient: context.client,
|
|
78
|
-
});
|
|
79
|
-
}
|
|
1
|
+
export {};
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
export { ArgumentValidationError } from '@apify/validations';
|
|
2
|
+
/**
|
|
3
|
+
* Returns `true` for a plain, non-empty object (not `null`, not an array).
|
|
4
|
+
* Mirrors the `ow.object.nonEmpty` predicate the SDK used previously.
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
export declare function isNonEmptyObject(value: unknown): value is Record<string, unknown>;
|
|
8
|
+
/** Content type of a JSON record, as `KeyValueStore` and the file-system adoption write it. */
|
|
9
|
+
export declare const JSON_CONTENT_TYPE = "application/json; charset=utf-8";
|
|
10
|
+
/** Content type of raw bytes, which is what a local input file without an extension is adopted as. */
|
|
11
|
+
export declare const BINARY_CONTENT_TYPE = "application/octet-stream";
|
|
12
|
+
/**
|
|
13
|
+
* Parses a raw input record the way `KeyValueStore.getValue` would, with one exception:
|
|
14
|
+
* `application/octet-stream` — the type a local input file without an extension is adopted as — is
|
|
15
|
+
* tried as JSON5 first, so such a file still yields an object. Bytes that do not parse come back as they are.
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export declare function parseInputValue(value: Buffer | ArrayBuffer, contentType: string | null): unknown;
|
|
19
|
+
/**
|
|
20
|
+
* Converts a `SNAKE_CASE` string to `camelCase` (previously provided by `@crawlee/utils`).
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
export declare function snakeCaseToCamelCase(snakeCaseStr: string): string;
|
|
1
24
|
/**
|
|
2
25
|
* Gets info about system, node version and apify package version.
|
|
3
26
|
* @internal
|
|
@@ -14,7 +37,9 @@ export declare function getSystemInfo(): {
|
|
|
14
37
|
*/
|
|
15
38
|
export declare function checkCrawleeVersion(): void;
|
|
16
39
|
/**
|
|
17
|
-
*
|
|
18
|
-
* @ignore
|
|
40
|
+
* A FIFO mutex that a critical section may re-enter from a nested call without deadlocking.
|
|
19
41
|
*/
|
|
20
|
-
export declare
|
|
42
|
+
export declare class ReentrantAsyncLock {
|
|
43
|
+
#private;
|
|
44
|
+
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
|
|
45
|
+
}
|