apify 4.0.0-beta.70 → 4.0.0-beta.72

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
@@ -115,9 +115,9 @@ export interface ApifyEnv {
115
115
  */
116
116
  userId: string | null;
117
117
  /**
118
- * If it is `1`, it means that the user who started the Actor is a paying user. (APIFY_USER_IS_PAYING)
118
+ * Whether the user who started the Actor is a paying user. `false` when not set. (APIFY_USER_IS_PAYING)
119
119
  */
120
- userIsPaying: string | null;
120
+ userIsPaying: boolean;
121
121
  /**
122
122
  * Authentication token representing privileges given to the Actor run,
123
123
  * it can be passed to various Apify APIs (APIFY_TOKEN)
@@ -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
@@ -1,7 +1,7 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
2
  import { readFile, stat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
4
+ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
5
5
  import { sleep } from '@crawlee/utils';
6
6
  import { ApifyClient } from 'apify-client';
7
7
  import { z } from 'zod';
@@ -22,6 +22,8 @@ import { PlatformEventManager } from './platform_event_manager.js';
22
22
  import { ProxyConfiguration } from './proxy_configuration.js';
23
23
  import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
24
24
  import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, printOutdatedSdkWarning, snakeCaseToCamelCase, } from './utils.js';
25
+ // `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
26
+ const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
25
27
  /**
26
28
  * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
27
29
  * JSON input reports where it came from.
@@ -99,6 +101,8 @@ export class Actor {
99
101
  #requestQueueAccess = 'single';
100
102
  /** Lazily built by the `#storageBackend` getter. */
101
103
  #cachedStorageBackend;
104
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
105
+ #pendingListeners = [];
102
106
  constructor(options = {}) {
103
107
  const { configuration, ...configOptions } = options;
104
108
  if (configuration) {
@@ -199,9 +203,7 @@ export class Actor {
199
203
  }
200
204
  catch (err) {
201
205
  log.exception(err, err.message);
202
- await this.exit({
203
- exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
204
- });
206
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
205
207
  }
206
208
  return ret;
207
209
  })();
@@ -239,9 +241,6 @@ export class Actor {
239
241
  else if (options.storage) {
240
242
  this.installStorageBackend(options.storage);
241
243
  }
242
- // Init the event manager the config uses
243
- await serviceLocator.getEventManager().init();
244
- log.debug(`Events initialized`);
245
244
  // Register handlers for aborting and migrating events for automatic graceful shutdown.
246
245
  // - aborting: calls Actor.exit() to terminate the run gracefully
247
246
  // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
@@ -268,6 +267,19 @@ export class Actor {
268
267
  // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
269
268
  this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
270
269
  this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
270
+ // Attach listeners queued before init(), then connect to the platform events only after all handlers
271
+ // are registered, so that an event sent right after the connection opens (e.g. an already pending
272
+ // `aborting`) is not missed.
273
+ const events = serviceLocator.getEventManager();
274
+ if (this.#pendingListeners.length > 0) {
275
+ for (const [event, listener] of this.#pendingListeners) {
276
+ events.on(event, listener);
277
+ }
278
+ log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
279
+ this.#pendingListeners = [];
280
+ }
281
+ await events.init();
282
+ log.debug(`Events initialized`);
271
283
  await purgeDefaultStorages({
272
284
  configuration: this.configuration,
273
285
  onlyPurgeOnce: true,
@@ -366,18 +378,29 @@ export class Actor {
366
378
  * @ignore
367
379
  */
368
380
  async fail(messageOrOptions, options = {}) {
369
- return this.exit(messageOrOptions, { exitCode: 1, ...options });
381
+ const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
382
+ return this.exit(messageOrOptions, { ...options, exitCode });
370
383
  }
371
384
  /**
372
385
  * @ignore
373
386
  */
374
387
  on(event, listener) {
388
+ // Before init() the service locator must stay untouched, otherwise it
389
+ // creates a default Configuration that init() then conflicts with.
390
+ if (!this.initialized) {
391
+ this.#pendingListeners.push([event, listener]);
392
+ return;
393
+ }
375
394
  serviceLocator.getEventManager().on(event, listener);
376
395
  }
377
396
  /**
378
397
  * @ignore
379
398
  */
380
399
  off(event, listener) {
400
+ if (!this.initialized) {
401
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
402
+ return;
403
+ }
381
404
  serviceLocator.getEventManager().off(event, listener);
382
405
  }
383
406
  /**
@@ -475,12 +498,11 @@ export class Actor {
475
498
  async abort(runId, options = {}) {
476
499
  const { token, statusMessage, ...rest } = options;
477
500
  const client = token ? this.newClient({ token }) : this.apifyClient;
501
+ const runClient = client.run(runId);
478
502
  if (statusMessage) {
479
- await this.setStatusMessage(statusMessage, {
480
- isStatusMessageTerminal: true,
481
- });
503
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
482
504
  }
483
- return client.run(runId).abort(rest);
505
+ return runClient.abort(rest);
484
506
  }
485
507
  /**
486
508
  * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -701,7 +723,8 @@ export class Actor {
701
723
  /**
702
724
  * Sets the status message for the current Actor run.
703
725
  *
704
- * @returns The return value is the Run object.
726
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
727
+ * or when the update failed or timed out (a warning is logged in that case).
705
728
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
706
729
  * @ignore
707
730
  */
@@ -729,17 +752,18 @@ export class Actor {
729
752
  }
730
753
  /**
731
754
  * Propagates a status message to the current run, without logging it locally.
755
+ * Resolves `undefined` when there is no run to update, or when the update failed or timed out.
732
756
  */
733
757
  async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
734
758
  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
- }
759
+ if (!runId) {
760
+ return undefined;
741
761
  }
742
- return {};
762
+ // just to be sure, this should be fast
763
+ return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
764
+ log.warning(e.message);
765
+ return undefined;
766
+ });
743
767
  }
744
768
  /**
745
769
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -845,38 +869,10 @@ export class Actor {
845
869
  : undefined,
846
870
  });
847
871
  }
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) {
872
+ async getValue(key, defaultValue) {
877
873
  this.ensureActorInit('getValue');
878
874
  const store = await this.openKeyValueStore();
879
- return store.getValue(key);
875
+ return store.getValue(key, defaultValue);
880
876
  }
881
877
  /**
882
878
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1184,15 +1180,18 @@ export class Actor {
1184
1180
  })) {
1185
1181
  const camelCaseName = snakeCaseToCamelCase(shortName);
1186
1182
  let value = env[fullName];
1187
- // Parse dates and integers.
1188
- if (value && fullName.endsWith('_AT')) {
1183
+ // Parse booleans, dates and integers.
1184
+ if (BOOLEAN_ENV_VARS.includes(fullName)) {
1185
+ value = !!value && coerceBoolean.parse(value);
1186
+ }
1187
+ else if (value && fullName.endsWith('_AT')) {
1189
1188
  const unix = Date.parse(value);
1190
1189
  value = unix > 0 ? new Date(unix) : undefined;
1191
1190
  }
1192
1191
  else if (INTEGER_ENV_VARS.includes(fullName)) {
1193
1192
  value = parseInt(value, 10);
1194
1193
  }
1195
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1194
+ Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
1196
1195
  }
1197
1196
  return envVars;
1198
1197
  }
@@ -1563,7 +1562,8 @@ export class Actor {
1563
1562
  * @param [options]
1564
1563
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1565
1564
  * 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 (`{}`).
1565
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1566
+ * or when the update failed or timed out (a warning is logged in that case).
1567
1567
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1568
1568
  */
1569
1569
  static async setStatusMessage(statusMessage, options) {
@@ -1618,35 +1618,8 @@ export class Actor {
1618
1618
  static async openDataset(datasetIdOrName, options = {}) {
1619
1619
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1620
1620
  }
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);
1621
+ static async getValue(key, defaultValue) {
1622
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1650
1623
  }
1651
1624
  /**
1652
1625
  * 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
  */
@@ -41,7 +41,7 @@ export declare const apifyConfigFields: {
41
41
  standbyUrl: ConfigField<z.ZodOptional<z.ZodString>>;
42
42
  isAtHome: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
43
43
  userId: ConfigField<z.ZodOptional<z.ZodString>>;
44
- userIsPaying: ConfigField<z.ZodOptional<z.ZodString>>;
44
+ userIsPaying: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
45
45
  actorPermissionLevel: ConfigField<z.ZodOptional<z.ZodString>>;
46
46
  inputSecretsPrivateKeyPassphrase: ConfigField<z.ZodOptional<z.ZodString>>;
47
47
  inputSecretsPrivateKeyFile: ConfigField<z.ZodOptional<z.ZodString>>;
@@ -121,6 +121,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
121
121
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
122
122
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
123
123
  * `userId` | `APIFY_USER_ID` | -
124
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
124
125
  * `xvfb` | `APIFY_XVFB` | -
125
126
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
126
127
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
@@ -85,7 +85,7 @@ export const apifyConfigFields = {
85
85
  standbyUrl: field(z.string().optional(), ACTOR_ENV_VARS.STANDBY_URL),
86
86
  isAtHome: field(coerceBoolean.default(false), APIFY_ENV_VARS.IS_AT_HOME),
87
87
  userId: field(z.string().optional(), APIFY_ENV_VARS.USER_ID),
88
- userIsPaying: field(z.string().optional(), APIFY_ENV_VARS.USER_IS_PAYING),
88
+ userIsPaying: field(coerceBoolean.default(false), APIFY_ENV_VARS.USER_IS_PAYING),
89
89
  actorPermissionLevel: field(z.string().optional(), ACTOR_ENV_VARS.PERMISSION_LEVEL),
90
90
  inputSecretsPrivateKeyPassphrase: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_PASSPHRASE),
91
91
  inputSecretsPrivateKeyFile: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_FILE),
@@ -164,6 +164,7 @@ export const apifyConfigFields = {
164
164
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
165
165
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
166
166
  * `userId` | `APIFY_USER_ID` | -
167
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
167
168
  * `xvfb` | `APIFY_XVFB` | -
168
169
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
169
170
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
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.70",
3
+ "version": "4.0.0-beta.72",
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"