apify 4.0.0-beta.15 → 4.0.0-beta.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +416 -281
  3. package/dist/actor.js +743 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +88 -0
  11. package/dist/apify_request_queue_backend.js +123 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +201 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +265 -0
  16. package/dist/apify_storage_backend.d.ts +95 -0
  17. package/dist/apify_storage_backend.js +219 -0
  18. package/dist/charging.d.ts +77 -47
  19. package/dist/charging.js +348 -226
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +110 -0
  23. package/dist/child_run_tracker.js +333 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +66 -12
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +32 -21
  38. package/dist/proxy_configuration.js +137 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
@@ -0,0 +1,219 @@
1
+ import { createHash } from 'node:crypto';
2
+ import log from '@apify/log';
3
+ import { cryptoRandomObjectId } from '@apify/utilities';
4
+ import { ApifyDatasetBackend } from './apify_dataset_backend.js';
5
+ import { ApifyKeyValueStoreBackend } from './apify_key_value_store_backend.js';
6
+ import { AsyncLock } from './apify_request_queue_backend.js';
7
+ import { ApifyRequestQueueSharedBackend } from './apify_request_queue_shared_backend.js';
8
+ import { ApifyRequestQueueSingleBackend } from './apify_request_queue_single_backend.js';
9
+ /** The reserved alias crawlee uses for the default (unnamed) storage. */
10
+ export const DEFAULT_STORAGE_ALIAS = '__default__';
11
+ /** The key of the default key-value store record holding this run's alias -> storage id mapping. */
12
+ const ALIAS_MAPPING_RECORD_KEY = 'APIFY_STORAGE_ALIASES_MAPPING';
13
+ async function readAliasMapping(store) {
14
+ const record = await store.getRecord(ALIAS_MAPPING_RECORD_KEY);
15
+ return record?.value ?? {};
16
+ }
17
+ /** The maximum clientKey length accepted by the request queue API. */
18
+ const MAX_CLIENT_KEY_LENGTH = 32;
19
+ const DEFAULT_ID_CONFIG_KEY = {
20
+ Dataset: 'defaultDatasetId',
21
+ KeyValueStore: 'defaultKeyValueStoreId',
22
+ RequestQueue: 'defaultRequestQueueId',
23
+ };
24
+ const ACTOR_STORAGES_TYPE_KEY = {
25
+ Dataset: 'datasets',
26
+ KeyValueStore: 'keyValueStores',
27
+ RequestQueue: 'requestQueues',
28
+ };
29
+ /**
30
+ * Bridges `apify-client`'s synchronous resource accessors (`dataset(id)`,
31
+ * `keyValueStore(id)`, `requestQueue(id, options?)`) to crawlee v4's
32
+ * `StorageBackend` interface (async factory methods accepting an `id`,
33
+ * a `name`, or an `alias`).
34
+ *
35
+ * Retries of storage calls are the client's — configure them on the `ApifyClient`. Request queue
36
+ * calls also end early when the caller's `signal` aborts.
37
+ *
38
+ * `Actor` wires this up automatically; construct it directly only to use Apify
39
+ * platform storage with crawlee's storage classes outside of `Actor` — e.g. to
40
+ * read another run's output with an explicit token:
41
+ *
42
+ * ```ts
43
+ * import { ApifyClient, ApifyStorageBackend, Dataset } from 'apify';
44
+ *
45
+ * const client = new ApifyClient({ token });
46
+ * const dataset = await Dataset.open(datasetId, { storageBackend: new ApifyStorageBackend(client) });
47
+ * const { items } = await dataset.getData();
48
+ * ```
49
+ */
50
+ export class ApifyStorageBackend {
51
+ #client;
52
+ #config;
53
+ #requestQueueAccess;
54
+ /** Unnamed storages resolved for aliases in this process, keyed like {@link AliasMapping}. */
55
+ #aliasIdCache = new Map();
56
+ /** The alias mapping read from the run's default key-value store; `undefined` until first read. */
57
+ #persistedAliasIds;
58
+ /** Serializes alias resolution — see `resolveAliasId`. */
59
+ #aliasLock = new AsyncLock();
60
+ /** Fallback request queue client key when the run id is unavailable — one per backend. */
61
+ #fallbackClientKey;
62
+ constructor(client, options = {}) {
63
+ this.#client = client;
64
+ this.#config = options.configuration;
65
+ this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
66
+ }
67
+ /**
68
+ * Partitions crawlee's storage-instance cache by API base URL and token, so the same storage
69
+ * opened through two differently-authenticated backends is cached separately. The request
70
+ * queue access mode is deliberately not part of the key — opening the same queue in `single`
71
+ * and `shared` mode at once is not supported, and whichever backend opens it first wins.
72
+ */
73
+ getStorageBackendCacheKey() {
74
+ return `ApifyStorageBackend:${this.credentialsHash()}`;
75
+ }
76
+ /** Lets crawlee's storage load signal see the API's rate-limit errors. */
77
+ get stats() {
78
+ return this.#client.stats;
79
+ }
80
+ /** Short digest of the API base URL and `identity`, the token unless given — identifies the credentials. */
81
+ credentialsHash(identity) {
82
+ return createHash('sha256')
83
+ .update(`${this.#client.publicBaseUrl}${identity || this.#client.token || ''}`)
84
+ .digest('hex')
85
+ .slice(0, 8);
86
+ }
87
+ async storageExists(id, type) {
88
+ // Lets `Dataset.open(idOrName)` and friends resolve a string to an id first (when one
89
+ // exists on the platform) and fall back to a name otherwise; without this, crawlee would
90
+ // treat every string as a name and silently create a new storage named like the passed id.
91
+ // Apify's `GET /v2/{kind}/{idOrName}` matches by either id or name;
92
+ // confirm it was an *id* match so crawlee can fall through to `{ name }`.
93
+ const info = await this.resourceClient(id, type).get();
94
+ return info?.id === id;
95
+ }
96
+ async createDatasetBackend(options) {
97
+ const id = await this.resolveId(options, 'Dataset');
98
+ return new ApifyDatasetBackend(this.#client.dataset(id));
99
+ }
100
+ async createKeyValueStoreBackend(options) {
101
+ const id = await this.resolveId(options, 'KeyValueStore');
102
+ return new ApifyKeyValueStoreBackend(this.#client.keyValueStore(id));
103
+ }
104
+ async createRequestQueueBackend(options) {
105
+ const id = await this.resolveId(options, 'RequestQueue');
106
+ const client = this.#client.requestQueue(id, { clientKey: this.requestQueueClientKey() });
107
+ return this.#requestQueueAccess === 'shared'
108
+ ? new ApifyRequestQueueSharedBackend(client)
109
+ : new ApifyRequestQueueSingleBackend(client);
110
+ }
111
+ /**
112
+ * A stable per-run client key makes the API's `hadMultipleClients` flag meaningful and lets a
113
+ * migrated or resurrected run re-acquire the request locks of its previous incarnation.
114
+ */
115
+ requestQueueClientKey() {
116
+ const key = this.#config?.actorRunId ?? (this.#fallbackClientKey ??= cryptoRandomObjectId(MAX_CLIENT_KEY_LENGTH));
117
+ return key.slice(0, MAX_CLIENT_KEY_LENGTH);
118
+ }
119
+ /**
120
+ * Resolves a crawlee {@link StorageIdentifier} to a platform storage id.
121
+ *
122
+ * Aliases resolve to unnamed storages: the reserved `__default__` alias maps to the run's
123
+ * default storage, and an alias declared in the Actor's schema to the storage the platform
124
+ * created for it (via the `ACTOR_STORAGES_JSON` environment variable). Any other alias gets an
125
+ * unnamed storage of its own — crawlee mints aliases at runtime, one per extra crawler instance
126
+ * and one per throttled domain, so an undeclared alias is not an error.
127
+ */
128
+ async resolveId(options, type) {
129
+ if (options?.id)
130
+ return options.id;
131
+ if (options?.name) {
132
+ return (await this.collectionClient(type).getOrCreate(options.name)).id;
133
+ }
134
+ const alias = (options && 'alias' in options && options.alias) || DEFAULT_STORAGE_ALIAS;
135
+ if (alias === DEFAULT_STORAGE_ALIAS) {
136
+ const defaultId = this.#config?.[DEFAULT_ID_CONFIG_KEY[type]];
137
+ if (defaultId)
138
+ return defaultId;
139
+ }
140
+ return this.resolveAliasId(alias, type);
141
+ }
142
+ /**
143
+ * Returns the unnamed storage backing `alias`, creating it on first use.
144
+ *
145
+ * On the platform the mapping is persisted, so a migrated run reopens the same storages rather
146
+ * than empty ones — aliased request queues hold live requests. Serialized, so one alias means
147
+ * one storage and the mapping's read-modify-write cannot drop entries.
148
+ */
149
+ async resolveAliasId(alias, type) {
150
+ // The credentials are part of the key, so the same alias opened through two
151
+ // differently-authenticated backends maps to two storages. The platform issues a new run token
152
+ // on migration, reboot and resurrection, so the run's own token is identified by its user.
153
+ const runUserId = this.#client.token === this.#config?.token ? this.#config?.userId : undefined;
154
+ const key = [type, alias, this.credentialsHash(runUserId)].join(',');
155
+ return this.#aliasLock.runExclusive(async () => {
156
+ const store = this.aliasMappingStore();
157
+ this.#persistedAliasIds ??= store ? await readAliasMapping(store) : {};
158
+ // A known id can point at a storage deleted since it was resolved. The persisted id wins
159
+ // over the declared one, as it only exists if the declared storage was gone.
160
+ const knownId = this.#aliasIdCache.get(key) ?? this.#persistedAliasIds[key] ?? this.aliasFromActorStorages(alias, type);
161
+ if (knownId && (await this.resourceClient(knownId, type).get())) {
162
+ this.#aliasIdCache.set(key, knownId);
163
+ return knownId;
164
+ }
165
+ const { id } = await this.collectionClient(type).getOrCreate();
166
+ this.#aliasIdCache.set(key, id);
167
+ if (store)
168
+ await this.persistAliasId(store, key, id);
169
+ return id;
170
+ });
171
+ }
172
+ /**
173
+ * Re-reads the record first, so a second backend in this process does not drop its entries.
174
+ * Logged rather than thrown: a lost entry only costs a re-created storage after a migration.
175
+ */
176
+ async persistAliasId(store, key, id) {
177
+ try {
178
+ const mapping = await readAliasMapping(store);
179
+ mapping[key] = id;
180
+ await store.setRecord({ key: ALIAS_MAPPING_RECORD_KEY, value: mapping });
181
+ this.#persistedAliasIds = mapping;
182
+ }
183
+ catch (error) {
184
+ log.warning(`Failed to persist the storage alias mapping: ${error.message}`);
185
+ }
186
+ }
187
+ /** The run's default key-value store, where the mapping lives — `undefined` off the platform. */
188
+ aliasMappingStore() {
189
+ return this.#config?.isAtHome ? this.#client.keyValueStore(this.#config.defaultKeyValueStoreId) : undefined;
190
+ }
191
+ /** Looks an alias up in the Actor's schema storages (the `ACTOR_STORAGES_JSON` env var). */
192
+ aliasFromActorStorages(alias, type) {
193
+ const storagesJson = this.#config?.actorStoragesJson;
194
+ if (!storagesJson)
195
+ return undefined;
196
+ let storages;
197
+ try {
198
+ storages = JSON.parse(storagesJson);
199
+ }
200
+ catch {
201
+ throw new Error(`Failed to parse ACTOR_STORAGES_JSON environment variable: ${storagesJson}`);
202
+ }
203
+ return storages[ACTOR_STORAGES_TYPE_KEY[type]]?.[alias];
204
+ }
205
+ resourceClient(id, type) {
206
+ if (type === 'Dataset')
207
+ return this.#client.dataset(id);
208
+ if (type === 'KeyValueStore')
209
+ return this.#client.keyValueStore(id);
210
+ return this.#client.requestQueue(id);
211
+ }
212
+ collectionClient(type) {
213
+ if (type === 'Dataset')
214
+ return this.#client.datasets();
215
+ if (type === 'KeyValueStore')
216
+ return this.#client.keyValueStores();
217
+ return this.#client.requestQueues();
218
+ }
219
+ }
@@ -1,5 +1,7 @@
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
+ /** Key of the default key-value store record that carries the charged event counts across a container restart. */
4
+ export declare const CHARGING_STATE_KEY = "APIFY_ACTOR_CHARGING_STATE";
3
5
  export declare const DEFAULT_DATASET_ITEM_EVENT = "apify-default-dataset-item";
