apify 4.0.0-beta.12 → 4.0.0-beta.120

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 (69) hide show
  1. package/README.md +29 -43
  2. package/dist/actor.d.ts +511 -167
  3. package/dist/actor.js +895 -322
  4. package/dist/apify_dataset_backend.d.ts +19 -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 +23 -0
  9. package/dist/apify_key_value_store_backend.js +56 -0
  10. package/dist/apify_request_queue_backend.d.ts +78 -0
  11. package/dist/apify_request_queue_backend.js +114 -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 +82 -18
  19. package/dist/charging.js +388 -128
  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 +86 -136
  25. package/dist/configuration.js +136 -145
  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 +11 -5
  33. package/dist/index.js +8 -5
  34. package/dist/input-schemas.d.ts +7 -0
  35. package/dist/input-schemas.js +58 -0
  36. package/dist/platform_event_manager.d.ts +15 -6
  37. package/dist/platform_event_manager.js +187 -41
  38. package/dist/proxy_configuration.d.ts +66 -59
  39. package/dist/proxy_configuration.js +172 -154
  40. package/dist/smart_apify_storage_backend.d.ts +52 -0
  41. package/dist/smart_apify_storage_backend.js +73 -0
  42. package/dist/storage.d.ts +38 -0
  43. package/dist/storage.js +1 -0
  44. package/dist/utils.d.ts +28 -4
  45. package/dist/utils.js +60 -20
  46. package/package.json +117 -73
  47. package/.turbo/turbo-build.log +0 -26
  48. package/.turbo/turbo-copy.log +0 -4
  49. package/dist/LICENSE.md +0 -201
  50. package/dist/README.md +0 -98
  51. package/dist/actor.d.ts.map +0 -1
  52. package/dist/actor.js.map +0 -1
  53. package/dist/charging.d.ts.map +0 -1
  54. package/dist/charging.js.map +0 -1
  55. package/dist/configuration.d.ts.map +0 -1
  56. package/dist/configuration.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/key_value_store.d.ts +0 -17
  60. package/dist/key_value_store.d.ts.map +0 -1
  61. package/dist/key_value_store.js +0 -33
  62. package/dist/key_value_store.js.map +0 -1
  63. package/dist/package.json +0 -75
  64. package/dist/platform_event_manager.d.ts.map +0 -1
  65. package/dist/platform_event_manager.js.map +0 -1
  66. package/dist/proxy_configuration.d.ts.map +0 -1
  67. package/dist/proxy_configuration.js.map +0 -1
  68. package/dist/utils.d.ts.map +0 -1
  69. package/dist/utils.js.map +0 -1
