apify 4.0.0-beta.99 → 4.0.0-rc.1

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
@@ -173,13 +173,6 @@ export interface ApifyEnv {
173
173
  fact: string | null;
174
174
  inputSecretsPrivateKeyFile: string | null;
175
175
  inputSecretsPrivateKeyPassphrase: string | null;
176
- /**
177
- * Defines the path to a local directory where KeyValueStore, Dataset, and RequestQueue
178
- * store their data. Typically, it is set to ./storage. If omitted, you should define the
179
- * APIFY_TOKEN environment variable instead. See more info on combination of this and
180
- * APIFY_TOKEN [here](https://docs.apify.com/sdk/js/docs/concepts/environment-variables#combinations-of-apify_local_storage_dir-and-apify_token)(CRAWLEE_STORAGE_DIR)
181
- */
182
- localStorageDir: string | null;
183
176
  /**
184
177
  * Specifies the minimum log level, which can be one of the following values (in order of severity): DEBUG, INFO, WARNING and ERROR
185
178
  * (APIFY_LOG_LEVEL)
@@ -330,6 +323,11 @@ export interface MetamorphOptions {
330
323
  customAfterSleepMillis?: number;
331
324
  }
332
325
  export interface RebootOptions {
326
+ /**
327
+ * Amount of time, in seconds, to wait for the `persistState` and `migrating` event handlers before rebooting.
328
+ * @default 30
329
+ */
330
+ timeoutSecs?: number;
333
331
  /** @internal */
334
332
  customAfterSleepMillis?: number;
335
333
  }
@@ -670,6 +668,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
670
668
  * @param item Object or array of objects containing data to be stored in the default dataset.
671
669
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
672
670
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
671
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
673
672
  * @ignore
674
673
  */
675
674
  pushData(item: Data | Data[], eventName?: string | undefined): Promise<ChargeResult>;
@@ -792,6 +791,9 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
792
791
  * working directory. A storage backend that doesn't read the default key-value store's directory under
793
792
  * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
794
793
  *
794
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
795
+ * replaced with the links of their CSV exports.
796
+ *
795
797
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
796
798
  * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
797
799
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
@@ -916,6 +918,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
916
918
  * rather than batching via `count` — this gives finer control over budget consumption
917
919
  * and avoids situations where more work is requested than the budget allows.
918
920
  *
921
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
922
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
923
+ * be globally unique (e.g. derived from `requestId`).
924
+ *
919
925
  * @param options The name of the event to charge for and the number of events to be charged.
920
926
  * @ignore
921
927
  */
@@ -925,6 +931,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
925
931
  * @ignore
926
932
  */
927
933
  getChargingManager(): ChargingManager;
934
+ /**
935
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
936
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
937
+ * Resolves to `undefined` when not running on the Apify platform.
938
+ */
939
+ getCurrentRun(): Promise<ClientActorRun | undefined>;
928
940
  /**
929
941
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
930
942
  */
@@ -1308,6 +1320,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1308
1320
  * @param item Object or array of objects containing data to be stored in the default dataset.
1309
1321
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1310
1322
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1323
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1311
1324
  */
1312
1325
  static pushData<Data extends Dictionary = Dictionary>(item: Data | Data[], eventName: string): Promise<ChargeResult>;
1313
1326
  /**
@@ -1428,6 +1441,9 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1428
1441
  * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1429
1442
  * working directory.
1430
1443
  *
1444
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
1445
+ * replaced with the links of their CSV exports.
1446
+ *
1431
1447
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1432
1448
  * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1433
1449
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
@@ -1543,6 +1559,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1543
1559
  * rather than batching via `count` — this gives finer control over budget consumption
1544
1560
  * and avoids situations where more work is requested than the budget allows.
1545
1561
  *
1562
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1563
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1564
+ * be globally unique (e.g. derived from `requestId`).
1565
+ *
1546
1566
  * @param options The name of the event to charge for and the number of events to be charged.
1547
1567
  */
1548
1568
  static charge(options: ChargeOptions): Promise<ChargeResult>;
@@ -1570,6 +1590,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1570
1590
  * Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).
1571
1591
  */
1572
1592
  static isAtHome(): boolean;
