apify 4.0.0-beta.14 → 4.0.0-beta.141

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.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +393 -281
  3. package/dist/actor.js +734 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +81 -0
  11. package/dist/apify_request_queue_backend.js +110 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +69 -47
  19. package/dist/charging.js +321 -223
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +67 -13
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +31 -21
  38. package/dist/proxy_configuration.js +136 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
@@ -1,8 +1,41 @@
1
- import { EventManager } from '@crawlee/core';
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
+ /** Names of the platform events that are emitted to listeners. Messages with any other name are dropped. */
19
+ const PLATFORM_EVENT_NAMES = new Set([
20
+ ACTOR_EVENT_NAMES.SYSTEM_INFO,
21
+ ACTOR_EVENT_NAMES.MIGRATING,
22
+ ACTOR_EVENT_NAMES.ABORTING,
23
+ ACTOR_EVENT_NAMES.PERSIST_STATE,
24
+ ]);
25
+ /**
26
+ * Delays between reconnection attempts, mirroring the Python `websockets` library
27
+ * (see RFC 6455, section 7.2.3): a random initial delay, then exponential growth up to a cap.
28
+ */
29
+ function* backoffDelays() {
30
+ yield Math.random() * 5000;
31
+ let delay = 3100;
32
+ while (delay < 90_000) {
33
+ yield delay;
34
+ delay *= 1.618;
35
+ }
36
+ while (true)
37
+ yield 90_000;
38
+ }
6
39
  /**
7
40
  * Gets an instance of a Node.js'
8
41
  * [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
@@ -12,16 +45,16 @@ import { Configuration } from './configuration.js';
12
45
  * **Example usage:**
13
46
  *
14
47
  * ```javascript
15
- * Actor.on('cpuInfo', (data) => {
48
+ * Actor.on('systemInfo', (data) => {
16
49
  * if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');
17
50
  * });
18
51
  * ```
19
52
  *
20
53
  * The following events are emitted:
21
54
  *
22
- * - `cpuInfo`: `{ "isCpuOverloaded": Boolean }`
23
- * The event is emitted approximately every second
24
- * and it indicates whether the Actor is using the maximum of available CPU resources.
55
+ * - `systemInfo`: `{ "cpuCurrentUsage": Number, "isCpuOverloaded": Boolean, "memCurrentBytes": Number, ... }`
56
+ * The event is emitted approximately every second and it describes the CPU and memory usage of the Actor.
57
+ * `isCpuOverloaded` indicates whether the Actor is using the maximum of available CPU resources.
25
58
  * If that's the case, the Actor should not add more workload.
26
59
  * For example, this event is used by the {@link AutoscaledPool} class.
27
60
  * - `migrating`: `void`
@@ -40,63 +73,84 @@ import { Configuration } from './configuration.js';
40
73
  * in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
41
74
  * Note that the `persistState` event is provided merely for user convenience,
42
75
  * you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
76
+ *
77
+ * Messages with any other name are not emitted. This includes the deprecated `cpuInfo` event, which the platform
78
+ * sends next to `systemInfo` for backward compatibility. Registering a `cpuInfo` listener logs a warning.
79
+ * Unknown names are logged at the debug level.
80
+ *
81
+ * The connection to the platform events websocket is re-established after it drops, unless it was closed
82
+ * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
43
83
  */