@@ -0,0 +1,52 @@
1
+ import { Minimatch } from 'minimatch';
2
+ import { purlToRegExp } from '@apify/pseudo_url';
3
+ /**
4
+ * Turns the `globs` and `pseudoUrls` input editor values into a `transformRequestFunction` that skips requests
5
+ * matching no pattern (all requests pass when no pattern is given) and applies the options of the matched pattern.
6
+ * When a URL matches multiple patterns, the first one wins, with globs checked before pseudo-URLs. The matched
7
+ * pattern's options shallowly override the request's fields, including `userData` (no deep merge, like in v3).
8
+ *
9
+ * ```ts
10
+ * await enqueueLinks({ transformRequestFunction: createTransformRequestFunction({ globs: input.globs }) });
11
+ * ```
12
+ */
13
+ export function createTransformRequestFunction({ globs = [], pseudoUrls = [], }) {
14
+ const patterns = [
15
+ ...globs.flatMap((item) => {
16
+ if (item == null) {
17
+ return [];
18
+ }
19
+ const { glob, ...options } = typeof item === 'string' ? { glob: item } : item;
20
+ const trimmedGlob = typeof glob === 'string' ? glob.trim() : '';
21
+ if (trimmedGlob.length === 0) {
22
+ return [];
23
+ }
24
+ const minimatch = new Minimatch(trimmedGlob, { nocase: true });
25
+ return [{ matches: (url) => minimatch.match(url), options }];
26
+ }),
27
+ ...pseudoUrls.flatMap((item) => {
28
+ if (item == null) {
29
+ return [];
30
+ }
31
+ const { purl, ...options } = typeof item === 'string' ? { purl: item } : item;
32
+ if (typeof purl !== 'string' || purl.trim().length === 0) {
33
+ return [];
34
+ }
35
+ let regexp;
36
+ try {
37
+ regexp = purlToRegExp(purl);
38
+ }
39
+ catch (cause) {
40
+ throw new Error(`Invalid pseudoUrl pattern '${purl}': ${cause.message}`, { cause });
41
+ }
42
+ return [{ matches: (url) => regexp.test(url), options }];
43
+ }),
44
+ ];
45
+ if (patterns.length === 0) {
46
+ return () => 'unchanged';
47
+ }
48
+ return (request) => {
49
+ const matched = patterns.find(({ matches }) => matches(request.url));
50
+ return matched ? { ...request, ...matched.options } : false;
51
+ };
52
+ }
@@ -0,0 +1,31 @@
1
+ /** Why {@link Actor.getInput} could not produce the input. */
2
+ export type ActorInputErrorCode =
3
+ /** No input record in the default key-value store, and locally no input file either. */
4
+ 'NOT_FOUND'
5
+ /** The input is in more than one place — both `<inputKey>` and `<inputKey>.json` in one directory, or in the store and in the working directory — so none is picked. */
6
+ | 'MULTIPLE_FILES'
7
+ /** The secret fields of the input could not be decrypted; `cause` holds the underlying error. */
8
+ | 'DECRYPTION_FAILED'
9
+ /** A JSON input record or file does not parse; `cause` holds the parser error. */
10
+ | 'PARSE_FAILED';
11
+ /**
12
+ * Thrown by {@link Actor.getInput} when the Actor input cannot be produced. `code` says why, and
13
+ * `cause` carries the underlying error where there is one. Anything else thrown by `getInput()`, such as
14
+ * an Apify API error, is not an input problem and is passed through as is.
15
+ *
16
+ * ```js
17
+ * try {
18
+ * input = await Actor.getInput();
19
+ * } catch (error) {
20
+ * if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
21
+ * input = {};
22
+ * }
23
+ * ```
24
+ */
25
+ export declare class ActorInputError extends Error {
26
+ readonly name = "ActorInputError";
27
+ readonly code: ActorInputErrorCode;
28
+ constructor(code: ActorInputErrorCode, message: string, options?: {
29
+ cause?: unknown;
30
+ });
31
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Thrown by {@link Actor.getInput} when the Actor input cannot be produced. `code` says why, and
3
+ * `cause` carries the underlying error where there is one. Anything else thrown by `getInput()`, such as
4
+ * an Apify API error, is not an input problem and is passed through as is.
5
+ *
6
+ * ```js
7
+ * try {
8
+ * input = await Actor.getInput();
9
+ * } catch (error) {
10
+ * if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
11
+ * input = {};
12
+ * }
13
+ * ```
14
+ */
15
+ export class ActorInputError extends Error {
16
+ name = 'ActorInputError';
17
+ code;
18
+ constructor(code, message, options) {
19
+ super(message, options);
20
+ this.code = code;
21
+ }
22
+ }
@@ -0,0 +1,12 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ /**
3
+ * Turns a Google Sheets sharing link into the link of its CSV export, other URLs are returned unchanged.
4
+ * @internal
5
+ */
6
+ export declare function toGoogleSheetsCsvUrl(url: string): string;
7
+ /**
8
+ * Replaces Google Sheets sharing links in the `requestsFromUrl` entries of the input's array fields (as produced by
9
+ * the "Link remote text file" option of the `requestListSources` editor) with the links of their CSV exports.
10
+ * @internal
11
+ */
12
+ export declare function fixGoogleSheetsUrls<T extends Dictionary>(input: T): T;
@@ -0,0 +1,26 @@
1
+ // Links published to the web (`/spreadsheets/d/e/<id>/pub?output=csv`) and links that already point at an export
2
+ // (`/gviz/...`, `/export...`) are downloadable as they are, so they're left alone.
3
+ const GOOGLE_SHEETS_URL_REGEX = /^(https:\/\/docs\.google\.com\/spreadsheets\/d\/(?!e\/)(?:\w|-)+)(\/(?:gviz|export)\b)?/;
4
+ /**
5
+ * Turns a Google Sheets sharing link into the link of its CSV export, other URLs are returned unchanged.
6
+ * @internal
7
+ */
8
+ export function toGoogleSheetsCsvUrl(url) {
9
+ const match = GOOGLE_SHEETS_URL_REGEX.exec(url);
10
+ return match && !match[2] ? `${match[1]}/gviz/tq?tqx=out:csv` : url;
11
+ }
12
+ /**
13
+ * Replaces Google Sheets sharing links in the `requestsFromUrl` entries of the input's array fields (as produced by
14
+ * the "Link remote text file" option of the `requestListSources` editor) with the links of their CSV exports.
15
+ * @internal
16
+ */
17
+ export function fixGoogleSheetsUrls(input) {
18
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [
19
+ key,
20
+ Array.isArray(value)
21
+ ? value.map((item) => typeof item?.requestsFromUrl === 'string'
22
+ ? { ...item, requestsFromUrl: toGoogleSheetsCsvUrl(item.requestsFromUrl) }
23
+ : item)
24
+ : value,
25
+ ]));
26
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  export * from './actor.js';
2
- export * from './charging.js';
2
+ export { ApifyStorageBackend, type ApifyStorageBackendOptions } from './apify_storage_backend.js';
3
+ export { ApifyFileSystemStorageBackend, type ApifyFileSystemStorageOptions, } from './apify_file_system_storage_backend.js';
4
+ export type { RequestQueueAccessMode } from './apify_request_queue_backend.js';
5
+ export { ArgumentValidationError } from './utils.js';
6
+ export { ActorInputError, type ActorInputErrorCode } from './errors.js';
7
+ export { createTransformRequestFunction, type GlobInput, type PseudoUrlInput, type UrlPatternFilters, type UrlPatternRequestOptions, } from './enqueue_links_filters.js';
8
+ export type { OpenStorageOptions, StorageAlias, StorageId, StorageName, StorageIdentifier } from './storage.js';
9
+ export { ChargeOptions, ChargeResult, ActorPricingInfo, ChargingManager } from './charging.js';
3
10
  export * from './configuration.js';
