apify 3.7.3-beta.96 → 4.0.0-beta.100
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/README.md +1 -1
- package/dist/actor.d.ts +379 -139
- package/dist/actor.js +764 -500
- package/dist/apify_dataset_backend.d.ts +19 -0
- package/dist/apify_dataset_backend.js +77 -0
- package/dist/apify_file_system_storage_backend.d.ts +34 -0
- package/dist/apify_file_system_storage_backend.js +41 -0
- package/dist/apify_key_value_store_backend.d.ts +23 -0
- package/dist/apify_key_value_store_backend.js +56 -0
- package/dist/apify_request_queue_backend.d.ts +78 -0
- package/dist/apify_request_queue_backend.js +114 -0
- package/dist/apify_request_queue_shared_backend.d.ts +31 -0
- package/dist/apify_request_queue_shared_backend.js +193 -0
- package/dist/apify_request_queue_single_backend.d.ts +43 -0
- package/dist/apify_request_queue_single_backend.js +256 -0
- package/dist/apify_storage_backend.d.ts +90 -0
- package/dist/apify_storage_backend.js +210 -0
- package/dist/charging.d.ts +39 -44
- package/dist/charging.js +245 -292
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +105 -0
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +85 -144
- package/dist/configuration.js +138 -174
- package/dist/enqueue_links_filters.d.ts +29 -0
- package/dist/enqueue_links_filters.js +52 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +22 -0
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +12 -22
- package/dist/input-schemas.d.ts +1 -1
- package/dist/input-schemas.js +12 -18
- package/dist/platform_event_manager.d.ts +15 -10
- package/dist/platform_event_manager.js +193 -63
- package/dist/proxy_configuration.d.ts +52 -72
- package/dist/proxy_configuration.js +176 -221
- package/dist/smart_apify_storage_backend.d.ts +52 -0
- package/dist/smart_apify_storage_backend.js +73 -0
- package/dist/storage.d.ts +6 -24
- package/dist/storage.js +1 -79
- package/dist/utils.d.ts +30 -0
- package/dist/utils.js +81 -23
- package/package.json +38 -43
- package/dist/index.mjs +0 -19
- package/dist/key_value_store.d.ts +0 -16
- package/dist/key_value_store.js +0 -40
- package/dist/patched_apify_client.d.ts +0 -25
- package/dist/patched_apify_client.js +0 -75
|
@@ -0,0 +1,210 @@
|
|
|
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 = '__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
|
+
* `Actor` wires this up automatically; construct it directly only to use Apify
|
|
36
|
+
* platform storage with crawlee's storage classes outside of `Actor` — e.g. to
|
|
37
|
+
* read another run's output with an explicit token:
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { ApifyClient, ApifyStorageBackend, Dataset } from 'apify';
|
|
41
|
+
*
|
|
42
|
+
* const client = new ApifyClient({ token });
|
|
43
|
+
* const dataset = await Dataset.open(datasetId, { storageBackend: new ApifyStorageBackend(client) });
|
|
44
|
+
* const { items } = await dataset.getData();
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export class ApifyStorageBackend {
|
|
48
|
+
#client;
|
|
49
|
+
#config;
|
|
50
|
+
#requestQueueAccess;
|
|
51
|
+
/** Unnamed storages resolved for aliases in this process, keyed like {@link AliasMapping}. */
|
|
52
|
+
#aliasIdCache = new Map();
|
|
53
|
+
/** The alias mapping read from the run's default key-value store; `undefined` until first read. */
|
|
54
|
+
#persistedAliasIds;
|
|
55
|
+
/** Serializes alias resolution — see `resolveAliasId`. */
|
|
56
|
+
#aliasLock = new AsyncLock();
|
|
57
|
+
/** Fallback request queue client key when the run id is unavailable — one per backend. */
|
|
58
|
+
#fallbackClientKey;
|
|
59
|
+
constructor(client, options = {}) {
|
|
60
|
+
this.#client = client;
|
|
61
|
+
this.#config = options.configuration;
|
|
62
|
+
this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Partitions crawlee's storage-instance cache by API base URL and token, so the same storage
|
|
66
|
+
* opened through two differently-authenticated backends is cached separately. The request
|
|
67
|
+
* queue access mode is deliberately not part of the key — opening the same queue in `single`
|
|
68
|
+
* and `shared` mode at once is not supported, and whichever backend opens it first wins.
|
|
69
|
+
*/
|
|
70
|
+
getStorageBackendCacheKey() {
|
|
71
|
+
return `ApifyStorageBackend:${this.credentialsHash()}`;
|
|
72
|
+
}
|
|
73
|
+
/** Short digest of the API base URL and token — identifies the credentials a storage was opened with. */
|
|
74
|
+
credentialsHash() {
|
|
75
|
+
return createHash('sha256')
|
|
76
|
+
.update(`${this.#client.publicBaseUrl}${this.#client.token ?? ''}`)
|
|
77
|
+
.digest('hex')
|
|
78
|
+
.slice(0, 8);
|
|
79
|
+
}
|
|
80
|
+
async storageExists(id, type) {
|
|
81
|
+
// Lets `Dataset.open(idOrName)` and friends resolve a string to an id first (when one
|
|
82
|
+
// exists on the platform) and fall back to a name otherwise; without this, crawlee would
|
|
83
|
+
// treat every string as a name and silently create a new storage named like the passed id.
|
|
84
|
+
// Apify's `GET /v2/{kind}/{idOrName}` matches by either id or name;
|
|
85
|
+
// confirm it was an *id* match so crawlee can fall through to `{ name }`.
|
|
86
|
+
const info = await this.resourceClient(id, type).get();
|
|
87
|
+
return info?.id === id;
|
|
88
|
+
}
|
|
89
|
+
async createDatasetBackend(options) {
|
|
90
|
+
const id = await this.resolveId(options, 'Dataset');
|
|
91
|
+
return new ApifyDatasetBackend(this.#client.dataset(id));
|
|
92
|
+
}
|
|
93
|
+
async createKeyValueStoreBackend(options) {
|
|
94
|
+
const id = await this.resolveId(options, 'KeyValueStore');
|
|
95
|
+
return new ApifyKeyValueStoreBackend(this.#client.keyValueStore(id));
|
|
96
|
+
}
|
|
97
|
+
async createRequestQueueBackend(options) {
|
|
98
|
+
const id = await this.resolveId(options, 'RequestQueue');
|
|
99
|
+
const client = this.#client.requestQueue(id, { clientKey: this.requestQueueClientKey() });
|
|
100
|
+
return this.#requestQueueAccess === 'shared'
|
|
101
|
+
? new ApifyRequestQueueSharedBackend(client)
|
|
102
|
+
: new ApifyRequestQueueSingleBackend(client);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A stable per-run client key makes the API's `hadMultipleClients` flag meaningful and lets a
|
|
106
|
+
* migrated or resurrected run re-acquire the request locks of its previous incarnation.
|
|
107
|
+
*/
|
|
108
|
+
requestQueueClientKey() {
|
|
109
|
+
const key = this.#config?.actorRunId ?? (this.#fallbackClientKey ??= cryptoRandomObjectId(MAX_CLIENT_KEY_LENGTH));
|
|
110
|
+
return key.slice(0, MAX_CLIENT_KEY_LENGTH);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Resolves a crawlee {@link StorageIdentifier} to a platform storage id.
|
|
114
|
+
*
|
|
115
|
+
* Aliases resolve to unnamed storages: the reserved `__default__` alias maps to the run's
|
|
116
|
+
* default storage, and an alias declared in the Actor's schema to the storage the platform
|
|
117
|
+
* created for it (via the `ACTOR_STORAGES_JSON` environment variable). Any other alias gets an
|
|
118
|
+
* unnamed storage of its own — crawlee mints aliases at runtime, one per extra crawler instance
|
|
119
|
+
* and one per throttled domain, so an undeclared alias is not an error.
|
|
120
|
+
*/
|
|
121
|
+
async resolveId(options, type) {
|
|
122
|
+
if (options?.id)
|
|
123
|
+
return options.id;
|
|
124
|
+
if (options?.name) {
|
|
125
|
+
return (await this.collectionClient(type).getOrCreate(options.name)).id;
|
|
126
|
+
}
|
|
127
|
+
const alias = (options && 'alias' in options && options.alias) || DEFAULT_STORAGE_ALIAS;
|
|
128
|
+
if (alias === DEFAULT_STORAGE_ALIAS) {
|
|
129
|
+
const defaultId = this.#config?.[DEFAULT_ID_CONFIG_KEY[type]];
|
|
130
|
+
if (defaultId)
|
|
131
|
+
return defaultId;
|
|
132
|
+
}
|
|
133
|
+
return this.resolveAliasId(alias, type);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Returns the unnamed storage backing `alias`, creating it on first use.
|
|
137
|
+
*
|
|
138
|
+
* On the platform the mapping is persisted, so a migrated run reopens the same storages rather
|
|
139
|
+
* than empty ones — aliased request queues hold live requests. Serialized, so one alias means
|
|
140
|
+
* one storage and the mapping's read-modify-write cannot drop entries.
|
|
141
|
+
*/
|
|
142
|
+
async resolveAliasId(alias, type) {
|
|
143
|
+
// The credentials are part of the key, so the same alias opened through two
|
|
144
|
+
// differently-authenticated backends maps to two storages.
|
|
145
|
+
const key = [type, alias, this.credentialsHash()].join(',');
|
|
146
|
+
return this.#aliasLock.runExclusive(async () => {
|
|
147
|
+
const store = this.aliasMappingStore();
|
|
148
|
+
this.#persistedAliasIds ??= store ? await readAliasMapping(store) : {};
|
|
149
|
+
// A known id can point at a storage deleted since it was resolved. The persisted id wins
|
|
150
|
+
// over the declared one, as it only exists if the declared storage was gone.
|
|
151
|
+
const knownId = this.#aliasIdCache.get(key) ?? this.#persistedAliasIds[key] ?? this.aliasFromActorStorages(alias, type);
|
|
152
|
+
if (knownId && (await this.resourceClient(knownId, type).get())) {
|
|
153
|
+
this.#aliasIdCache.set(key, knownId);
|
|
154
|
+
return knownId;
|
|
155
|
+
}
|
|
156
|
+
const { id } = await this.collectionClient(type).getOrCreate();
|
|
157
|
+
this.#aliasIdCache.set(key, id);
|
|
158
|
+
if (store)
|
|
159
|
+
await this.persistAliasId(store, key, id);
|
|
160
|
+
return id;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Re-reads the record first, so a second backend in this process does not drop its entries.
|
|
165
|
+
* Logged rather than thrown: a lost entry only costs a re-created storage after a migration.
|
|
166
|
+
*/
|
|
167
|
+
async persistAliasId(store, key, id) {
|
|
168
|
+
try {
|
|
169
|
+
const mapping = await readAliasMapping(store);
|
|
170
|
+
mapping[key] = id;
|
|
171
|
+
await store.setRecord({ key: ALIAS_MAPPING_RECORD_KEY, value: mapping });
|
|
172
|
+
this.#persistedAliasIds = mapping;
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
log.warning(`Failed to persist the storage alias mapping: ${error.message}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** The run's default key-value store, where the mapping lives — `undefined` off the platform. */
|
|
179
|
+
aliasMappingStore() {
|
|
180
|
+
return this.#config?.isAtHome ? this.#client.keyValueStore(this.#config.defaultKeyValueStoreId) : undefined;
|
|
181
|
+
}
|
|
182
|
+
/** Looks an alias up in the Actor's schema storages (the `ACTOR_STORAGES_JSON` env var). */
|
|
183
|
+
aliasFromActorStorages(alias, type) {
|
|
184
|
+
const storagesJson = this.#config?.actorStoragesJson;
|
|
185
|
+
if (!storagesJson)
|
|
186
|
+
return undefined;
|
|
187
|
+
let storages;
|
|
188
|
+
try {
|
|
189
|
+
storages = JSON.parse(storagesJson);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new Error(`Failed to parse ACTOR_STORAGES_JSON environment variable: ${storagesJson}`);
|
|
193
|
+
}
|
|
194
|
+
return storages[ACTOR_STORAGES_TYPE_KEY[type]]?.[alias];
|
|
195
|
+
}
|
|
196
|
+
resourceClient(id, type) {
|
|
197
|
+
if (type === 'Dataset')
|
|
198
|
+
return this.#client.dataset(id);
|
|
199
|
+
if (type === 'KeyValueStore')
|
|
200
|
+
return this.#client.keyValueStore(id);
|
|
201
|
+
return this.#client.requestQueue(id);
|
|
202
|
+
}
|
|
203
|
+
collectionClient(type) {
|
|
204
|
+
if (type === 'Dataset')
|
|
205
|
+
return this.#client.datasets();
|
|
206
|
+
if (type === 'KeyValueStore')
|
|
207
|
+
return this.#client.keyValueStores();
|
|
208
|
+
return this.#client.requestQueues();
|
|
209
|
+
}
|
|
210
|
+
}
|
package/dist/charging.d.ts
CHANGED
|
@@ -13,7 +13,9 @@ export interface ChargeOptions {
|
|
|
13
13
|
*/
|
|
14
14
|
count?: number;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
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.
|
|
17
19
|
*/
|
|
18
20
|
idempotencyKey?: string;
|
|
19
21
|
}
|
|
@@ -53,27 +55,14 @@ export interface ActorPricingInfo {
|
|
|
53
55
|
isPayPerEvent: boolean;
|
|
54
56
|
perEventPrices: Record<string, number>;
|
|
55
57
|
}
|
|
56
|
-
export declare function mergeChargeResults(a: ChargeResult, b: ChargeResult): ChargeResult;
|
|
57
58
|
/**
|
|
58
59
|
* Handles pay-per-event charging.
|
|
59
60
|
*/
|
|
60
61
|
export declare class ChargingManager {
|
|
61
|
-
private
|
|
62
|
-
private readonly LOCAL_CHARGING_LOG_DATASET_NAME;
|
|
63
|
-
private readonly PLATFORM_CHARGING_LOG_DATASET_ID_KEY;
|
|
64
|
-
private maxTotalChargeUsd;
|
|
65
|
-
private isAtHome;
|
|
66
|
-
private actorRunId?;
|
|
67
|
-
private pricingModel?;
|
|
68
|
-
private purgeChargingLogDataset;
|
|
69
|
-
private useChargingLogDataset;
|
|
70
|
-
private notPpeWarningPrinted;
|
|
71
|
-
private pricingInfo;
|
|
72
|
-
private chargingState?;
|
|
73
|
-
private chargingLogDataset?;
|
|
74
|
-
private apifyClient;
|
|
62
|
+
#private;
|
|
75
63
|
constructor(configuration: Configuration, apifyClient: ApifyClient);
|
|
76
|
-
|
|
64
|
+
/** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
|
|
65
|
+
get isPayPerEvent(): boolean;
|
|
77
66
|
private fetchPricingInfo;
|
|
78
67
|
/**
|
|
79
68
|
* Initialize the ChargingManager by loading pricing information and charging state via Apify API.
|
|
@@ -106,6 +95,8 @@ export declare class ChargingManager {
|
|
|
106
95
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
107
96
|
*/
|
|
108
97
|
charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
|
|
98
|
+
private getIdempotentCharge;
|
|
99
|
+
private setIdempotentCharge;
|
|
109
100
|
/**
|
|
110
101
|
* Get the number of events with given name that the Actor has charged for so far.
|
|
111
102
|
*/
|
|
@@ -123,31 +114,35 @@ export declare class ChargingManager {
|
|
|
123
114
|
private calculateEventPrice;
|
|
124
115
|
private calculateMaxChargesByPrice;
|
|
125
116
|
/**
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*/
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
117
|
+
* Whether the remaining budget is insufficient to charge even a single event of the given type.
|
|
118
|
+
* Always false when nothing is charged in the first place.
|
|
119
|
+
*/
|
|
120
|
+
isEventChargeLimitReached(eventName: string): boolean;
|
|
121
|
+
/**
|
|
122
|
+
* How many events of each known type can still be charged within the limit.
|
|
123
|
+
*/
|
|
124
|
+
calculateChargeableWithinLimit(): Record<string, number>;
|
|
125
|
+
/**
|
|
126
|
+
* How many of `itemsCount` items may be pushed to a dataset within the remaining budget.
|
|
127
|
+
*
|
|
128
|
+
* The budget is measured against the combined per-item price of the explicit `eventName` and - on
|
|
129
|
+
* the default dataset - the synthetic {@link DEFAULT_DATASET_ITEM_EVENT}, since pushing one item
|
|
130
|
+
* charges both.
|
|
131
|
+
*
|
|
132
|
+
* When the budget cannot cover a single item, one item is still allowed through so that the
|
|
133
|
+
* resulting overcharge makes the platform terminate the run - unless the run is already strictly
|
|
134
|
+
* over budget, in which case nothing is allowed through.
|
|
135
|
+
*/
|
|
136
|
+
calculatePushDataLimit(itemsCount: number, { eventName, isDefaultDataset }?: {
|
|
137
|
+
eventName?: string;
|
|
138
|
+
isDefaultDataset?: boolean;
|
|
139
|
+
}): number;
|
|
140
|
+
/**
|
|
141
|
+
* Runs `fn` under the charge lock, which keeps a limit reservation and the charge that acts on it
|
|
142
|
+
* atomic against concurrent pushes. Only pay-per-event runs charge anything, so for every other
|
|
143
|
+
* run there is nothing to serialize and the lock is skipped.
|
|
144
|
+
*
|
|
145
|
+
* @internal
|
|
146
|
+
*/
|
|
147
|
+
withChargeLock<T>(fn: () => Promise<T>): Promise<T>;
|
|
137
148
|
}
|
|
138
|
-
/**
|
|
139
|
-
* Helper for PPE-aware pushing of data to the dataset.
|
|
140
|
-
*
|
|
141
|
-
* 1. Calculate limits based on budget
|
|
142
|
-
* 2. Push limited items via the provided callback
|
|
143
|
-
* 3. Charge for the events
|
|
144
|
-
*
|
|
145
|
-
* @internal
|
|
146
|
-
*/
|
|
147
|
-
export declare function pushDataAndCharge<T>({ chargingManager, items, eventName, isDefaultDataset, pushFn, }: {
|
|
148
|
-
chargingManager: ChargingManager;
|
|
149
|
-
items: T | T[];
|
|
150
|
-
eventName: string | undefined;
|
|
151
|
-
isDefaultDataset: boolean;
|
|
152
|
-
pushFn: (limitedItems: T | T[]) => Promise<void>;
|
|
153
|
-
}): Promise<ChargeResult>;
|