apify 4.0.0-beta.69 → 4.0.0-beta.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actor.d.ts CHANGED
@@ -628,11 +628,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
628
628
  /**
629
629
  * Sets the status message for the current Actor run.
630
630
  *
631
- * @returns The return value is the Run object.
631
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
632
+ * or when the update failed or timed out (a warning is logged in that case).
632
633
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
633
634
  * @ignore
634
635
  */
635
- setStatusMessage(statusMessage: string, options?: SetStatusMessageOptions): Promise<ClientActorRun>;
636
+ setStatusMessage(statusMessage: string, options?: SetStatusMessageOptions): Promise<ClientActorRun | undefined>;
636
637
  /**
637
638
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
638
639
  *
@@ -709,6 +710,35 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
709
710
  * @ignore
710
711
  */
711
712
  getValue<T = unknown>(key: string): Promise<T | null>;
713
+ /**
714
+ * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
715
+ *
716
+ * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
717
+ * For example, calling the following code:
718
+ * ```js
719
+ * const value = await Actor.getValue('my-key');
720
+ * ```
721
+ *
722
+ * is equivalent to:
723
+ * ```js
724
+ * const store = await Actor.openKeyValueStore();
725
+ * const value = await store.getValue('my-key');
726
+ * ```
727
+ *
728
+ * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
729
+ *
730
+ * For more information, see {@link Actor.openKeyValueStore}
731
+ * and {@link KeyValueStore.getValue}.
732
+ *
733
+ * @param key Unique record key.
734
+ * @param defaultValue Fallback that will be returned if no value if present in the storage.
735
+ * @returns
736
+ * Returns a promise that resolves to an object, string
737
+ * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
738
+ * on the MIME content type of the record, or the provided default value.
739
+ * @ignore
740
+ */
741
+ getValue<T = unknown>(key: string, defaultValue: T): Promise<T>;
712
742
  /**
713
743
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
714
744
  *
@@ -1211,10 +1241,11 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1211
1241
  * @param [options]
1212
1242
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1213
1243
  * This is required for the last status message of the run. Default value is `false`.
1214
- * @returns The return value is the Run object. When run locally, this method returns empty object (`{}`).
1244
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1245
+ * or when the update failed or timed out (a warning is logged in that case).
1215
1246
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1216
1247
  */
1217
- static setStatusMessage(statusMessage: string, options?: SetStatusMessageOptions): Promise<ClientActorRun>;
1248
+ static setStatusMessage(statusMessage: string, options?: SetStatusMessageOptions): Promise<ClientActorRun | undefined>;
1218
1249
  /**
1219
1250
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
1220
1251
  *
@@ -1313,6 +1344,34 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1313
1344
  * if the record is missing.
1314
1345
  */
1315
1346
  static getValue<T = unknown>(key: string): Promise<T | null>;
1347
+ /**
1348
+ * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
1349
+ *
1350
+ * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
1351
+ * For example, calling the following code:
1352
+ * ```js
1353
+ * const value = await Actor.getValue('my-key');
1354
+ * ```
1355
+ *
1356
+ * is equivalent to:
1357
+ * ```js
1358
+ * const store = await Actor.openKeyValueStore();
1359
+ * const value = await store.getValue('my-key');
1360
+ * ```
1361
+ *
1362
+ * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
1363
+ *
1364
+ * For more information, see {@link Actor.openKeyValueStore}
1365
+ * and {@link KeyValueStore.getValue}.
1366
+ *
1367
+ * @param key Unique record key.
1368
+ * @param defaultValue Fallback that will be returned if no value if present in the storage.
1369
+ * @returns
1370
+ * Returns a promise that resolves to an object, string
1371
+ * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1372
+ * on the MIME content type of the record, or the provided default value.
1373
+ */
1374
+ static getValue<T = unknown>(key: string, defaultValue: T): Promise<T>;
1316
1375
  /**
1317
1376
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
1318
1377
  *
package/dist/actor.js CHANGED
@@ -199,9 +199,7 @@ export class Actor {
199
199
  }
200
200
  catch (err) {
201
201
  log.exception(err, err.message);
202
- await this.exit({
203
- exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
204
- });
202
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
205
203
  }
206
204
  return ret;
207
205
  })();
@@ -239,9 +237,6 @@ export class Actor {
239
237
  else if (options.storage) {
240
238
  this.installStorageBackend(options.storage);
241
239
  }
242
- // Init the event manager the config uses
243
- await serviceLocator.getEventManager().init();
244
- log.debug(`Events initialized`);
245
240
  // Register handlers for aborting and migrating events for automatic graceful shutdown.
246
241
  // - aborting: calls Actor.exit() to terminate the run gracefully
247
242
  // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
@@ -268,6 +263,10 @@ export class Actor {
268
263
  // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
269
264
  this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
270
265
  this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
266
+ // Connect to the platform events only after the handlers above are registered, so that an event sent
267
+ // right after the connection opens (e.g. an already pending `aborting`) is not missed.
268
+ await serviceLocator.getEventManager().init();
269
+ log.debug(`Events initialized`);
271
270
  await purgeDefaultStorages({
272
271
  configuration: this.configuration,
273
272
  onlyPurgeOnce: true,
@@ -366,7 +365,8 @@ export class Actor {
366
365
  * @ignore
367
366
  */