4
11
  export * from './proxy_configuration.js';
5
12
  export * from './platform_event_manager.js';
6
- export * from './key_value_store.js';
7
- export { Dataset, DatasetDataOptions, DatasetIteratorOptions, DatasetConsumer, DatasetMapper, DatasetReducer, DatasetOptions, DatasetContent, RequestQueue, QueueOperationInfo, RequestQueueOperationOptions, RequestQueueOptions, KeyConsumer, KeyValueStoreOptions, RecordOptions, KeyValueStoreIteratorOptions, log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
8
- export { ApifyClient, ApifyClientOptions } from 'apify-client';
9
- //# sourceMappingURL=index.d.ts.map
13
+ export { Dataset, DatasetDataOptions, DatasetIteratorOptions, DatasetConsumer, DatasetMapper, DatasetReducer, DatasetOptions, DatasetContent, RequestQueue, RequestQueueOperationOptions, RequestQueueOptions, KeyValueStore, KeyConsumer, KeyValueStoreOptions, RecordOptions, KeyValueStoreIteratorOptions, log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
14
+ export type { QueueOperationInfo } from '@crawlee/types';
15
+ export { ApifyClient, ApifyClientOptions, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
package/dist/index.js CHANGED
@@ -1,9 +1,12 @@
1
1
  export * from './actor.js';
2
- export * from './charging.js';
2
+ export { ApifyStorageBackend } from './apify_storage_backend.js';
3
+ export { ApifyFileSystemStorageBackend, } from './apify_file_system_storage_backend.js';
4
+ export { ArgumentValidationError } from './utils.js';
5
+ export { ActorInputError } from './errors.js';
6
+ export { createTransformRequestFunction, } from './enqueue_links_filters.js';
7
+ export { ChargingManager } from './charging.js';
3
8
  export * from './configuration.js';
4
9
  export * from './proxy_configuration.js';
5
10
  export * from './platform_event_manager.js';
6
- export * from './key_value_store.js';
7
- export { Dataset, RequestQueue, log, Log, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
8
- export { ApifyClient } from 'apify-client';
9
- //# sourceMappingURL=index.js.map
11
+ export { Dataset, RequestQueue, KeyValueStore, log, Log, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
12
+ export { ApifyClient, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
@@ -0,0 +1,7 @@
1
+ import type { Dictionary } from '@crawlee/types';
2
+ /**
3
+ * @ignore
4
+ */
5
+ export declare const noActorInputSchemaDefinedMarker: unique symbol;
6
+ export declare const readInputSchema: () => Dictionary | null | typeof noActorInputSchemaDefinedMarker;
7
+ export declare const getDefaultsFromInputSchema: (inputSchema: any) => Record<string, unknown>;
@@ -0,0 +1,58 @@
1
+ // TODO: https://github.com/apify/apify-shared-js/issues/547
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import process from 'node:process';
5
+ // These paths are used *if* there is no `input` field in the actor.json configuration file!
6
+ const DEFAULT_INPUT_SCHEMA_PATHS = [
7
+ ['.actor', 'INPUT_SCHEMA.json'],
8
+ ['INPUT_SCHEMA.json'],
9
+ ['.actor', 'input_schema.json'],
10
+ ['input_schema.json'],
11
+ ];
12
+ const ACTOR_SPECIFICATION_FOLDER = '.actor';
13
+ const LOCAL_CONFIG_NAME = 'actor.json';
14
+ const readJSONIfExists = (path) => {
15
+ if (existsSync(path)) {
16
+ const content = readFileSync(path, 'utf8');
17
+ return JSON.parse(content);
18
+ }
19
+ return null;
20
+ };
21
+ /**
22
+ * @ignore
23
+ */
24
+ export const noActorInputSchemaDefinedMarker = Symbol.for('apify.noActorInputSchemaDefined');
25
+ export const readInputSchema = () => {
26
+ const localConfig = readJSONIfExists(join(process.cwd(), ACTOR_SPECIFICATION_FOLDER, LOCAL_CONFIG_NAME));
27
+ // Input schema nested in the actor config
28
+ if (typeof localConfig?.input === 'object') {
29
+ return localConfig.input;
30
+ }
31
+ // Input schema path from the actor config
32
+ if (typeof localConfig?.input === 'string') {
33
+ const fullPath = join(process.cwd(), ACTOR_SPECIFICATION_FOLDER, localConfig.input);
34
+ return readJSONIfExists(fullPath);
35
+ }
36
+ // Try to find it from possible default paths
37
+ for (const path of DEFAULT_INPUT_SCHEMA_PATHS) {
38
+ const fullPath = join(process.cwd(), ...path);
39
+ const result = readJSONIfExists(fullPath);
40
+ if (result) {
41
+ return result;
42
+ }
43
+ }
44
+ // If we are in an Actor context, BUT we do not have an input schema defined, we want to skip the warning
45
+ if (!localConfig?.input) {
46
+ return noActorInputSchemaDefinedMarker;
47
+ }
48
+ return null;
49
+ };
50
+ export const getDefaultsFromInputSchema = (inputSchema) => {
51
+ const defaults = {};
52
+ for (const [key, fieldSchema] of Object.entries(inputSchema.properties)) {
53
+ if (fieldSchema.default !== undefined) {
54
+ defaults[key] = fieldSchema.default;
55
+ }
56
+ }
57
+ return defaults;
58
+ };
@@ -1,3 +1,4 @@
1
+ import type { EventTypeName } from '@crawlee/core';
1
2
  import { EventManager } from '@crawlee/core';
2
3
  import { Configuration } from './configuration.js';
3
4
  /**
@@ -37,18 +38,27 @@ import { Configuration } from './configuration.js';
37
38
  * in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
38
39
  * Note that the `persistState` event is provided merely for user convenience,
39
40
  * you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
41
+ *
42
+ * The connection to the platform events websocket is re-established after it drops, unless it was closed
43
+ * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
40
44
  */
41
45
  export declare class PlatformEventManager extends EventManager {
42
- readonly config: Configuration;
43
- /** Websocket connection to Actor events. */
44
- private eventsWs?;
45
- constructor(config?: Configuration);
46
+ #private;
47
+ readonly configuration: Configuration;
48
+ /**
49
+ * @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
50
+ * user code can neither remove them with `off()` nor see them in `listeners()`.
51
+ */
52
+ constructor(configuration?: Configuration, internalListeners?: Partial<Record<EventTypeName, (...args: any[]) => unknown>>);
53
+ emit(event: EventTypeName, ...args: unknown[]): void;
54
+ waitForAllListenersToComplete(): Promise<boolean>;
46
55
  /**
47
56
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
48
57
  * This is an internal function that is automatically called by `Actor.main()`.
58
+ *
59
+ * Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
49
60
  */
50
61
  init(): Promise<void>;
51
- private createWebSocketConnection;
52
62
  /**
53
63
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
54
64
  * of Apify package such as `persistState`.
@@ -56,4 +66,3 @@ export declare class PlatformEventManager extends EventManager {
56
66
  */
57
67
  close(): Promise<void>;
58
68
  }
59
- //# sourceMappingURL=platform_event_manager.d.ts.map
@@ -1,8 +1,34 @@
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
+ /**
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,62 +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
- config;
74
+ configuration;
46
75
  /** Websocket connection to Actor events. */
47
- eventsWs;
48
- constructor(config = Configuration.getGlobalConfig()) {
49
- super();
50
- this.config = config;
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 = {}) {
89
+ super({
90
+ persistStateIntervalMillis: configuration.persistStateIntervalMillis,
91
+ });
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;
51
108
  }
52
109
  /**
53
110
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
54
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.
55
114
  */
56
115
  async init() {
57
116
  if (this.initialized) {
58
117
  return;
59
118
  }
60
119
  await super.init();
61
- const eventsWsUrl = this.config.get('actorEventsWsUrl');
120
+ const eventsWsUrl = this.configuration.actorEventsWsUrl;
62
121
  // Locally there is no web socket to connect, so just print a log message.
63
122
  if (!eventsWsUrl) {
64
123
  this.log.debug(`Environment variable ${ACTOR_ENV_VARS.EVENTS_WEBSOCKET_URL} is not set, no events from Apify platform will be emitted.`);
65
124
  return;
66
125
  }
67
- this.createWebSocketConnection(eventsWsUrl);
68
- }
69
- createWebSocketConnection(eventsWsUrl) {
70
- this.eventsWs = new WebSocket(eventsWsUrl);
71
- this.eventsWs.on('message', (message) => {
72
- if (!message)
73
- return;
74
- try {
75
- const { name, data } = JSON.parse(String(message));
76
- this.events.emit(name, data);
77
- if (name === ACTOR_EVENT_NAMES.MIGRATING) {
78
- betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
79
- this.events.emit("persistState" /* EventType.PERSIST_STATE */, {
80
- isMigrating: true,
81
- });
82
- }
83
- }
84
- catch (err) {
85
- this.log.exception(err, 'Cannot parse Actor event');
86
- }
87
- });
88
- this.eventsWs.on('error', (err) => {
89
- // Don't print this error as this happens in the case of very short Actor.main().
90
- if (err.message ===
91
- 'WebSocket was closed before the connection was established')
92
- return;
93
- this.log.exception(err, 'web socket connection failed');
94
- });
95
- this.eventsWs.on('close', () => {
96
- this.log.debug('web socket has been closed');
97
- this.eventsWs = undefined;
98
- });
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
+ }
99
136
  }
100
137
  /**
101
138
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
@@ -107,7 +144,116 @@ export class PlatformEventManager extends EventManager {
107
144
  return;
108
145
  }
109
146
  await super.close();
110
- this.eventsWs?.close();
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(() => { });
111
258
  }
112
259
  }
113
- //# sourceMappingURL=platform_event_manager.js.map