44
84
  export class PlatformEventManager extends EventManager {
45
- config;
85
+ configuration;
46
86
  /** Websocket connection to Actor events. */
47
- eventsWs;
48
- constructor(config = Configuration.getGlobalConfig()) {
87
+ #eventsWs;
88
+ /** Aborted by `close()`, which stops any pending reconnection and marks the final close as intentional. */
89
+ #abortController = new AbortController();
90
+ /** Backoff for rapid reconnections; reset after a connection that stayed open long enough to count as healthy. */
91
+ #backoff;
92
+ #internalListeners;
93
+ /** Calls of the internal listeners that are still in progress. */
94
+ #internalListenerCalls = new Set();
95
+ /**
96
+ * @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
97
+ * user code can neither remove them with `off()` nor see them in `listeners()`.
98
+ */
99
+ constructor(configuration = Configuration.getGlobalConfiguration(), internalListeners = {}) {
49
100
  super({
50
- persistStateIntervalMillis: config.persistStateIntervalMillis,
101
+ persistStateIntervalMillis: configuration.persistStateIntervalMillis,
51
102
  });
52
- this.config = config;
103
+ this.configuration = configuration;
104
+ this.#internalListeners = internalListeners;
105
+ }
106
+ on(event, listener) {
107
+ if (event === ACTOR_EVENT_NAMES.CPU_INFO) {
108
+ this.log.warning('The "cpuInfo" event is deprecated and never emitted. ' +
109
+ 'Listen to "systemInfo" instead, which has the same "isCpuOverloaded" field.');
110
+ }
111
+ super.on(event, listener);
112
+ }
113
+ emit(event, ...args) {
114
+ super.emit(event, ...args);
115
+ const listener = this.#internalListeners[event];
116
+ if (!listener)
117
+ return;
118
+ const call = (async () => listener(...args))()
119
+ .catch((err) => this.log.exception(err, `Internal listener of the "${event}" event failed`))
120
+ .finally(() => this.#internalListenerCalls.delete(call));
121
+ this.#internalListenerCalls.add(call);
122
+ }
123
+ async waitForAllListenersToComplete() {
124
+ const [completed] = await Promise.all([super.waitForAllListenersToComplete(), ...this.#internalListenerCalls]);
125
+ return completed;
53
126
  }
54
127
  /**
55
128
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
56
129
  * This is an internal function that is automatically called by `Actor.main()`.
130
+ *
131
+ * Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
57
132
  */
58
133
  async init() {
59
134
  if (this.initialized) {
60
135
  return;
61
136
  }
62
137
  await super.init();
63
- const eventsWsUrl = this.config.actorEventsWsUrl;
138
+ const eventsWsUrl = this.configuration.actorEventsWsUrl;
64
139
  // Locally there is no web socket to connect, so just print a log message.
65
140
  if (!eventsWsUrl) {
66
141
  this.log.debug(`Environment variable ${ACTOR_ENV_VARS.EVENTS_WEBSOCKET_URL} is not set, no events from Apify platform will be emitted.`);
67
142
  return;
68
143
  }
69
- this.createWebSocketConnection(eventsWsUrl);
70
- }
71
- createWebSocketConnection(eventsWsUrl) {
72
- this.eventsWs = new WebSocket(eventsWsUrl);
73
- this.eventsWs.on('message', (message) => {
74
- if (!message)
75
- return;
76
- try {
77
- const { name, data } = JSON.parse(String(message));
78
- this.events.emit(name, data);
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
- });
144
+ this.#abortController = new AbortController();
145
+ this.#backoff = undefined;
146
+ try {
147
+ await this.#connect(eventsWsUrl);
148
+ }
149
+ catch (err) {
150
+ // Leave no `persistState` interval behind, so that `init()` can be retried.
151
+ await this.close();
152
+ throw new Error('Error connecting to platform events websocket!', { cause: err });
153
+ }
100
154
  }
101
155
  /**
102
156
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
@@ -108,6 +162,122 @@ export class PlatformEventManager extends EventManager {
108
162
  return;
109
163
  }
110
164
  await super.close();
111
- this.eventsWs?.close();
165
+ this.#abortController.abort();
166
+ this.#eventsWs?.close();
167
+ }
168
+ /** Opens a new connection; resolves once it is established and rejects if it fails before that. */
169
+ async #connect(eventsWsUrl) {
170
+ await new Promise((resolve, reject) => {
171
+ // `ws` has no default handshake timeout, so without it a silent server would block `init()` forever.
172
+ const ws = new WebSocket(eventsWsUrl, { handshakeTimeout: 10_000 });
173
+ this.#eventsWs = ws;
174
+ let openedAt;
175
+ let lastError;
176
+ ws.on('open', () => {
177
+ openedAt = Date.now();
178
+ resolve();
179
+ });
180
+ ws.on('message', (message) => this.#handleMessage(message));
181
+ ws.on('error', (err) => {
182
+ // Before the connection is open, the error is reported through the `close` event.
183
+ lastError = err;
184
+ if (openedAt !== undefined)
185
+ this.log.exception(err, 'Platform events websocket error');
186
+ });
187
+ ws.on('close', (code, reason) => {
188
+ if (this.#eventsWs === ws)
189
+ this.#eventsWs = undefined;
190
+ if (openedAt === undefined) {
191
+ reject(lastError ??
192
+ new Error(`Web socket closed before the connection was established (code=${code})`));
193
+ return;
194
+ }
195
+ this.#handleClose(eventsWsUrl, { code, reason: reason.toString(), openedAt });
196
+ });
197
+ });
198
+ }
199
+ #handleMessage(message) {
200
+ if (!message)
201
+ return;
202
+ try {
203
+ const { name, data } = JSON.parse(String(message));
204
+ if (name === ACTOR_EVENT_NAMES.CPU_INFO)
205
+ return;
206
+ if (!PLATFORM_EVENT_NAMES.has(name)) {
207
+ this.log.debug('Unknown platform event received', { name, data });
208
+ return;
209
+ }
210
+ this.emit(name, data);
211
+ if (name === ACTOR_EVENT_NAMES.MIGRATING) {
212
+ betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
213
+ this.events.emit(EventType.PERSIST_STATE, {
214
+ isMigrating: true,
215
+ });
216
+ }
217
+ }
218
+ catch (err) {
219
+ this.log.exception(err, 'Cannot parse Actor event');
220
+ }
221
+ }
222
+ /** Logs the close of an established connection and schedules a reconnection, unless the close is final. */
223
+ #handleClose(eventsWsUrl, { code, reason, openedAt }) {
224
+ if (this.#abortController.signal.aborted) {
225
+ this.log.debug('web socket has been closed');
226
+ return;
227
+ }
228
+ const details = `code=${code}, reason=${JSON.stringify(reason)}`;
229
+ if (NON_RETRYABLE_CLOSE_CODES.has(code)) {
230
+ this.log.error(`Connection to platform events websocket was closed with a non-retryable code (${details}); not reconnecting. ` +
231
+ 'No further platform events will be received for the rest of this run, so migration and abort handling ' +
232
+ '(e.g. persisting state before a migration) is now disabled.');
233
+ return;
234
+ }
235
+ if (CLEAN_CLOSE_CODES.has(code)) {
236
+ this.log.info(`Connection to platform events websocket was closed (${details}), reconnecting...`);
237
+ }
238
+ else {
239
+ this.log.warning(`Connection to platform events websocket was lost (${details}), reconnecting...`);
240
+ }
241
+ // Reconnect a healthy connection immediately; back off only on repeated rapid drops. The first rapid drop
242
+ // retries without delay (it just primes the backoff), each consecutive one waits for the next interval.
243
+ let delay = 0;
244
+ if (Date.now() - openedAt >= HEALTHY_CONNECTION_MIN_DURATION_MILLIS) {
245
+ this.#backoff = undefined;
246
+ }
247
+ else if (this.#backoff) {
248
+ delay = this.#backoff.next().value;
249
+ }
250
+ else {
251
+ this.#backoff = backoffDelays();
252
+ }
253
+ this.#reconnect(eventsWsUrl, delay).catch((err) => {
254
+ this.log.exception(err, 'Reconnecting to platform events websocket failed');
255
+ });
256
+ }
257
+ /** Keeps trying to connect, with backoff between failed attempts, until it succeeds or `close()` is called. */
258
+ async #reconnect(eventsWsUrl, initialDelayMillis) {
259
+ const { signal } = this.#abortController;
260
+ await this.#sleep(initialDelayMillis, signal);
261
+ while (!signal.aborted) {
262
+ try {
263
+ await this.#connect(eventsWsUrl);
264
+ this.log.info('Reconnected to the platform events websocket.');
265
+ return;
266
+ }
267
+ catch (err) {
268
+ if (signal.aborted)
269
+ return;
270
+ this.log.warning(`Reconnecting to platform events websocket failed: ${err.message}`);
271
+ }
272
+ this.#backoff ??= backoffDelays();
273
+ await this.#sleep(this.#backoff.next().value, signal);
274
+ }
275
+ }
276
+ /** Sleeps for the given time, or until the signal is aborted. */
277
+ async #sleep(millis, signal) {
278
+ if (millis <= 0 || signal.aborted)
279
+ return;
280
+ // Rejects with an `AbortError` when aborted, which just means there is nothing left to wait for.
281
+ await sleep(millis, undefined, { signal }).catch(() => { });
112
282
  }
113
283
  }
@@ -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
- type NewUrlOptions = Parameters<CoreProxyConfiguration['newProxyInfo']>[0];
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
- readonly config: Configuration;
149
- private groups;
150
- private countryCode?;
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, config?: Configuration);
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(options?: NewUrlOptions): Promise<ProxyInfo | undefined>;
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(options?: NewUrlOptions): Promise<string | undefined>;
186
+ newUrl(): Promise<string | undefined>;
183
187
  /**
184
188
  * Returns proxy username.
185
189
  */
186
- protected _getUsername(sessionId: string): string;
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
- protected _setPasswordIfToken(): Promise<void>;
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 _checkAccess(): Promise<boolean>;
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 _fetchStatus(): Promise<{
202
- connected: boolean;
203
- connectionError: string;
204
- isManInTheMiddle: boolean;
205
- } | undefined>;
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 _throwCannotCombineCustomWithApify(): void;
220
+ protected throwCannotCombineCustomWithApify(): void;
211
221
  }
212
222
  export {};