368
367
  async fail(messageOrOptions, options = {}) {
369
- return this.exit(messageOrOptions, { exitCode: 1, ...options });
368
+ const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
369
+ return this.exit(messageOrOptions, { ...options, exitCode });
370
370
  }
371
371
  /**
372
372
  * @ignore
@@ -701,7 +701,8 @@ export class Actor {
701
701
  /**
702
702
  * Sets the status message for the current Actor run.
703
703
  *
704
- * @returns The return value is the Run object.
704
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
705
+ * or when the update failed or timed out (a warning is logged in that case).
705
706
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
706
707
  * @ignore
707
708
  */
@@ -729,17 +730,18 @@ export class Actor {
729
730
  }
730
731
  /**
731
732
  * Propagates a status message to the current run, without logging it locally.
733
+ * Resolves `undefined` when there is no run to update, or when the update failed or timed out.
732
734
  */
733
735
  async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
734
736
  const runId = this.configuration.actorRunId;
735
- if (runId) {
736
- // just to be sure, this should be fast
737
- const run = await addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => log.warning(e.message));
738
- if (run) {
739
- return run;
740
- }
737
+ if (!runId) {
738
+ return undefined;
741
739
  }
742
- return {};
740
+ // just to be sure, this should be fast
741
+ return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
742
+ log.warning(e.message);
743
+ return undefined;
744
+ });
743
745
  }
