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,34 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import { EventManager, EventType } from '@crawlee/core';
|
|
2
3
|
import { WebSocket } from 'ws';
|
|
3
4
|
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES } from '@apify/consts';
|
|
4
5
|
import { betterClearInterval } from '@apify/utilities';
|
|
5
6
|
import { Configuration } from './configuration.js';
|
|
7
|
+
/**
|
|
8
|
+
* WebSocket close codes for a permanent condition, on which the connection is not re-established.
|
|
9
|
+
*
|
|
10
|
+
* The platform sends `1008` (policy violation) for an unknown/missing run ID or an exceeded per-run connection limit.
|
|
11
|
+
* The rest are protocol, data, or mandatory-extension failures that reconnecting cannot resolve.
|
|
12
|
+
*/
|
|
13
|
+
const NON_RETRYABLE_CLOSE_CODES = new Set([1002, 1003, 1007, 1008, 1010]);
|
|
14
|
+
/** Close codes of a clean close, as opposed to a lost connection. */
|
|
15
|
+
const CLEAN_CLOSE_CODES = new Set([1000, 1001]);
|
|
16
|
+
/** How long a connection must stay open to count as healthy, after which a drop reconnects without backoff. */
|
|
17
|
+
const HEALTHY_CONNECTION_MIN_DURATION_MILLIS = 1000;
|
|
18
|
+
/**
|
|
19
|
+
* Delays between reconnection attempts, mirroring the Python `websockets` library
|
|
20
|
+
* (see RFC 6455, section 7.2.3): a random initial delay, then exponential growth up to a cap.
|
|
21
|
+
*/
|
|
22
|
+
function* backoffDelays() {
|
|
23
|
+
yield Math.random() * 5000;
|
|
24
|
+
let delay = 3100;
|
|
25
|
+
while (delay < 90_000) {
|
|
26
|
+
yield delay;
|
|
27
|
+
delay *= 1.618;
|
|
28
|
+
}
|
|
29
|
+
while (true)
|
|
30
|
+
yield 90_000;
|
|
31
|
+
}
|
|
6
32
|
/**
|
|
7
33
|
* Gets an instance of a Node.js'
|
|
8
34
|
* [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
|
@@ -40,63 +66,73 @@ import { Configuration } from './configuration.js';
|
|
|
40
66
|
* in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
|
|
41
67
|
* Note that the `persistState` event is provided merely for user convenience,
|
|
42
68
|
* you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
|
|
69
|
+
*
|
|
70
|
+
* The connection to the platform events websocket is re-established after it drops, unless it was closed
|
|
71
|
+
* with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
|
|
43
72
|
*/
|
|
44
73
|
export class PlatformEventManager extends EventManager {
|
|
45
|
-
|
|
74
|
+
configuration;
|
|
46
75
|
/** Websocket connection to Actor events. */
|
|
47
|
-
eventsWs;
|
|
48
|
-
|
|
76
|
+
#eventsWs;
|
|
77
|
+
/** Aborted by `close()`, which stops any pending reconnection and marks the final close as intentional. */
|
|
78
|
+
#abortController = new AbortController();
|
|
79
|
+
/** Backoff for rapid reconnections; reset after a connection that stayed open long enough to count as healthy. */
|
|
80
|
+
#backoff;
|
|
81
|
+
#internalListeners;
|
|
82
|
+
/** Calls of the internal listeners that are still in progress. */
|
|
83
|
+
#internalListenerCalls = new Set();
|
|
84
|
+
/**
|
|
85
|
+
* @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
|
|
86
|
+
* user code can neither remove them with `off()` nor see them in `listeners()`.
|
|
87
|
+
*/
|
|
88
|
+
constructor(configuration = Configuration.getGlobalConfiguration(), internalListeners = {}) {
|
|
49
89
|
super({
|
|
50
|
-
persistStateIntervalMillis:
|
|
90
|
+
persistStateIntervalMillis: configuration.persistStateIntervalMillis,
|
|
51
91
|
});
|
|
52
|
-
this.
|
|
92
|
+
this.configuration = configuration;
|
|
93
|
+
this.#internalListeners = internalListeners;
|
|
94
|
+
}
|
|
95
|
+
emit(event, ...args) {
|
|
96
|
+
super.emit(event, ...args);
|
|
97
|
+
const listener = this.#internalListeners[event];
|
|
98
|
+
if (!listener)
|
|
99
|
+
return;
|
|
100
|
+
const call = (async () => listener(...args))()
|
|
101
|
+
.catch((err) => this.log.exception(err, `Internal listener of the "${event}" event failed`))
|
|
102
|
+
.finally(() => this.#internalListenerCalls.delete(call));
|
|
103
|
+
this.#internalListenerCalls.add(call);
|
|
104
|
+
}
|
|
105
|
+
async waitForAllListenersToComplete() {
|
|
106
|
+
const [completed] = await Promise.all([super.waitForAllListenersToComplete(), ...this.#internalListenerCalls]);
|
|
107
|
+
return completed;
|
|
53
108
|
}
|
|
54
109
|
/**
|
|
55
110
|
* Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
|
|
56
111
|
* This is an internal function that is automatically called by `Actor.main()`.
|
|
112
|
+
*
|
|
113
|
+
* Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
|
|
57
114
|
*/
|
|
58
115
|
async init() {
|
|
59
116
|
if (this.initialized) {
|
|
60
117
|
return;
|
|
61
118
|
}
|
|
62
119
|
await super.init();
|
|
63
|
-
const eventsWsUrl = this.
|
|
120
|
+
const eventsWsUrl = this.configuration.actorEventsWsUrl;
|
|
64
121
|
// Locally there is no web socket to connect, so just print a log message.
|
|
65
122
|
if (!eventsWsUrl) {
|
|
66
123
|
this.log.debug(`Environment variable ${ACTOR_ENV_VARS.EVENTS_WEBSOCKET_URL} is not set, no events from Apify platform will be emitted.`);
|
|
67
124
|
return;
|
|
68
125
|
}
|
|
69
|
-
this
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (name === ACTOR_EVENT_NAMES.MIGRATING) {
|
|
80
|
-
betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
|
|
81
|
-
this.events.emit("persistState" /* EventType.PERSIST_STATE */, {
|
|
82
|
-
isMigrating: true,
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
catch (err) {
|
|
87
|
-
this.log.exception(err, 'Cannot parse Actor event');
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
this.eventsWs.on('error', (err) => {
|
|
91
|
-
// Don't print this error as this happens in the case of very short Actor.main().
|
|
92
|
-
if (err.message === 'WebSocket was closed before the connection was established')
|
|
93
|
-
return;
|
|
94
|
-
this.log.exception(err, 'web socket connection failed');
|
|
95
|
-
});
|
|
96
|
-
this.eventsWs.on('close', () => {
|
|
97
|
-
this.log.debug('web socket has been closed');
|
|
98
|
-
this.eventsWs = undefined;
|
|
99
|
-
});
|
|
126
|
+
this.#abortController = new AbortController();
|
|
127
|
+
this.#backoff = undefined;
|
|
128
|
+
try {
|
|
129
|
+
await this.#connect(eventsWsUrl);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
// Leave no `persistState` interval behind, so that `init()` can be retried.
|
|
133
|
+
await this.close();
|
|
134
|
+
throw new Error('Error connecting to platform events websocket!', { cause: err });
|
|
135
|
+
}
|
|
100
136
|
}
|
|
101
137
|
/**
|
|
102
138
|
* Closes websocket providing events from Actor infrastructure and also stops sending internal events
|
|
@@ -108,6 +144,116 @@ export class PlatformEventManager extends EventManager {
|
|
|
108
144
|
return;
|
|
109
145
|
}
|
|
110
146
|
await super.close();
|
|
111
|
-
this.
|
|
147
|
+
this.#abortController.abort();
|
|
148
|
+
this.#eventsWs?.close();
|
|
149
|
+
}
|
|
150
|
+
/** Opens a new connection; resolves once it is established and rejects if it fails before that. */
|
|
151
|
+
async #connect(eventsWsUrl) {
|
|
152
|
+
await new Promise((resolve, reject) => {
|
|
153
|
+
// `ws` has no default handshake timeout, so without it a silent server would block `init()` forever.
|
|
154
|
+
const ws = new WebSocket(eventsWsUrl, { handshakeTimeout: 10_000 });
|
|
155
|
+
this.#eventsWs = ws;
|
|
156
|
+
let openedAt;
|
|
157
|
+
let lastError;
|
|
158
|
+
ws.on('open', () => {
|
|
159
|
+
openedAt = Date.now();
|
|
160
|
+
resolve();
|
|
161
|
+
});
|
|
162
|
+
ws.on('message', (message) => this.#handleMessage(message));
|
|
163
|
+
ws.on('error', (err) => {
|
|
164
|
+
// Before the connection is open, the error is reported through the `close` event.
|
|
165
|
+
lastError = err;
|
|
166
|
+
if (openedAt !== undefined)
|
|
167
|
+
this.log.exception(err, 'Platform events websocket error');
|
|
168
|
+
});
|
|
169
|
+
ws.on('close', (code, reason) => {
|
|
170
|
+
if (this.#eventsWs === ws)
|
|
171
|
+
this.#eventsWs = undefined;
|
|
172
|
+
if (openedAt === undefined) {
|
|
173
|
+
reject(lastError ??
|
|
174
|
+
new Error(`Web socket closed before the connection was established (code=${code})`));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.#handleClose(eventsWsUrl, { code, reason: reason.toString(), openedAt });
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
#handleMessage(message) {
|
|
182
|
+
if (!message)
|
|
183
|
+
return;
|
|
184
|
+
try {
|
|
185
|
+
const { name, data } = JSON.parse(String(message));
|
|
186
|
+
this.emit(name, data);
|
|
187
|
+
if (name === ACTOR_EVENT_NAMES.MIGRATING) {
|
|
188
|
+
betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
|
|
189
|
+
this.events.emit(EventType.PERSIST_STATE, {
|
|
190
|
+
isMigrating: true,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
this.log.exception(err, 'Cannot parse Actor event');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Logs the close of an established connection and schedules a reconnection, unless the close is final. */
|
|
199
|
+
#handleClose(eventsWsUrl, { code, reason, openedAt }) {
|
|
200
|
+
if (this.#abortController.signal.aborted) {
|
|
201
|
+
this.log.debug('web socket has been closed');
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const details = `code=${code}, reason=${JSON.stringify(reason)}`;
|
|
205
|
+
if (NON_RETRYABLE_CLOSE_CODES.has(code)) {
|
|
206
|
+
this.log.error(`Connection to platform events websocket was closed with a non-retryable code (${details}); not reconnecting. ` +
|
|
207
|
+
'No further platform events will be received for the rest of this run, so migration and abort handling ' +
|
|
208
|
+
'(e.g. persisting state before a migration) is now disabled.');
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (CLEAN_CLOSE_CODES.has(code)) {
|
|
212
|
+
this.log.info(`Connection to platform events websocket was closed (${details}), reconnecting...`);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
this.log.warning(`Connection to platform events websocket was lost (${details}), reconnecting...`);
|
|
216
|
+
}
|
|
217
|
+
// Reconnect a healthy connection immediately; back off only on repeated rapid drops. The first rapid drop
|
|
218
|
+
// retries without delay (it just primes the backoff), each consecutive one waits for the next interval.
|
|
219
|
+
let delay = 0;
|
|
220
|
+
if (Date.now() - openedAt >= HEALTHY_CONNECTION_MIN_DURATION_MILLIS) {
|
|
221
|
+
this.#backoff = undefined;
|
|
222
|
+
}
|
|
223
|
+
else if (this.#backoff) {
|
|
224
|
+
delay = this.#backoff.next().value;
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
this.#backoff = backoffDelays();
|
|
228
|
+
}
|
|
229
|
+
this.#reconnect(eventsWsUrl, delay).catch((err) => {
|
|
230
|
+
this.log.exception(err, 'Reconnecting to platform events websocket failed');
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
/** Keeps trying to connect, with backoff between failed attempts, until it succeeds or `close()` is called. */
|
|
234
|
+
async #reconnect(eventsWsUrl, initialDelayMillis) {
|
|
235
|
+
const { signal } = this.#abortController;
|
|
236
|
+
await this.#sleep(initialDelayMillis, signal);
|
|
237
|
+
while (!signal.aborted) {
|
|
238
|
+
try {
|
|
239
|
+
await this.#connect(eventsWsUrl);
|
|
240
|
+
this.log.info('Reconnected to the platform events websocket.');
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
if (signal.aborted)
|
|
245
|
+
return;
|
|
246
|
+
this.log.warning(`Reconnecting to platform events websocket failed: ${err.message}`);
|
|
247
|
+
}
|
|
248
|
+
this.#backoff ??= backoffDelays();
|
|
249
|
+
await this.#sleep(this.#backoff.next().value, signal);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** Sleeps for the given time, or until the signal is aborted. */
|
|
253
|
+
async #sleep(millis, signal) {
|
|
254
|
+
if (millis <= 0 || signal.aborted)
|
|
255
|
+
return;
|
|
256
|
+
// Rejects with an `AbortError` when aborted, which just means there is nothing left to wait for.
|
|
257
|
+
await sleep(millis, undefined, { signal }).catch(() => { });
|
|
112
258
|
}
|
|
113
259
|
}
|
|
@@ -2,7 +2,12 @@ import type { ProxyConfigurationOptions as CoreProxyConfigurationOptions } from
|
|
|
2
2
|
import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
|
|
3
3
|
import type { ProxyInfo as CoreProxyInfo } from '@crawlee/types';
|
|
4
4
|
import { Configuration } from './configuration.js';
|
|
5
|
-
|
|
5
|
+
/** Response of the Apify Proxy status endpoint (`proxy.apify.com/?format=json`). */
|
|
6
|
+
interface ProxyStatus {
|
|
7
|
+
connected: boolean;
|
|
8
|
+
connectionError: string;
|
|
9
|
+
isManInTheMiddle: boolean;
|
|
10
|
+
}
|
|
6
11
|
export interface ProxyConfigurationOptions extends CoreProxyConfigurationOptions {
|
|
7
12
|
/**
|
|
8
13
|
* User's password for the proxy. By default, it is taken from the `APIFY_PROXY_PASSWORD`
|
|
@@ -145,18 +150,13 @@ export interface ProxyInfo extends CoreProxyInfo {
|
|
|
145
150
|
* @category Scaling
|
|
146
151
|
*/
|
|
147
152
|
export declare class ProxyConfiguration extends CoreProxyConfiguration {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
private subdivisionCode?;
|
|
152
|
-
private password?;
|
|
153
|
-
private hostname;
|
|
154
|
-
private port?;
|
|
155
|
-
private usesApifyProxy?;
|
|
153
|
+
#private;
|
|
154
|
+
readonly configuration: Configuration;
|
|
155
|
+
protected readonly log: import("@crawlee/core").Log;
|
|
156
156
|
/**
|
|
157
157
|
* @internal
|
|
158
158
|
*/
|
|
159
|
-
constructor(options?: ProxyConfigurationOptions,
|
|
159
|
+
constructor(options?: ProxyConfigurationOptions, configuration?: Configuration);
|
|
160
160
|
/**
|
|
161
161
|
* Loads proxy password if token is provided and checks access to Apify Proxy and provided proxy groups
|
|
162
162
|
* if Apify Proxy configuration is used.
|
|
@@ -172,41 +172,51 @@ export declare class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
172
172
|
* Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
|
|
173
173
|
* independent URL; for Apify Proxy a random session id is embedded so consecutive
|
|
174
174
|
* calls resolve to different IPs.
|
|
175
|
+
*
|
|
176
|
+
* A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
|
|
177
|
+
* Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
|
|
178
|
+
* username and with it the proxy session.
|
|
175
179
|
*/
|
|
176
|
-
newProxyInfo(
|
|
180
|
+
newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
|
|
177
181
|
/**
|
|
178
182
|
* Returns a new proxy URL. For Apify Proxy, each call generates a URL with a fresh
|
|
179
183
|
* random session id, so consecutive calls return independent URLs. For custom
|
|
180
184
|
* `proxyUrls`, the URLs are rotated round-robin.
|
|
181
185
|
*/
|
|
182
|
-
newUrl(
|
|
186
|
+
newUrl(): Promise<string | undefined>;
|
|
183
187
|
/**
|
|
184
188
|
* Returns proxy username.
|
|
185
189
|
*/
|
|
186
|
-
protected
|
|
190
|
+
protected getUsername(sessionId: string): string;
|
|
187
191
|
protected composeDefaultUrl(sessionId: string): string;
|
|
192
|
+
private composeUrl;
|
|
188
193
|
/**
|
|
189
194
|
* Fetch & set the proxy password from Apify API if an Apify token is provided.
|
|
190
195
|
*/
|
|
191
|
-
|
|
196
|
+
private setPasswordIfToken;
|
|
192
197
|
/**
|
|
193
198
|
* Checks whether the user has access to the proxies specified in the provided ProxyConfigurationOptions.
|
|
194
199
|
* If the check can not be made, it only prints a warning and allows the program to continue. This is to
|
|
195
200
|
* prevent program crashes caused by short downtimes of Proxy.
|
|
196
201
|
*/
|
|
197
|
-
protected
|
|
202
|
+
protected checkAccess(): Promise<boolean>;
|
|
198
203
|
/**
|
|
199
204
|
* Apify Proxy can be down for a second or a minute, but this should not crash processes.
|
|
200
205
|
*/
|
|
201
|
-
protected
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
+
protected fetchStatus(): Promise<ProxyStatus | undefined>;
|
|
207
|
+
/**
|
|
208
|
+
* Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
|
|
209
|
+
* response reports on this exact connection (auth + man-in-the-middle).
|
|
210
|
+
*
|
|
211
|
+
* Uses a native `node:http` forward-proxy request — an absolute request URL
|
|
212
|
+
* plus a `Proxy-Authorization` header — so no proxy-agent dependency is
|
|
213
|
+
* needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
|
|
214
|
+
*/
|
|
215
|
+
protected requestStatus(statusUrl: string, proxyUrl: string): Promise<ProxyStatus>;
|
|
206
216
|
/**
|
|
207
217
|
* Throws cannot combine custom proxies with Apify Proxy
|
|
208
218
|
* @internal
|
|
209
219
|
*/
|
|
210
|
-
protected
|
|
220
|
+
protected throwCannotCombineCustomWithApify(): void;
|
|
211
221
|
}
|
|
212
222
|
export {};
|