4
6
  export interface ChargeOptions {
5
7
  /**
@@ -12,6 +14,19 @@ export interface ChargeOptions {
12
14
  * @default 1
13
15
  */
14
16
  count?: number;
17
+ /**
18
+ * A unique key preventing a retried operation from being charged for twice - e.g. a request handler rerun by a retry.
19
+ * A repeat under the same key within three minutes is not sent to the API and reports the `chargedCount` of
20
+ * the original call, or zero if it names a different event. Like the platform, the key is forgotten afterwards.
21
+ * In a multi-tenant Server Actor run, every call is sent and the platform deduplicates it.
22
+ */
23
+ idempotencyKey?: string;
24
+ /**
25
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
26
+ * 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.
27
+ * Ignored elsewhere.
28
+ */
29
+ requestId?: string;
15
30
  }
16
31
  export interface ChargeResult {
17
32
  /**
@@ -49,33 +64,32 @@ export interface ActorPricingInfo {
49
64
  isPayPerEvent: boolean;
50
65
  perEventPrices: Record<string, number>;
51
66
  }
52
- export declare function mergeChargeResults(a: ChargeResult, b: ChargeResult): ChargeResult;
53
67
  /**
54
68
  * Handles pay-per-event charging.
55
69
  */
56
70
  export declare class ChargingManager {
57
- private configuration;
58
- private readonly LOCAL_CHARGING_LOG_DATASET_NAME;
59
- private readonly PLATFORM_CHARGING_LOG_DATASET_ID_KEY;
60
- private maxTotalChargeUsd;
61
- private isAtHome;
62
- private actorRunId?;
63
- private pricingModel?;
64
- private purgeChargingLogDataset;
65
- private useChargingLogDataset;
66
- private notPpeWarningPrinted;
67
- private pricingInfo;
68
- private chargingState?;
69
- private chargingLogDataset?;
70
- private apifyClient;
71
- constructor(configuration: Configuration, apifyClient: ApifyClient);
72
- private get isPayPerEvent();
71
+ #private;
72
+ constructor(configuration: Configuration, apifyClient: ApifyClient, getCurrentRun: () => Promise<ClientActorRun | undefined>, getCurrentActor: () => Promise<ActorResource | undefined>);
73
+ /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
74
+ get isPayPerEvent(): boolean;
75
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
76
+ get isMultiTenant(): boolean;
73
77
  private fetchPricingInfo;
74
78
  /**
75
79
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
76
80
  */
77
81
  init(): Promise<void>;
78
- private ensureChargingLogDatasetOnPlatform;
82
+ /**
83
+ * Persist the charged event counts one last time and stop listening for the persist state events.
84
+ *
85
+ * @internal
86
+ */
87
+ teardown(): Promise<void>;
88
+ /**
89
+ * Whether {@link ChargingManager.init} has run. All charging operations (including
90
+ * {@link ChargingManager.getPricingInfo}) require an initialized manager.
91
+ */
92
+ get isInitialized(): boolean;
79
93
  /**
80
94
  * Get information about the pricing for this Actor.
81
95
  */
@@ -94,9 +108,21 @@ export declare class ChargingManager {
94
108
  * rather than batching via `count` — this gives finer control over budget consumption
95
109
  * and avoids situations where more work is requested than the budget allows.
96
110
  *
111
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
112
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
113
+ * be globally unique (e.g. derived from `requestId`).
114
+ *
97
115
  * @param options The name of the event to charge for and the number of events to be charged.
98
116
  */
99
- charge({ eventName, count }: ChargeOptions): Promise<ChargeResult>;
117
+ charge({ eventName, count, idempotencyKey, requestId }: ChargeOptions): Promise<ChargeResult>;
118
+ /**
119
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
120
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
121
+ * run, even by another caller.
122
+ */
123
+ private chargeServerRequest;
124
+ private getIdempotentCharge;
125
+ private setIdempotentCharge;
100
126
  /**
101
127
  * Get the number of events with given name that the Actor has charged for so far.
102
128
  */
@@ -114,31 +140,35 @@ export declare class ChargingManager {
114
140
  private calculateEventPrice;
115
141
  private calculateMaxChargesByPrice;
116
142
  /**
117
- * Helper to calculate how many items can be pushed within charging limits.
118
- * Returns the limited items and count to charge.
119
- */
120
- calculatePushDataLimits<T>({ items, eventName, isDefaultDataset, }: {
121
- items: T | T[];
122
- eventName: string | undefined;
123
- isDefaultDataset: boolean;
124
- }): {
125
- limitedItems: T[];
126
- eventsToCharge: Record<string, number>;
127
- };
143
+ * Whether the remaining budget is insufficient to charge even a single event of the given type.
144
+ * Always false when nothing is charged in the first place.
145
+ */
146
+ isEventChargeLimitReached(eventName: string): boolean;
147
+ /**
148
+ * How many events of each known type can still be charged within the limit.
149
+ */
150
+ calculateChargeableWithinLimit(): Record<string, number>;
151
+ /**
152
+ * How many of `itemsCount` items may be pushed to a dataset within the remaining budget.
153
+ *
154
+ * The budget is measured against the combined per-item price of the explicit `eventName` and - on
155
+ * the default dataset - the synthetic {@link DEFAULT_DATASET_ITEM_EVENT}, since pushing one item
156
+ * charges both.
157
+ *
158
+ * When the budget cannot cover a single item, one item is still allowed through so that the
159
+ * resulting overcharge makes the platform terminate the run - unless the run is already strictly
160
+ * over budget, in which case nothing is allowed through.
161
+ */
162
+ calculatePushDataLimit(itemsCount: number, { eventName, isDefaultDataset }?: {
163
+ eventName?: string;
164
+ isDefaultDataset?: boolean;
165
+ }): number;
166
+ /**
167
+ * Runs `fn` under the charge lock, which keeps a limit reservation and the charge that acts on it
168
+ * atomic against concurrent pushes. Only pay-per-event runs charge anything, so for every other
169
+ * run there is nothing to serialize and the lock is skipped.
170
+ *
171
+ * @internal
172
+ */
173
+ withChargeLock<T>(fn: () => Promise<T>): Promise<T>;
128
174
  }
129
- /**
130
- * Helper for PPE-aware pushing of data to the dataset.
131
- *
132
- * 1. Calculate limits based on budget
133
- * 2. Push limited items via the provided callback
134
- * 3. Charge for the events
135
- *
136
- * @internal
137
- */
138
- export declare function pushDataAndCharge<T>({ chargingManager, items, eventName, isDefaultDataset, pushFn, }: {
139
- chargingManager: ChargingManager;
140
- items: T | T[];
141
- eventName: string | undefined;
142
- isDefaultDataset: boolean;
143
- pushFn: (limitedItems: T | T[]) => Promise<void>;
144
- }): Promise<ChargeResult>;