1593
+ /**
1594
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1595
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1596
+ * Resolves to `undefined` when not running on the Apify platform.
1597
+ */
1598
+ static getCurrentRun(): Promise<ClientActorRun | undefined>;
1573
1599
  /** Default {@link ApifyClient} instance. */
1574
1600
  static get apifyClient(): ApifyClient;
1575
1601
  /** Default {@link Configuration} instance. */
package/dist/actor.js CHANGED
@@ -5,10 +5,11 @@ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend,
5
5
  import { sleep } from '@crawlee/utils';
6
6
  import { ApifyClient } from 'apify-client';
7
7
  import { z } from 'zod';
8
- import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, } from '@apify/consts';
8
+ import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, META_ORIGINS, } from '@apify/consts';
9
9
  import { decryptInputSecrets } from '@apify/input_secrets';
10
10
  import log from '@apify/log';
11
11
  import { addTimeoutToPromise } from '@apify/timeout';
12
+ import { timeoutPromise } from '@apify/utilities';
12
13
  import { parseArgument } from '@apify/validations';
13
14
  import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
14
15
  import { ApifyStorageBackend } from './apify_storage_backend.js';
@@ -17,6 +18,7 @@ import { ChargingStorageBackend } from './charging_storage_backend.js';
17
18
  import { ChildRunTracker } from './child_run_tracker.js';
18
19
  import { Configuration } from './configuration.js';
19
20
  import { ActorInputError } from './errors.js';
21
+ import { fixGoogleSheetsUrls } from './google_sheets.js';
20
22
  import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
21
23
  import { PlatformEventManager } from './platform_event_manager.js';
22
24
  import { ProxyConfiguration } from './proxy_configuration.js';
@@ -24,10 +26,11 @@ import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
24
26
  import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, snakeCaseToCamelCase, } from './utils.js';
25
27
  // `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
26
28
  const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
27
- // Still listed in `@apify/consts`, but no longer read by the SDK.
29
+ // Still listed in `@apify/consts`, but not read by the SDK.
28
30
  const IGNORED_ENV_VARS = [
29
31
  APIFY_ENV_VARS.DISABLE_OUTDATED_WARNING,
30
32
  APIFY_ENV_VARS.SDK_LATEST_VERSION,
33
+ APIFY_ENV_VARS.LOCAL_STORAGE_DIR,
31
34
  ];
32
35
  /**
33
36
  * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
@@ -102,6 +105,8 @@ export class Actor {
102
105
  */
103
106
  #statusMessageForwarder;
104
107
  #chargingManager;
108
+ #runPromise;
109
+ #actorPromise;
105
110
  /** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
106
111
  #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
107
112
  /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
@@ -136,7 +141,7 @@ export class Actor {
136
141
  this.eventManager = new PlatformEventManager(this.configuration, {
137
142
  [ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
138
143
  });
139
- this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
144
+ this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
140
145
  this.#childRunTracker = new ChildRunTracker();
141
146
  }
142
147
  /**
@@ -294,11 +299,20 @@ export class Actor {
294
299
  });
295
300
  log.debug(`Default storages purged`);
296
301
  await this.#childRunTracker.load();
302
+ this.#runPromise = undefined;
303
+ this.#actorPromise = undefined;
304
+ if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
305
+ // Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
306
+ void this.getCurrentRun().catch(() => { });
307
+ void this.#getCurrentActor().catch(() => { });
308
+ }
297
309
  await this.#chargingManager.init();
298
310
  log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
299
311
  // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
300
312
  // registered with crawlee directly; the storages the Actor installs itself are wrapped.
301
- if (this.#chargingManager.isPayPerEvent && !this.#chargesDefaultDatasetItems()) {
313
+ if (this.#chargingManager.isPayPerEvent &&
314
+ !this.#chargingManager.isMultiTenant &&
315
+ !this.#chargesDefaultDatasetItems()) {
302
316
  log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
303
317
  'storage - the platform only counts items it stores itself.');
304
318
  }
@@ -674,23 +688,36 @@ export class Actor {
674
688
  return;
675
689
  }
676
690
  this.#isRebooting = true;
691
+ const { timeoutSecs = 30, customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
692
+ const callListeners = (event, data) => serviceLocator
693
+ .getEventManager()
694
+ .listeners(event)
695
+ .map(async (listener) => {
696
+ try {
697
+ await listener(data);
698
+ }
699
+ catch (err) {
700
+ log.exception(err, 'A pre-reboot event listener failed');
701
+ }
702
+ });
677
703
  // Waiting for all the listeners to finish, as `.reboot()` kills the container.
678
- await Promise.all([
704
+ // Not using `addTimeoutToPromise`, its timeout would also cancel the enclosing one (e.g. a request handler).
705
+ await timeoutPromise(Promise.all([
679
706
  // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
680
- ...serviceLocator
681
- .getEventManager()
682
- .listeners(EventType.PERSIST_STATE)
683
- .map(async (x) => x({})),
707
+ ...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
684
708
  // `migrating` to pause Apify crawlers
685
- ...serviceLocator
686
- .getEventManager()
687
- .listeners(EventType.MIGRATING)
688
- .map(async (x) => x({})),
689
- ]);
709
+ ...callListeners(EventType.MIGRATING, {}),
710
+ ]), timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
690
711
  const runId = this.configuration.actorRunId;
691
- await this.apifyClient.run(runId).reboot();
712
+ try {
713
+ await this.apifyClient.run(runId).reboot();
714
+ }
715
+ catch (err) {
716
+ // Reset the flag so that a failed reboot can be retried.
717
+ this.#isRebooting = false;
718
+ throw err;
719
+ }
692
720
  // Wait some time for container to be stopped.
693
- const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
694
721
  await sleep(customAfterSleepMillis);
695
722
  }
696
723
  /**
@@ -807,6 +834,7 @@ export class Actor {
807
834
  * @param item Object or array of objects containing data to be stored in the default dataset.
808
835
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
809
836
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
837
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
810
838
  * @ignore
811
839
  */