744
746
  /**
745
747
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -845,38 +847,10 @@ export class Actor {
845
847
  : undefined,
846
848
  });
847
849
  }
848
- /**
849
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
850
- *
851
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
852
- * For example, calling the following code:
853
- * ```js
854
- * const value = await Actor.getValue('my-key');
855
- * ```
856
- *
857
- * is equivalent to:
858
- * ```js
859
- * const store = await Actor.openKeyValueStore();
860
- * const value = await store.getValue('my-key');
861
- * ```
862
- *
863
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
864
- *
865
- * For more information, see {@link Actor.openKeyValueStore}
866
- * and {@link KeyValueStore.getValue}.
867
- *
868
- * @param key Unique record key.
869
- * @returns
870
- * Returns a promise that resolves to an object, string
871
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
872
- * on the MIME content type of the record, or `null`
873
- * if the record is missing.
874
- * @ignore
875
- */
876
- async getValue(key) {
850
+ async getValue(key, defaultValue) {
877
851
  this.ensureActorInit('getValue');
878
852
  const store = await this.openKeyValueStore();
879
- return store.getValue(key);
853
+ return store.getValue(key, defaultValue);
880
854
  }
881
855
  /**
882
856
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1563,7 +1537,8 @@ export class Actor {
1563
1537
  * @param [options]
1564
1538
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1565
1539
  * This is required for the last status message of the run. Default value is `false`.
1566
- * @returns The return value is the Run object. When run locally, this method returns empty object (`{}`).
1540
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1541
+ * or when the update failed or timed out (a warning is logged in that case).
1567
1542
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1568
1543
  */
1569
1544
  static async setStatusMessage(statusMessage, options) {
@@ -1618,35 +1593,8 @@ export class Actor {
1618
1593
  static async openDataset(datasetIdOrName, options = {}) {
1619
1594
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1620
1595
  }
1621
- /**
1622
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
1623
- *
1624
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
1625
- * For example, calling the following code:
1626
- * ```js
1627
- * const value = await Actor.getValue('my-key');
1628
- * ```
1629
- *
1630
- * is equivalent to:
1631
- * ```js
1632
- * const store = await Actor.openKeyValueStore();
1633
- * const value = await store.getValue('my-key');
1634
- * ```
1635
- *
1636
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
1637
- *
1638
- * For more information, see {@link Actor.openKeyValueStore}
1639
- * and {@link KeyValueStore.getValue}.
1640
- *
1641
- * @param key Unique record key.
1642
- * @returns
1643
- * Returns a promise that resolves to an object, string
1644
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1645
- * on the MIME content type of the record, or `null`
1646
- * if the record is missing.
1647
- */
1648
- static async getValue(key) {
1649
- return Actor.getDefaultInstance().getValue(key);
1596
+ static async getValue(key, defaultValue) {
1597
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1650
1598
  }
1651
1599
  /**
1652
1600
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -13,8 +13,9 @@ export interface ChargeOptions {
13
13
  */
14
14
  count?: number;
15
15
  /**
16
- * Repeated charges sharing a key are billed once - e.g. a request handler rerun by a retry.
17
- * Local accounting still counts every call, so the remaining budget comes out underestimated.
16
+ * A unique key preventing a retried operation from being charged for twice - e.g. a request handler rerun by a retry.
17
+ * A repeat under the same key within three minutes is not sent to the API and reports the `chargedCount` of
18
+ * the original call, or zero if it names a different event. Like the platform, the key is forgotten afterwards.
18
19
  */
19
20
  idempotencyKey?: string;
20
21
  }
@@ -94,6 +95,8 @@ export declare class ChargingManager {
94
95
  * @param options The name of the event to charge for and the number of events to be charged.
95
96
  */
96
97
  charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
98
+ private getIdempotentCharge;
99
+ private setIdempotentCharge;
97
100
  /**
98
101
  * Get the number of events with given name that the Actor has charged for so far.
99
102
  */
package/dist/charging.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Dataset, KeyValueStore } from '@crawlee/core';
2
2
  import log from '@apify/log';
3
3
  import { ReentrantAsyncLock } from './utils.js';
4
+ /** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
5
+ const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
4
6
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
5
7
  /**
6
8
  * Handles pay-per-event charging.
@@ -18,6 +20,8 @@ export class ChargingManager {
18
20
  #pricingInfo = {};
19
21
  #chargingState;
20
22
  #chargingLogDataset;
23
+ /** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
24
+ #idempotentCharges = new Map();
21
25
  #chargeLock = new ReentrantAsyncLock();
22
26
  #apifyClient;
23
27
  #configuration;
@@ -164,6 +168,9 @@ export class ChargingManager {
164
168
  * @param options The name of the event to charge for and the number of events to be charged.
165
169
  */
166
170
  async charge({ eventName, count = 1, idempotencyKey }) {
171
+ if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
172
+ throw new Error('idempotencyKey must not be blank');
173
+ }
167
174
  if (!this.isPayPerEvent) {
168
175
  if (!this.#notPpeWarningPrinted) {
169
176
  log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
@@ -180,6 +187,25 @@ export class ChargingManager {
180
187
  throw new Error('ChargingManager is not initialized');
181
188
  }
182
189
  return await this.withChargeLock(async () => {
190
+ // A repeat the platform would discard is resolved here too - counting it would inflate the charging state
191
+ // and make the run hit `maxTotalChargeUsd` early. The key alone decides, as on the platform.
192
+ const previous = idempotencyKey === undefined ? undefined : this.getIdempotentCharge(idempotencyKey);
193
+ if (previous !== undefined) {
194
+ let repeatedCount;
195
+ if (previous.eventName === eventName) {
196
+ log.debug(`Skipped a repeated charge of event '${eventName}' under key '${idempotencyKey}'.`);
197
+ repeatedCount = previous.chargedCount;
198
+ }
199
+ else {
200
+ log.warning(`Idempotency key '${idempotencyKey}' was already used to charge for event '${previous.eventName}', so the charge of event '${eventName}' is skipped.`);
201
+ repeatedCount = 0;
202
+ }
203
+ return {
204
+ eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
205
+ chargedCount: repeatedCount,
206
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
207
+ };
208
+ }
183
209
  const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
184
210
  const chargedCount = (() => {
185
211
  if (count <= maxEventChargeCount) {
@@ -204,12 +230,6 @@ export class ChargingManager {
204
230
  price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
205
231
  title: `Unknown event '${eventName}'`,
206
232
  };
207
- chargingState[eventName] ??= {
208
- chargeCount: 0,
209
- totalChargedAmount: 0,
210
- };
211
- chargingState[eventName].chargeCount += chargedCount;
212
- chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
213
233
  if (this.#isAtHome) {
214
234
  if (eventName.startsWith('apify-')) {
215
235
  // Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
@@ -226,12 +246,26 @@ export class ChargingManager {
226
246
  log.warning(`Attempting to charge for an unknown event '${eventName}'`);
227
247
  }
228
248
  }
249
+ // Count the charge only after the API call succeeds, so a failed call retried under the same key
250
+ // is counted once.
251
+ chargingState[eventName] ??= {
252
+ chargeCount: 0,
253
+ totalChargedAmount: 0,
254
+ };
255
+ chargingState[eventName].chargeCount += chargedCount;
256
+ chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
257
+ // Remember the key for every charge that was counted, including events the API never receives,
258
+ // such as synthetic ones - those are counted locally and a repeat would count them twice.
259
+ if (idempotencyKey !== undefined) {
260
+ this.setIdempotentCharge(idempotencyKey, { eventName, chargedCount });
261
+ }
229
262
  if (this.#chargingLogDataset !== undefined) {
230
263
  await this.#chargingLogDataset.pushData({
231
264
  eventName,
232
265
  eventTitle: pricingInfo.title,
233
266
  eventPriceUsd: pricingInfo.price,
234
267
  chargedCount,
268
+ idempotencyKey,
235
269
  timestamp: new Date().toISOString(),
236
270
  });
237
271
  }
@@ -246,6 +280,25 @@ export class ChargingManager {
246
280
  };
247
281
  });
248
282
  }
283
+ getIdempotentCharge(idempotencyKey) {
284
+ const charge = this.#idempotentCharges.get(idempotencyKey);
285
+ if (charge !== undefined && charge.expiresAt <= Date.now()) {
286
+ this.#idempotentCharges.delete(idempotencyKey);
287
+ return undefined;
288
+ }
289
+ return charge;
290
+ }
291
+ setIdempotentCharge(idempotencyKey, charge) {
292
+ const now = Date.now();
293
+ // Entries expire in insertion order, so pruning can stop at the first live one.
294
+ for (const [key, { expiresAt }] of this.#idempotentCharges) {
295
+ if (expiresAt > now) {
296
+ break;
297
+ }
298
+ this.#idempotentCharges.delete(key);
299
+ }
300
+ this.#idempotentCharges.set(idempotencyKey, { ...charge, expiresAt: now + IDEMPOTENCY_KEY_TTL_MILLIS });
301
+ }
249
302
  /**
250
303
  * Get the number of events with given name that the Actor has charged for so far.
251
304
  */
package/dist/index.d.ts CHANGED
@@ -12,4 +12,4 @@ export * from './proxy_configuration.js';
12
12
  export * from './platform_event_manager.js';
13
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
14
  export type { QueueOperationInfo } from '@crawlee/types';
15
- export { ApifyClient, ApifyClientOptions } from 'apify-client';
15
+ export { ApifyClient, ApifyClientOptions, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
package/dist/index.js CHANGED
@@ -9,4 +9,4 @@ export * from './configuration.js';
9
9
  export * from './proxy_configuration.js';
10
10
  export * from './platform_event_manager.js';
11
11
  export { Dataset, RequestQueue, KeyValueStore, log, Log, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
12
- export { ApifyClient } from 'apify-client';
12
+ export { ApifyClient, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
@@ -37,6 +37,9 @@ import { Configuration } from './configuration.js';
37
37
  * in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
38
38
  * Note that the `persistState` event is provided merely for user convenience,
39
39
  * you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
40
+ *
41
+ * The connection to the platform events websocket is re-established after it drops, unless it was closed
42
+ * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
40
43
  */
41
44
  export declare class PlatformEventManager extends EventManager {
42
45
  #private;
@@ -45,9 +48,10 @@ export declare class PlatformEventManager extends EventManager {
45
48
  /**
46
49
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
47
50
  * This is an internal function that is automatically called by `Actor.main()`.
51
+ *
52
+ * Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
48
53
  */
49
54
  init(): Promise<void>;
50
- private createWebSocketConnection;
51
55
  /**
52
56
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
53
57
  * of Apify package such as `persistState`.
@@ -1,8 +1,34 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
1
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,11 +66,18 @@ 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
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;
48
81
  constructor(configuration = Configuration.getGlobalConfiguration()) {
49
82
  super({
50
83
  persistStateIntervalMillis: configuration.persistStateIntervalMillis,
@@ -54,6 +87,8 @@ export class PlatformEventManager extends EventManager {
54
87
  /**
55
88
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
56
89
  * This is an internal function that is automatically called by `Actor.main()`.
90
+ *
91
+ * Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
57
92
  */
58
93
  async init() {
59
94
  if (this.initialized) {
@@ -66,37 +101,16 @@ export class PlatformEventManager extends EventManager {
66
101
  this.log.debug(`Environment variable ${ACTOR_ENV_VARS.EVENTS_WEBSOCKET_URL} is not set, no events from Apify platform will be emitted.`);
67
102
  return;
68
103
  }
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(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
- });
104
+ this.#abortController = new AbortController();
105
+ this.#backoff = undefined;
106
+ try {
107
+ await this.#connect(eventsWsUrl);
108
+ }
109
+ catch (err) {
110
+ // Leave no `persistState` interval behind, so that `init()` can be retried.
111
+ await this.close();
112
+ throw new Error('Error connecting to platform events websocket!', { cause: err });
113
+ }
100
114
  }
101
115
  /**
102
116
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
@@ -108,6 +122,116 @@ export class PlatformEventManager extends EventManager {
108
122
  return;
109
123
  }
110
124
  await super.close();
125
+ this.#abortController.abort();
111
126
  this.#eventsWs?.close();
112
127
  }
128
+ /** Opens a new connection; resolves once it is established and rejects if it fails before that. */
129
+ async #connect(eventsWsUrl) {
130
+ await new Promise((resolve, reject) => {
131
+ // `ws` has no default handshake timeout, so without it a silent server would block `init()` forever.
132
+ const ws = new WebSocket(eventsWsUrl, { handshakeTimeout: 10_000 });
133
+ this.#eventsWs = ws;
134
+ let openedAt;
135
+ let lastError;
136
+ ws.on('open', () => {
137
+ openedAt = Date.now();
138
+ resolve();
139
+ });
140
+ ws.on('message', (message) => this.#handleMessage(message));
141
+ ws.on('error', (err) => {
142
+ // Before the connection is open, the error is reported through the `close` event.
143
+ lastError = err;
144
+ if (openedAt !== undefined)
145
+ this.log.exception(err, 'Platform events websocket error');
146
+ });
147
+ ws.on('close', (code, reason) => {
148
+ if (this.#eventsWs === ws)
149
+ this.#eventsWs = undefined;
150
+ if (openedAt === undefined) {
151
+ reject(lastError ??
152
+ new Error(`Web socket closed before the connection was established (code=${code})`));
153
+ return;
154
+ }
155
+ this.#handleClose(eventsWsUrl, { code, reason: reason.toString(), openedAt });
156
+ });
157
+ });
158
+ }
159
+ #handleMessage(message) {
160
+ if (!message)
161
+ return;
162
+ try {
163
+ const { name, data } = JSON.parse(String(message));
164
+ this.events.emit(name, data);
165
+ if (name === ACTOR_EVENT_NAMES.MIGRATING) {
166
+ betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
167
+ this.events.emit(EventType.PERSIST_STATE, {
168
+ isMigrating: true,
169
+ });
170
+ }
171
+ }
172
+ catch (err) {
173
+ this.log.exception(err, 'Cannot parse Actor event');
174
+ }
175
+ }
176
+ /** Logs the close of an established connection and schedules a reconnection, unless the close is final. */
177
+ #handleClose(eventsWsUrl, { code, reason, openedAt }) {
178
+ if (this.#abortController.signal.aborted) {
179
+ this.log.debug('web socket has been closed');
180
+ return;
181
+ }
182
+ const details = `code=${code}, reason=${JSON.stringify(reason)}`;
183
+ if (NON_RETRYABLE_CLOSE_CODES.has(code)) {
184
+ this.log.error(`Connection to platform events websocket was closed with a non-retryable code (${details}); not reconnecting. ` +
185
+ 'No further platform events will be received for the rest of this run, so migration and abort handling ' +
186
+ '(e.g. persisting state before a migration) is now disabled.');
187
+ return;
188
+ }
189
+ if (CLEAN_CLOSE_CODES.has(code)) {
190
+ this.log.info(`Connection to platform events websocket was closed (${details}), reconnecting...`);
191
+ }
192
+ else {
193
+ this.log.warning(`Connection to platform events websocket was lost (${details}), reconnecting...`);
194
+ }
195
+ // Reconnect a healthy connection immediately; back off only on repeated rapid drops. The first rapid drop
196
+ // retries without delay (it just primes the backoff), each consecutive one waits for the next interval.
197
+ let delay = 0;
198
+ if (Date.now() - openedAt >= HEALTHY_CONNECTION_MIN_DURATION_MILLIS) {
199
+ this.#backoff = undefined;
200
+ }
201
+ else if (this.#backoff) {
202
+ delay = this.#backoff.next().value;
203
+ }
204
+ else {
205
+ this.#backoff = backoffDelays();
206
+ }
207
+ this.#reconnect(eventsWsUrl, delay).catch((err) => {
208
+ this.log.exception(err, 'Reconnecting to platform events websocket failed');
209
+ });
210
+ }
211
+ /** Keeps trying to connect, with backoff between failed attempts, until it succeeds or `close()` is called. */
212
+ async #reconnect(eventsWsUrl, initialDelayMillis) {
213
+ const { signal } = this.#abortController;
214
+ await this.#sleep(initialDelayMillis, signal);
215
+ while (!signal.aborted) {
216
+ try {
217
+ await this.#connect(eventsWsUrl);
218
+ this.log.info('Reconnected to the platform events websocket.');
219
+ return;
220
+ }
221
+ catch (err) {
222
+ if (signal.aborted)
223
+ return;
224
+ this.log.warning(`Reconnecting to platform events websocket failed: ${err.message}`);
225
+ }
226
+ this.#backoff ??= backoffDelays();
227
+ await this.#sleep(this.#backoff.next().value, signal);
228
+ }
229
+ }
230
+ /** Sleeps for the given time, or until the signal is aborted. */
231
+ async #sleep(millis, signal) {
232
+ if (millis <= 0 || signal.aborted)
233
+ return;
234
+ // Rejects with an `AbortError` when aborted, which just means there is nothing left to wait for.
235
+ await sleep(millis, undefined, { signal }).catch(() => { });
236
+ }
113
237
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.69",
3
+ "version": "4.0.0-beta.71",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"
@@ -85,7 +85,7 @@
85
85
  "husky": "^9.1.7",
86
86
  "lint-staged": "^17.6.0",
87
87
  "oxfmt": "0.73.0",
88
- "oxlint": "1.88.0",
88
+ "oxlint": "1.89.0",
89
89
  "oxlint-tsgolint": "7.0.2004",
90
90
  "playwright": "^1.63.0",
91
91
  "puppeteer": "^25.12.0",