812
840
  async pushData(item, eventName) {
@@ -814,6 +842,9 @@ export class Actor {
814
842
  if (eventName?.startsWith('apify-')) {
815
843
  throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
816
844
  }
845
+ if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
846
+ throw new Error('Charging for pushed items is not supported in a multi-tenant Server Actor run - use Actor.charge() with the `requestId` of the incoming request instead.');
847
+ }
817
848
  if (eventName !== undefined) {
818
849
  rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
819
850
  'so a rolled-back request would be billed for items that were never stored.');
@@ -937,6 +968,9 @@ export class Actor {
937
968
  * working directory. A storage backend that doesn't read the default key-value store's directory under
938
969
  * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
939
970
  *
971
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
972
+ * replaced with the links of their CSV exports.
973
+ *
940
974
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
941
975
  * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
942
976
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
@@ -995,7 +1029,7 @@ export class Actor {
995
1029
  }
996
1030
  }
997
1031
  if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
998
- input = await this.inferDefaultsFromInputSchema(input);
1032
+ input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
999
1033
  }
1000
1034
  return input;
1001
1035
  }
@@ -1155,6 +1189,10 @@ export class Actor {
1155
1189
  * rather than batching via `count` — this gives finer control over budget consumption
1156
1190
  * and avoids situations where more work is requested than the budget allows.
1157
1191
  *
1192
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1193
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1194
+ * be globally unique (e.g. derived from `requestId`).
1195
+ *
1158
1196
  * @param options The name of the event to charge for and the number of events to be charged.
1159
1197
  * @ignore
1160
1198
  */
@@ -1170,6 +1208,40 @@ export class Actor {
1170
1208
  this.ensureActorInit('getChargingManager');
1171
1209
  return this.#chargingManager;
1172
1210
  }
1211
+ /**
1212
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1213
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1214
+ * Resolves to `undefined` when not running on the Apify platform.
1215
+ */
1216
+ async getCurrentRun() {
1217
+ const runId = this.configuration.actorRunId;
1218
+ if (!runId) {
1219
+ return undefined;
1220
+ }
1221
+ this.#runPromise ??= this.apifyClient
1222
+ .run(runId)
1223
+ .get()
1224
+ .catch((err) => {
1225
+ this.#runPromise = undefined;
1226
+ throw err;
1227
+ });
1228
+ return this.#runPromise;
1229
+ }
1230
+ /** Cached for the lifetime of the Actor; only the charging manager needs it. */
1231
+ async #getCurrentActor() {
1232
+ const { actorId } = this.configuration;
1233
+ if (!actorId) {
1234
+ return undefined;
1235
+ }
1236
+ this.#actorPromise ??= this.apifyClient
1237
+ .actor(actorId)
1238
+ .get()
1239
+ .catch((err) => {
1240
+ this.#actorPromise = undefined;
1241
+ throw err;
1242
+ });
1243
+ return this.#actorPromise;
1244
+ }
1173
1245
  /**
1174
1246
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
1175
1247
  */
@@ -1618,6 +1690,7 @@ export class Actor {
1618
1690
  * @param item Object or array of objects containing data to be stored in the default dataset.
1619
1691
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1620
1692
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1693
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1621
1694
  */
1622
1695
  static async pushData(item, eventName) {
1623
1696
  if (eventName === undefined) {
@@ -1694,6 +1767,9 @@ export class Actor {
1694
1767
  * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1695
1768
  * working directory.
1696
1769
  *
1770
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
1771
+ * replaced with the links of their CSV exports.
1772
+ *
1697
1773
  * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1698
1774
  * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1699
1775
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
@@ -1815,6 +1891,10 @@ export class Actor {
1815
1891
  * rather than batching via `count` — this gives finer control over budget consumption
1816
1892
  * and avoids situations where more work is requested than the budget allows.
1817
1893
  *
1894
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1895
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1896
+ * be globally unique (e.g. derived from `requestId`).
1897
+ *
1818
1898
  * @param options The name of the event to charge for and the number of events to be charged.
1819
1899
  */
1820
1900
  static async charge(options) {
@@ -1852,6 +1932,14 @@ export class Actor {
1852
1932
  static isAtHome() {
1853
1933
  return Actor.getDefaultInstance().isAtHome();
1854
1934
  }
1935
+ /**
1936
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1937
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1938
+ * Resolves to `undefined` when not running on the Apify platform.
1939
+ */
1940
+ static async getCurrentRun() {
1941
+ return Actor.getDefaultInstance().getCurrentRun();
1942
+ }
1855
1943
  /** Default {@link ApifyClient} instance. */
1856
1944
  static get apifyClient() {
1857
1945
  return Actor.getDefaultInstance().apifyClient;
@@ -1,4 +1,4 @@
1
- import type { ActorRunPricingInfo, ApifyClient } from 'apify-client';
1
+ import type { ActorResource, ActorRunPricingInfo, ApifyClient, Run as ClientActorRun } from 'apify-client';
2
2
  import type { Configuration } from './configuration.js';
3
3
  export declare const DEFAULT_DATASET_ITEM_EVENT = "apify-default-dataset-item";
4
4
  export interface ChargeOptions {
@@ -16,8 +16,15 @@ export interface ChargeOptions {
16
16
  * A unique key preventing a retried operation from being charged for twice - e.g. a request handler rerun by a retry.
17
17
  * A repeat under the same key within three minutes is not sent to the API and reports the `chargedCount` of
18
18
  * the original call, or zero if it names a different event. Like the platform, the key is forgotten afterwards.
19
+ * In a multi-tenant Server Actor run, every call is sent and the platform deduplicates it.
19
20
  */
20
21
  idempotencyKey?: string;
22
+ /**
23
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
24
+ * Required for multi-tenant Server Actor runs, where it maps the charge to the caller's account instead of the account that started the run.
25
+ * Ignored elsewhere.
26
+ */
27
+ requestId?: string;
21
28
  }
22
29
  export interface ChargeResult {
23
30
  /**
@@ -60,9 +67,11 @@ export interface ActorPricingInfo {
60
67
  */
61
68
  export declare class ChargingManager {
62
69
  #private;
63
- constructor(configuration: Configuration, apifyClient: ApifyClient);
70
+ constructor(configuration: Configuration, apifyClient: ApifyClient, getCurrentRun: () => Promise<ClientActorRun | undefined>, getCurrentActor: () => Promise<ActorResource | undefined>);
64
71
  /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
65
72
  get isPayPerEvent(): boolean;
73
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
74
+ get isMultiTenant(): boolean;
66
75
  private fetchPricingInfo;
67
76
  /**
68
77
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
@@ -92,9 +101,19 @@ export declare class ChargingManager {
92
101
  * rather than batching via `count` — this gives finer control over budget consumption
93
102
  * and avoids situations where more work is requested than the budget allows.
94
103
  *
104
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
105
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
106
+ * be globally unique (e.g. derived from `requestId`).
107
+ *
95
108
  * @param options The name of the event to charge for and the number of events to be charged.
96
109
  */
97
- charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
110
+ charge({ eventName, count, idempotencyKey, requestId }: ChargeOptions): Promise<ChargeResult>;
111
+ /**
112
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
113
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
114
+ * run, even by another caller.
115
+ */
116
+ private chargeServerRequest;
98
117
  private getIdempotentCharge;
99
118
  private setIdempotentCharge;
100
119
  /**
package/dist/charging.js CHANGED
@@ -1,9 +1,23 @@
1
1
  import { Dataset, KeyValueStore } from '@crawlee/core';
2
+ import { META_ORIGINS } from '@apify/consts';
2
3
  import log from '@apify/log';
3
4
  import { ReentrantAsyncLock } from './utils.js';
4
5
  /** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
5
6
  const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
6
7
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
8
+ /**
9
+ * The pricing history includes scheduled future changes, so the effective entry is the latest one
10
+ * with `startedAt <= now`, not the last one.
11
+ *
12
+ * Resolved once at init on purpose. A change kicking in mid-run only affects local event titles and
13
+ * "unknown event" warnings; the platform prices each charge from its own current pricing anyway.
14
+ */
15
+ function getEffectivePricingInfo(pricingInfos, now = new Date()) {
16
+ return pricingInfos
17
+ .filter((info) => new Date(info.startedAt) <= now)
18
+ .sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime())
19
+ .at(-1);
20
+ }
7
21
  /**
8
22
  * Handles pay-per-event charging.
9
23
  */
@@ -14,6 +28,8 @@ export class ChargingManager {
14
28
  #isAtHome;
15
29
  #actorRunId;
16
30
  #pricingModel;
31
+ /** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
32
+ #isMultiTenant = false;
17
33
  #purgeChargingLogDataset;
18
34
  #useChargingLogDataset;
19
35
  #notPpeWarningPrinted = false;
@@ -25,7 +41,9 @@ export class ChargingManager {
25
41
  #chargeLock = new ReentrantAsyncLock();
26
42
  #apifyClient;
27
43
  #configuration;
28
- constructor(configuration, apifyClient) {
44
+ #getCurrentRun;
45
+ #getCurrentActor;
46
+ constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
29
47
  this.#configuration = configuration;
30
48
  this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
31
49
  this.#isAtHome = configuration.isAtHome;
@@ -33,27 +51,52 @@ export class ChargingManager {
33
51
  this.#purgeChargingLogDataset = configuration.purgeOnStart;
34
52
  this.#useChargingLogDataset = configuration.useChargingLogDataset;
35
53
  this.#apifyClient = apifyClient;
54
+ this.#getCurrentRun = getCurrentRun;
55
+ this.#getCurrentActor = getCurrentActor;
36
56
  }
37
57
  /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
38
58
  get isPayPerEvent() {
39
59
  return this.#pricingModel === 'PAY_PER_EVENT';
40
60
  }
61
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
62
+ get isMultiTenant() {
63
+ return this.#isMultiTenant;
64
+ }
41
65
  async fetchPricingInfo() {
42
66
  if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
43
- return {
44
- pricingInfo: JSON.parse(this.#configuration.actorPricingInfo),
45
- chargedEventCounts: JSON.parse(this.#configuration.chargedEventCounts),
46
- maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
47
- };
67
+ const pricingInfo = JSON.parse(this.#configuration.actorPricingInfo);
68
+ // Multi-tenant runs get an empty snapshot (`{}`); only the run tells them apart from free Server Actor runs.
69
+ const isMultiTenantCandidate = pricingInfo.pricingModel === undefined &&
70
+ this.#isAtHome &&
71
+ this.#configuration.metaOrigin === META_ORIGINS.STANDBY;
72
+ if (!isMultiTenantCandidate) {
73
+ return {
74
+ pricingInfo,
75
+ chargedEventCounts: JSON.parse(this.#configuration.chargedEventCounts),
76
+ maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
77
+ };
78
+ }
48
79
  }
49
80
  if (this.#isAtHome) {
50
81
  if (this.#actorRunId === undefined) {
51
82
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
52
83
  }
53
- const run = await this.#apifyClient.run(this.#actorRunId).get();
84
+ const run = await this.#getCurrentRun();
54
85
  if (run === undefined) {
55
86
  throw new Error('Actor run not found');
56
87
  }
88
+ if (run.standby?.deployment.startsWith('MULTI_TENANT')) {
89
+ const actor = await this.#getCurrentActor();
90
+ if (actor === undefined) {
91
+ throw new Error('Actor not found');
92
+ }
93
+ this.#isMultiTenant = true;
94
+ return {
95
+ pricingInfo: getEffectivePricingInfo(actor.pricingInfos ?? []),
96
+ chargedEventCounts: {}, // the run's counts mix all callers
97
+ maxTotalChargeUsd: Infinity, // the platform prices and limits per caller
98
+ };
99
+ }
57
100
  return {
58
101
  pricingInfo: run.pricingInfo,
59
102
  chargedEventCounts: run.chargedEventCounts,
@@ -165,9 +208,13 @@ export class ChargingManager {
165
208
  * rather than batching via `count` — this gives finer control over budget consumption
166
209
  * and avoids situations where more work is requested than the budget allows.
167
210
  *
211
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
212
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
213
+ * be globally unique (e.g. derived from `requestId`).
214
+ *
168
215
  * @param options The name of the event to charge for and the number of events to be charged.
169
216
  */
170
- async charge({ eventName, count = 1, idempotencyKey }) {
217
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
171
218
  if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
172
219
  throw new Error('idempotencyKey must not be blank');
173
220
  }
@@ -182,6 +229,9 @@ export class ChargingManager {
182
229
  chargeableWithinLimit: this.calculateChargeableWithinLimit(),
183
230
  };
184
231
  }
232
+ if (this.#isMultiTenant) {
233
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
234
+ }
185
235
  // Match the Python SDK: a non-positive count never reaches the platform and never
186
236
  // mutates local charge state (a negative count would otherwise decrement the budget).
187
237
  if (count <= 0) {
@@ -249,6 +299,7 @@ export class ChargingManager {
249
299
  eventName,
250
300
  count: chargedCount,
251
301
  idempotencyKey,
302
+ requestId,
252
303
  });
253
304
  }
254
305
  else {
@@ -275,6 +326,7 @@ export class ChargingManager {
275
326
  eventPriceUsd: pricingInfo.price,
276
327
  chargedCount,
277
328
  idempotencyKey,
329
+ requestId,
278
330
  timestamp: new Date().toISOString(),
279
331
  });
280
332
  }
@@ -289,6 +341,35 @@ export class ChargingManager {
289
341
  };
290
342
  });
291
343
  }
344
+ /**
345
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
346
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
347
+ * run, even by another caller.
348
+ */
349
+ async chargeServerRequest(eventName, count, idempotencyKey, requestId) {
350
+ if (eventName.startsWith('apify-')) {
351
+ throw new Error(`Cannot charge for synthetic event '${eventName}' in a multi-tenant Server Actor run`);
352
+ }
353
+ if (!requestId) {
354
+ throw new Error(`Charging for '${eventName}' in a multi-tenant Server Actor run requires \`requestId\` - pass the value of the incoming request's X-Actor-Request-ID header to Actor.charge().`);
355
+ }
356
+ let chargedCount = 0;
357
+ if (count <= 0) {
358
+ // Nothing to charge.
359
+ }
360
+ else if (this.#pricingInfo[eventName] === undefined) {
361
+ log.warning(`Attempting to charge for an unknown event '${eventName}'`);
362
+ }
363
+ else {
364
+ await this.#apifyClient.run(this.#actorRunId).charge({ eventName, count, idempotencyKey, requestId });
365
+ chargedCount = count;
366
+ }
367
+ return {
368
+ eventChargeLimitReached: false,
369
+ chargedCount,
370
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
371
+ };
372
+ }
292
373
  getIdempotentCharge(idempotencyKey) {
293
374
  const charge = this.#idempotentCharges.get(idempotencyKey);
294
375
  if (charge !== undefined && charge.expiresAt <= Date.now()) {
@@ -30,8 +30,12 @@ export class ChargingDatasetBackend {
30
30
  }
31
31
  async pushData(items) {
32
32
  const chargingManager = this.#getChargingManager();
33
- // `Dataset.pushData()` also works without `Actor.init()`, where there is no charging state yet.
34
- if (items.length === 0 || !chargingManager.isInitialized || !chargingManager.isPayPerEvent) {
33
+ // `Dataset.pushData()` also works without `Actor.init()`, where there is no charging state yet. Multi-tenant
34
+ // runs charge per request only, so dataset writes charge nothing there.
35
+ if (items.length === 0 ||
36
+ !chargingManager.isInitialized ||
37
+ !chargingManager.isPayPerEvent ||
38
+ chargingManager.isMultiTenant) {
35
39
  await this.#inner.pushData(items);
36
40
  return;
37
41
  }
@@ -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
@@ -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, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
15
+ export { ApifyClient, ApifyClientOptions, ApifyClientError, 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, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
12
+ export { ApifyClient, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
@@ -231,7 +231,7 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
231
231
  return;
232
232
  try {
233
233
  const user = await Actor.apifyClient.user().get();
234
- this.#password = user?.proxy?.password;
234
+ this.#password = user?.proxy?.password ?? undefined;
235
235
  }
236
236
  catch (error) {
237
237
  if (Actor.isAtHome()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.99",
3
+ "version": "4.0.0-rc.1",
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"
@@ -53,40 +53,40 @@
53
53
  ]
54
54
  },
55
55
  "dependencies": {
56
- "@apify/consts": "^3.0.1",
56
+ "@apify/consts": "^3.1.0",
57
57
  "@apify/datastructures": "^3.0.1",
58
- "@apify/input_secrets": "^2.0.8",
59
- "@apify/log": "^3.0.1",
60
- "@apify/pseudo_url": "^3.0.1",
58
+ "@apify/input_secrets": "^2.0.9",
59
+ "@apify/log": "^3.0.2",
60
+ "@apify/pseudo_url": "^3.0.2",
61
61
  "@apify/timeout": "^1.0.1",
62
- "@apify/utilities": "^3.1.0",
62
+ "@apify/utilities": "^3.1.1",
63
63
  "@apify/validations": "^1.1.4",
64
64
  "@crawlee/core": "4.0.0-rc.2",
65
65
  "@crawlee/fs-storage": "4.0.0-rc.2",
66
66
  "@crawlee/types": "4.0.0-rc.2",
67
67
  "@crawlee/utils": "4.0.0-rc.2",
68
- "apify-client": "^3.0.0-rc.0",
69
- "minimatch": "^11.0.5",
68
+ "apify-client": "^3.0.0-rc.1",
69
+ "minimatch": "^11.0.9",
70
70
  "tslib": "^2.9.1",
71
- "ws": "^8.22.2",
71
+ "ws": "^8.23.0",
72
72
  "zod": "^4.6.7"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@apify/oxlint-config": "^0.3.0",
76
76
  "@apify/tsconfig": "^0.2.0",
77
77
  "@commitlint/config-conventional": "^21.2.4",
78
- "@playwright/browser-chromium": "^1.65.0",
78
+ "@playwright/browser-chromium": "^1.65.1",
79
79
  "@types/node": "^26.6.6",
80
80
  "@types/ws": "^8.18.2",
81
81
  "commitlint": "^21.2.4",
82
82
  "crawlee": "4.0.0-rc.2",
83
83
  "husky": "^9.1.7",
84
- "lint-staged": "^17.6.0",
85
- "oxfmt": "0.78.0",
86
- "oxlint": "1.93.0",
87
- "oxlint-tsgolint": "7.0.2006",
88
- "playwright": "^1.65.0",
89
- "puppeteer": "^25.16.0",
84
+ "lint-staged": "^17.6.1",
85
+ "oxfmt": "0.79.0",
86
+ "oxlint": "1.94.0",
87
+ "oxlint-tsgolint": "7.0.2007",
88
+ "playwright": "^1.65.1",
89
+ "puppeteer": "^25.17.0",
90
90
  "rimraf": "^6.1.4",
91
91
  "tsx": "^4.23.15",
92
92
  "typescript": "~7.0.2",
@@ -95,7 +95,7 @@
95
95
  "devEngines": {
96
96
  "packageManager": {
97
97
  "name": "pnpm",
98
- "version": "12.18.0",
98
+ "version": "12.21.0",
99
99
  "onFail": "warn"
100
100
  }
101
101
  },