apify 4.0.0-beta.13 → 4.0.0-beta.130
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 +24 -2
- package/dist/actor.d.ts +391 -279
- package/dist/actor.js +732 -415
- 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 +69 -46
- package/dist/charging.js +326 -208
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +109 -0
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +49 -28
- package/dist/configuration.js +67 -12
- 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 +11 -4
- package/dist/index.js +8 -3
- package/dist/input-schemas.d.ts +1 -1
- package/dist/platform_event_manager.d.ts +15 -5
- package/dist/platform_event_manager.js +185 -39
- package/dist/proxy_configuration.d.ts +31 -21
- package/dist/proxy_configuration.js +136 -79
- 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 -26
- package/dist/storage.js +1 -79
- package/dist/utils.d.ts +28 -3
- package/dist/utils.js +59 -17
- package/package.json +38 -44
- package/dist/apify_storage_client.d.ts +0 -54
- package/dist/apify_storage_client.js +0 -152
- package/dist/key_value_store.d.ts +0 -21
- package/dist/key_value_store.js +0 -41
package/dist/actor.js
CHANGED
|
@@ -1,21 +1,40 @@
|
|
|
1
1
|
import { createPrivateKey } from 'node:crypto';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
|
|
5
|
+
import { sleep } from '@crawlee/utils';
|
|
4
6
|
import { ApifyClient } from 'apify-client';
|
|
5
|
-
import
|
|
6
|
-
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS,
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, META_ORIGINS } from '@apify/consts';
|
|
7
9
|
import { decryptInputSecrets } from '@apify/input_secrets';
|
|
8
10
|
import log from '@apify/log';
|
|
9
11
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
+
import { parseArgument } from '@apify/validations';
|
|
13
|
+
import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
|
|
14
|
+
import { ApifyStorageBackend } from './apify_storage_backend.js';
|
|
15
|
+
import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
|
|
16
|
+
import { ChargingStorageBackend } from './charging_storage_backend.js';
|
|
17
|
+
import { ChildRunTracker } from './child_run_tracker.js';
|
|
12
18
|
import { Configuration } from './configuration.js';
|
|
19
|
+
import { ActorInputError } from './errors.js';
|
|
20
|
+
import { fixGoogleSheetsUrls } from './google_sheets.js';
|
|
13
21
|
import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
|
|
14
|
-
import { KeyValueStore } from './key_value_store.js';
|
|
15
22
|
import { PlatformEventManager } from './platform_event_manager.js';
|
|
16
23
|
import { ProxyConfiguration } from './proxy_configuration.js';
|
|
17
|
-
import {
|
|
18
|
-
import { checkCrawleeVersion, getSystemInfo,
|
|
24
|
+
import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
|
|
25
|
+
import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, } from './utils.js';
|
|
26
|
+
/**
|
|
27
|
+
* {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
|
|
28
|
+
* JSON input reports where it came from.
|
|
29
|
+
*/
|
|
30
|
+
function parseInput(value, contentType, source) {
|
|
31
|
+
try {
|
|
32
|
+
return parseInputValue(value, contentType);
|
|
33
|
+
}
|
|
34
|
+
catch (cause) {
|
|
35
|
+
throw new ActorInputError('PARSE_FAILED', `The input in ${source} is not valid JSON.`, { cause });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
19
38
|
/**
|
|
20
39
|
* Exit codes for the Actor process.
|
|
21
40
|
* The error codes must be in the range 1-128, to avoid collision with signal exits
|
|
@@ -34,12 +53,13 @@ export const EXIT_CODES = {
|
|
|
34
53
|
*/
|
|
35
54
|
export class Actor {
|
|
36
55
|
/** @internal */
|
|
37
|
-
static
|
|
56
|
+
static #instance;
|
|
57
|
+
#childRunTracker;
|
|
38
58
|
/**
|
|
39
59
|
* Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
|
|
40
60
|
* @internal
|
|
41
61
|
*/
|
|
42
|
-
|
|
62
|
+
configuration;
|
|
43
63
|
/**
|
|
44
64
|
* Default {@link ApifyClient} instance.
|
|
45
65
|
* @internal
|
|
@@ -58,26 +78,34 @@ export class Actor {
|
|
|
58
78
|
* Set if the Actor called a method that requires the instance to be initialized, but did not do so.
|
|
59
79
|
* A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
|
|
60
80
|
*/
|
|
61
|
-
warnedAboutMissingInitCall = false;
|
|
81
|
+
#warnedAboutMissingInitCall = false;
|
|
62
82
|
/**
|
|
63
83
|
* Set if the Actor is currently rebooting.
|
|
64
84
|
*/
|
|
65
|
-
isRebooting = false;
|
|
85
|
+
#isRebooting = false;
|
|
66
86
|
/**
|
|
67
87
|
* Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
|
|
68
88
|
*/
|
|
69
|
-
isExiting = false;
|
|
89
|
+
#isExiting = false;
|
|
70
90
|
/**
|
|
71
91
|
* References to graceful shutdown handlers so they can be removed during cleanup.
|
|
72
92
|
*/
|
|
73
|
-
gracefulShutdownHandlers = {};
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
93
|
+
#gracefulShutdownHandlers = {};
|
|
94
|
+
/**
|
|
95
|
+
* Reference to the crawlee status message forwarder, so it can be removed during cleanup.
|
|
96
|
+
*/
|
|
97
|
+
#statusMessageForwarder;
|
|
98
|
+
#chargingManager;
|
|
99
|
+
#runPromise;
|
|
100
|
+
#actorPromise;
|
|
101
|
+
/** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
|
|
102
|
+
#abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
|
|
103
|
+
/** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
|
|
104
|
+
#requestQueueAccess = 'single';
|
|
105
|
+
/** Lazily built by the `#storageBackend` getter. */
|
|
106
|
+
#cachedStorageBackend;
|
|
107
|
+
/** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
|
|
108
|
+
#pendingListeners = [];
|
|
81
109
|
constructor(options = {}) {
|
|
82
110
|
const { configuration, ...configOptions } = options;
|
|
83
111
|
if (configuration) {
|
|
@@ -91,18 +119,21 @@ export class Actor {
|
|
|
91
119
|
throw new Error('Actor `configuration` must be an Apify SDK Configuration (imported from `apify`), ' +
|
|
92
120
|
'not a crawlee Configuration, otherwise APIFY_*/ACTOR_* environment variables are not resolved.');
|
|
93
121
|
}
|
|
94
|
-
this.
|
|
122
|
+
this.configuration = configuration;
|
|
95
123
|
}
|
|
96
124
|
else if (Object.keys(configOptions).length === 0) {
|
|
97
125
|
// use default configuration object if nothing overridden (it fallbacks to env vars)
|
|
98
|
-
this.
|
|
126
|
+
this.configuration = Configuration.getGlobalConfiguration();
|
|
99
127
|
}
|
|
100
128
|
else {
|
|
101
|
-
this.
|
|
129
|
+
this.configuration = new Configuration(configOptions);
|
|
102
130
|
}
|
|
103
131
|
this.apifyClient = this.newClient();
|
|
104
|
-
this.eventManager = new PlatformEventManager(this.
|
|
105
|
-
|
|
132
|
+
this.eventManager = new PlatformEventManager(this.configuration, {
|
|
133
|
+
[ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
|
|
134
|
+
});
|
|
135
|
+
this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
|
|
136
|
+
this.#childRunTracker = new ChildRunTracker();
|
|
106
137
|
}
|
|
107
138
|
/**
|
|
108
139
|
* Runs the main user function that performs the job of the Actor
|
|
@@ -139,24 +170,22 @@ export class Actor {
|
|
|
139
170
|
*
|
|
140
171
|
* If the user function returns a promise, it is considered asynchronous:
|
|
141
172
|
* ```js
|
|
142
|
-
* import { gotScraping } from 'got-scraping';
|
|
143
|
-
*
|
|
144
173
|
* await Actor.main(() => {
|
|
145
174
|
* // My asynchronous function that returns a promise
|
|
146
|
-
* return
|
|
147
|
-
*
|
|
148
|
-
*
|
|
175
|
+
* return fetch('http://www.example.com')
|
|
176
|
+
* .then((response) => response.text())
|
|
177
|
+
* .then((html) => {
|
|
178
|
+
* console.log(html);
|
|
179
|
+
* });
|
|
149
180
|
* });
|
|
150
181
|
* ```
|
|
151
182
|
*
|
|
152
183
|
* To simplify your code, you can take advantage of the `async`/`await` keywords:
|
|
153
184
|
*
|
|
154
185
|
* ```js
|
|
155
|
-
* import { gotScraping } from 'got-scraping';
|
|
156
|
-
*
|
|
157
186
|
* await Actor.main(async () => {
|
|
158
187
|
* // My asynchronous function
|
|
159
|
-
* const html = await
|
|
188
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
160
189
|
* console.log(html);
|
|
161
190
|
* });
|
|
162
191
|
* ```
|
|
@@ -179,9 +208,7 @@ export class Actor {
|
|
|
179
208
|
}
|
|
180
209
|
catch (err) {
|
|
181
210
|
log.exception(err, err.message);
|
|
182
|
-
await this.exit({
|
|
183
|
-
exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW,
|
|
184
|
-
});
|
|
211
|
+
await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
|
|
185
212
|
}
|
|
186
213
|
return ret;
|
|
187
214
|
})();
|
|
@@ -195,7 +222,7 @@ export class Actor {
|
|
|
195
222
|
return;
|
|
196
223
|
}
|
|
197
224
|
// If the warning about forgotten init call was emitted, we will not continue the init procedure.
|
|
198
|
-
if (this
|
|
225
|
+
if (this.#warnedAboutMissingInitCall) {
|
|
199
226
|
throw new Error([
|
|
200
227
|
'Actor.init() was called after a method that would access a storage client was used.',
|
|
201
228
|
'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
|
|
@@ -204,62 +231,93 @@ export class Actor {
|
|
|
204
231
|
this.initialized = true;
|
|
205
232
|
checkCrawleeVersion();
|
|
206
233
|
log.info('System info', getSystemInfo());
|
|
207
|
-
printOutdatedSdkWarning();
|
|
208
234
|
// Register this Actor's config as the global one so crawlee storages and
|
|
209
235
|
// the event manager resolve the same instance (`availableMemoryRatio` /
|
|
210
236
|
// `disableBrowserSandbox` at-home defaults now live in `Configuration`).
|
|
211
|
-
serviceLocator.setConfiguration(this.
|
|
237
|
+
serviceLocator.setConfiguration(this.configuration);
|
|
238
|
+
this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
|
|
212
239
|
if (this.isAtHome()) {
|
|
213
|
-
serviceLocator.setStorageClient(new ApifyStorageClient(this.apifyClient, this.config, () => this.chargingManager));
|
|
214
240
|
serviceLocator.setEventManager(this.eventManager);
|
|
215
241
|
}
|
|
242
|
+
if (!serviceLocator.getServicesIfSet().storageBackend) {
|
|
243
|
+
this.installStorageBackend(options.storage ?? this.#storageBackend);
|
|
244
|
+
}
|
|
216
245
|
else if (options.storage) {
|
|
217
|
-
|
|
246
|
+
this.installStorageBackend(options.storage);
|
|
218
247
|
}
|
|
219
|
-
// Init the event manager the config uses
|
|
220
|
-
await serviceLocator.getEventManager().init();
|
|
221
|
-
log.debug(`Events initialized`);
|
|
222
248
|
// Register handlers for aborting and migrating events for automatic graceful shutdown.
|
|
223
249
|
// - aborting: calls Actor.exit() to terminate the run gracefully
|
|
224
250
|
// - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
|
|
225
251
|
// Using setTimeout to avoid deadlock with waitForAllListenersToComplete() in exit()/reboot()
|
|
226
252
|
if (options.gracefulShutdown !== false) {
|
|
227
253
|
const delay = options.gracefulShutdownDelayMillis ?? 0;
|
|
228
|
-
this
|
|
254
|
+
this.#gracefulShutdownHandlers.aborting = () => {
|
|
229
255
|
setTimeout(() => {
|
|
230
256
|
this.exit().catch((err) => {
|
|
231
257
|
log.exception(err, 'Failed to exit gracefully');
|
|
232
258
|
});
|
|
233
259
|
}, delay);
|
|
234
260
|
};
|
|
235
|
-
this.on(ACTOR_EVENT_NAMES.ABORTING, this
|
|
236
|
-
this
|
|
261
|
+
this.on(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
|
|
262
|
+
this.#gracefulShutdownHandlers.migrating = () => {
|
|
237
263
|
setTimeout(() => {
|
|
238
264
|
this.reboot().catch((err) => {
|
|
239
265
|
log.exception(err, 'Failed to reboot on migration');
|
|
240
266
|
});
|
|
241
267
|
}, delay);
|
|
242
268
|
};
|
|
243
|
-
this.on(ACTOR_EVENT_NAMES.MIGRATING, this
|
|
269
|
+
this.on(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
|
|
244
270
|
}
|
|
271
|
+
// Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
|
|
272
|
+
this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
|
|
273
|
+
this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
|
|
274
|
+
// Attach listeners queued before init(), then connect to the platform events only after all handlers
|
|
275
|
+
// are registered, so that an event sent right after the connection opens (e.g. an already pending
|
|
276
|
+
// `aborting`) is not missed.
|
|
277
|
+
const events = serviceLocator.getEventManager();
|
|
278
|
+
if (this.#pendingListeners.length > 0) {
|
|
279
|
+
for (const [event, listener] of this.#pendingListeners) {
|
|
280
|
+
events.on(event, listener);
|
|
281
|
+
}
|
|
282
|
+
log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
|
|
283
|
+
this.#pendingListeners = [];
|
|
284
|
+
}
|
|
285
|
+
await events.init();
|
|
286
|
+
log.debug(`Events initialized`);
|
|
245
287
|
await purgeDefaultStorages({
|
|
246
|
-
|
|
288
|
+
configuration: this.configuration,
|
|
247
289
|
onlyPurgeOnce: true,
|
|
248
290
|
});
|
|
249
291
|
log.debug(`Default storages purged`);
|
|
250
|
-
await this.
|
|
251
|
-
|
|
292
|
+
await this.#childRunTracker.load();
|
|
293
|
+
this.#runPromise = undefined;
|
|
294
|
+
this.#actorPromise = undefined;
|
|
295
|
+
if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
|
|
296
|
+
// Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
|
|
297
|
+
void this.getCurrentRun().catch(() => { });
|
|
298
|
+
void this.#getCurrentActor().catch(() => { });
|
|
299
|
+
}
|
|
300
|
+
await this.#chargingManager.init();
|
|
301
|
+
log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
|
|
302
|
+
// Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
|
|
303
|
+
// registered with crawlee directly; the storages the Actor installs itself are wrapped.
|
|
304
|
+
if (this.#chargingManager.isPayPerEvent &&
|
|
305
|
+
!this.#chargingManager.isMultiTenant &&
|
|
306
|
+
!this.#chargesDefaultDatasetItems()) {
|
|
307
|
+
log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
|
|
308
|
+
'storage - the platform only counts items it stores itself.');
|
|
309
|
+
}
|
|
252
310
|
}
|
|
253
311
|
/**
|
|
254
312
|
* @ignore
|
|
255
313
|
*/
|
|
256
314
|
async exit(messageOrOptions, options = {}) {
|
|
257
315
|
// Prevent double-exit from graceful shutdown handlers
|
|
258
|
-
if (this
|
|
316
|
+
if (this.#isExiting) {
|
|
259
317
|
log.debug('Actor.exit() called while already exiting, skipping');
|
|
260
318
|
return;
|
|
261
319
|
}
|
|
262
|
-
this
|
|
320
|
+
this.#isExiting = true;
|
|
263
321
|
options =
|
|
264
322
|
typeof messageOrOptions === 'string'
|
|
265
323
|
? { ...options, statusMessage: messageOrOptions }
|
|
@@ -267,21 +325,21 @@ export class Actor {
|
|
|
267
325
|
options.exit ??= true;
|
|
268
326
|
options.exitCode ??= EXIT_CODES.SUCCESS;
|
|
269
327
|
options.timeoutSecs ??= 30;
|
|
270
|
-
this.
|
|
271
|
-
const client = serviceLocator.
|
|
328
|
+
this.ensureActorInit('exit');
|
|
329
|
+
const client = serviceLocator.getStorageBackend();
|
|
272
330
|
const events = serviceLocator.getEventManager();
|
|
273
331
|
// Remove graceful shutdown handlers to prevent them from interfering with exit
|
|
274
|
-
if (this
|
|
275
|
-
this.off(ACTOR_EVENT_NAMES.ABORTING, this
|
|
332
|
+
if (this.#gracefulShutdownHandlers.aborting) {
|
|
333
|
+
this.off(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
|
|
276
334
|
}
|
|
277
|
-
if (this
|
|
278
|
-
this.off(ACTOR_EVENT_NAMES.MIGRATING, this
|
|
335
|
+
if (this.#gracefulShutdownHandlers.migrating) {
|
|
336
|
+
this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
|
|
279
337
|
}
|
|
280
338
|
// Close the event manager and emit the final PERSIST_STATE event
|
|
281
339
|
await events.close();
|
|
282
340
|
log.debug(`Events closed`);
|
|
283
341
|
// Emit the exit event
|
|
284
|
-
events.emit(
|
|
342
|
+
events.emit(EventType.EXIT, options);
|
|
285
343
|
// Wait for all event listeners to be processed
|
|
286
344
|
log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
|
|
287
345
|
if (options.exit) {
|
|
@@ -293,6 +351,11 @@ export class Actor {
|
|
|
293
351
|
}
|
|
294
352
|
await addTimeoutToPromise(async () => {
|
|
295
353
|
await events.waitForAllListenersToComplete();
|
|
354
|
+
// The final status messages have been forwarded by now; stop listening so
|
|
355
|
+
// that a periodic one can't overwrite the terminal message set below.
|
|
356
|
+
if (this.#statusMessageForwarder) {
|
|
357
|
+
this.off(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
|
|
358
|
+
}
|
|
296
359
|
if (client.teardown) {
|
|
297
360
|
let finished = false;
|
|
298
361
|
setTimeout(() => {
|
|
@@ -318,7 +381,7 @@ export class Actor {
|
|
|
318
381
|
});
|
|
319
382
|
// Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
|
|
320
383
|
// When process.exit() actually terminates the process, this line is never reached - which is fine.
|
|
321
|
-
this
|
|
384
|
+
this.#isExiting = false;
|
|
322
385
|
if (!options.exit) {
|
|
323
386
|
return;
|
|
324
387
|
}
|
|
@@ -328,18 +391,29 @@ export class Actor {
|
|
|
328
391
|
* @ignore
|
|
329
392
|
*/
|
|
330
393
|
async fail(messageOrOptions, options = {}) {
|
|
331
|
-
|
|
394
|
+
const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
|
|
395
|
+
return this.exit(messageOrOptions, { ...options, exitCode });
|
|
332
396
|
}
|
|
333
397
|
/**
|
|
334
398
|
* @ignore
|
|
335
399
|
*/
|
|
336
400
|
on(event, listener) {
|
|
401
|
+
// Before init() the service locator must stay untouched, otherwise it
|
|
402
|
+
// creates a default Configuration that init() then conflicts with.
|
|
403
|
+
if (!this.initialized) {
|
|
404
|
+
this.#pendingListeners.push([event, listener]);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
337
407
|
serviceLocator.getEventManager().on(event, listener);
|
|
338
408
|
}
|
|
339
409
|
/**
|
|
340
410
|
* @ignore
|
|
341
411
|
*/
|
|
342
412
|
off(event, listener) {
|
|
413
|
+
if (!this.initialized) {
|
|
414
|
+
this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
343
417
|
serviceLocator.getEventManager().off(event, listener);
|
|
344
418
|
}
|
|
345
419
|
/**
|
|
@@ -360,17 +434,33 @@ export class Actor {
|
|
|
360
434
|
* @param actorId
|
|
361
435
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
362
436
|
* @param [input]
|
|
363
|
-
* Input for the Actor.
|
|
364
|
-
*
|
|
365
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
437
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
438
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
366
439
|
* @param [options]
|
|
367
440
|
* @ignore
|
|
368
441
|
*/
|
|
369
442
|
async call(actorId, input, options = {}) {
|
|
370
|
-
const
|
|
371
|
-
const { token, ...rest } = options;
|
|
443
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
444
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
372
445
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
373
|
-
|
|
446
|
+
if (abortWithParent && !runName)
|
|
447
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
448
|
+
if (!runName)
|
|
449
|
+
return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
|
|
450
|
+
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
451
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
452
|
+
const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
453
|
+
// The earlier part of a resumed run's log was already redirected before the migration.
|
|
454
|
+
const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
|
|
455
|
+
streamedLog?.start();
|
|
456
|
+
try {
|
|
457
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
458
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
459
|
+
return finishedRun;
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
await streamedLog?.stop();
|
|
463
|
+
}
|
|
374
464
|
}
|
|
375
465
|
/**
|
|
376
466
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
@@ -390,17 +480,22 @@ export class Actor {
|
|
|
390
480
|
* @param actorId
|
|
391
481
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
392
482
|
* @param [input]
|
|
393
|
-
* Input for the Actor.
|
|
394
|
-
*
|
|
395
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
483
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
484
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
396
485
|
* @param [options]
|
|
397
486
|
* @ignore
|
|
398
487
|
*/
|
|
399
488
|
async start(actorId, input, options = {}) {
|
|
400
|
-
const
|
|
401
|
-
const { token, ...rest } = options;
|
|
489
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
490
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
402
491
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
403
|
-
|
|
492
|
+
if (abortWithParent && !runName)
|
|
493
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
494
|
+
if (!runName)
|
|
495
|
+
return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
|
|
496
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
497
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
498
|
+
return run;
|
|
404
499
|
}
|
|
405
500
|
/**
|
|
406
501
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -420,12 +515,35 @@ export class Actor {
|
|
|
420
515
|
async abort(runId, options = {}) {
|
|
421
516
|
const { token, statusMessage, ...rest } = options;
|
|
422
517
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
518
|
+
const runClient = client.run(runId);
|
|
423
519
|
if (statusMessage) {
|
|
424
|
-
await
|
|
425
|
-
isStatusMessageTerminal: true,
|
|
426
|
-
});
|
|
520
|
+
await runClient.update({ statusMessage, isStatusMessageTerminal: true });
|
|
427
521
|
}
|
|
428
|
-
return
|
|
522
|
+
return runClient.abort(rest);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
526
|
+
*
|
|
527
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
528
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
529
|
+
*
|
|
530
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
531
|
+
*
|
|
532
|
+
* For more information about Actors, read the
|
|
533
|
+
* [documentation](https://docs.apify.com/actor).
|
|
534
|
+
*
|
|
535
|
+
* **Example usage:**
|
|
536
|
+
*
|
|
537
|
+
* ```js
|
|
538
|
+
* const run = await Actor.resurrect(runId);
|
|
539
|
+
* ```
|
|
540
|
+
* @ignore
|
|
541
|
+
*/
|
|
542
|
+
async resurrect(runId, options = {}) {
|
|
543
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
544
|
+
const { token, timeout: _timeout, ...rest } = options;
|
|
545
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
546
|
+
return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
|
|
429
547
|
}
|
|
430
548
|
/**
|
|
431
549
|
* Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -454,10 +572,70 @@ export class Actor {
|
|
|
454
572
|
* @ignore
|
|
455
573
|
*/
|
|
456
574
|
async callTask(taskId, input, options = {}) {
|
|
457
|
-
const
|
|
458
|
-
const { token, ...rest } = options;
|
|
575
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
576
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
577
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
578
|
+
if (abortWithParent && !runName)
|
|
579
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
580
|
+
if (!runName)
|
|
581
|
+
return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
|
|
582
|
+
const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
583
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
584
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
585
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
586
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
587
|
+
return finishedRun;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
591
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
592
|
+
*
|
|
593
|
+
* ```js
|
|
594
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
595
|
+
* ```
|
|
596
|
+
*
|
|
597
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
598
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
599
|
+
* under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
|
|
600
|
+
*/
|
|
601
|
+
get childRuns() {
|
|
602
|
+
this.ensureActorInit('childRuns');
|
|
603
|
+
return this.#childRunTracker.getRunClients(this.apifyClient);
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
607
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
608
|
+
*
|
|
609
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
610
|
+
*
|
|
611
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
612
|
+
*
|
|
613
|
+
* **Example usage:**
|
|
614
|
+
*
|
|
615
|
+
* ```js
|
|
616
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
617
|
+
* ```
|
|
618
|
+
*
|
|
619
|
+
* @param taskId
|
|
620
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
621
|
+
* @param [input]
|
|
622
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
623
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
624
|
+
* Provided input will be merged with Actor task input.
|
|
625
|
+
* @param [options]
|
|
626
|
+
* @ignore
|
|
627
|
+
*/
|
|
628
|
+
async startTask(taskId, input, options = {}) {
|
|
629
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
630
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
459
631
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
460
|
-
|
|
632
|
+
if (abortWithParent && !runName)
|
|
633
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
634
|
+
if (!runName)
|
|
635
|
+
return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
|
|
636
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
637
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
638
|
+
return run;
|
|
461
639
|
}
|
|
462
640
|
/**
|
|
463
641
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
@@ -467,9 +645,8 @@ export class Actor {
|
|
|
467
645
|
* @param targetActorId
|
|
468
646
|
* Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
|
|
469
647
|
* @param [input]
|
|
470
|
-
* Input for the Actor.
|
|
471
|
-
*
|
|
472
|
-
* Otherwise, the `options.contentType` parameter must be provided.
|
|
648
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
649
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
473
650
|
* @param [options]
|
|
474
651
|
* @ignore
|
|
475
652
|
*/
|
|
@@ -478,8 +655,8 @@ export class Actor {
|
|
|
478
655
|
log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
|
|
479
656
|
return;
|
|
480
657
|
}
|
|
481
|
-
const { customAfterSleepMillis = this.
|
|
482
|
-
const runId = this.
|
|
658
|
+
const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
|
|
659
|
+
const runId = this.configuration.actorRunId;
|
|
483
660
|
await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
|
|
484
661
|
// Wait some time for container to be stopped.
|
|
485
662
|
await sleep(customAfterSleepMillis);
|
|
@@ -492,33 +669,47 @@ export class Actor {
|
|
|
492
669
|
* @ignore
|
|
493
670
|
*/
|
|
494
671
|
async reboot(options = {}) {
|
|
495
|
-
this.
|
|
672
|
+
this.ensureActorInit('reboot');
|
|
496
673
|
if (!this.isAtHome()) {
|
|
497
674
|
log.warning('Actor.reboot() is only supported when running on the Apify platform.');
|
|
498
675
|
return;
|
|
499
676
|
}
|
|
500
|
-
if (this
|
|
677
|
+
if (this.#isRebooting) {
|
|
501
678
|
log.debug('Actor is already rebooting, skipping the additional reboot call.');
|
|
502
679
|
return;
|
|
503
680
|
}
|
|
504
|
-
this
|
|
681
|
+
this.#isRebooting = true;
|
|
682
|
+
const { timeoutSecs = 30, customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
|
|
683
|
+
const callListeners = (event, data) => serviceLocator
|
|
684
|
+
.getEventManager()
|
|
685
|
+
.listeners(event)
|
|
686
|
+
.map(async (listener) => {
|
|
687
|
+
try {
|
|
688
|
+
await listener(data);
|
|
689
|
+
}
|
|
690
|
+
catch (err) {
|
|
691
|
+
log.exception(err, 'A pre-reboot event listener failed');
|
|
692
|
+
}
|
|
693
|
+
});
|
|
505
694
|
// Waiting for all the listeners to finish, as `.reboot()` kills the container.
|
|
506
|
-
await
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
.
|
|
510
|
-
|
|
511
|
-
.
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
695
|
+
await addTimeoutToPromise(async () => {
|
|
696
|
+
await Promise.all([
|
|
697
|
+
// `persistState` for individual RequestLists, RequestQueue... instances to be persisted
|
|
698
|
+
...callListeners(EventType.PERSIST_STATE, { isMigrating: true }),
|
|
699
|
+
// `migrating` to pause Apify crawlers
|
|
700
|
+
...callListeners(EventType.MIGRATING, {}),
|
|
701
|
+
]);
|
|
702
|
+
}, timeoutSecs * 1000, `Pre-reboot event listeners did not finish within ${timeoutSecs} seconds, proceeding with the reboot`).catch((err) => log.warning(err.message));
|
|
703
|
+
const runId = this.configuration.actorRunId;
|
|
704
|
+
try {
|
|
705
|
+
await this.apifyClient.run(runId).reboot();
|
|
706
|
+
}
|
|
707
|
+
catch (err) {
|
|
708
|
+
// Reset the flag so that a failed reboot can be retried.
|
|
709
|
+
this.#isRebooting = false;
|
|
710
|
+
throw err;
|
|
711
|
+
}
|
|
520
712
|
// Wait some time for container to be stopped.
|
|
521
|
-
const { customAfterSleepMillis = this.config.metamorphAfterSleepMillis } = options;
|
|
522
713
|
await sleep(customAfterSleepMillis);
|
|
523
714
|
}
|
|
524
715
|
/**
|
|
@@ -534,23 +725,25 @@ export class Actor {
|
|
|
534
725
|
* @ignore
|
|
535
726
|
*/
|
|
536
727
|
async addWebhook(options) {
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
728
|
+
parseArgument(options, z
|
|
729
|
+
.object({
|
|
730
|
+
eventTypes: z.array(z.string()),
|
|
731
|
+
requestUrl: z.string(),
|
|
732
|
+
payloadTemplate: z.string().optional(),
|
|
733
|
+
idempotencyKey: z.string().optional(),
|
|
734
|
+
headersTemplate: z.string().optional(),
|
|
735
|
+
description: z.string().optional(),
|
|
736
|
+
ignoreSslErrors: z.boolean().optional(),
|
|
737
|
+
doNotRetry: z.boolean().optional(),
|
|
738
|
+
shouldInterpolateStrings: z.boolean().optional(),
|
|
739
|
+
isApifyIntegration: z.boolean().optional(),
|
|
740
|
+
})
|
|
741
|
+
.strict());
|
|
549
742
|
if (!this.isAtHome()) {
|
|
550
743
|
log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
|
|
551
744
|
return undefined;
|
|
552
745
|
}
|
|
553
|
-
const runId = this.
|
|
746
|
+
const runId = this.configuration.actorRunId;
|
|
554
747
|
if (!runId) {
|
|
555
748
|
throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
|
|
556
749
|
}
|
|
@@ -565,15 +758,16 @@ export class Actor {
|
|
|
565
758
|
/**
|
|
566
759
|
* Sets the status message for the current Actor run.
|
|
567
760
|
*
|
|
568
|
-
* @returns The
|
|
761
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
762
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
569
763
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
570
764
|
* @ignore
|
|
571
765
|
*/
|
|
572
766
|
async setStatusMessage(statusMessage, options) {
|
|
573
767
|
const { isStatusMessageTerminal, level } = options || {};
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
this.
|
|
768
|
+
parseArgument(statusMessage, z.string());
|
|
769
|
+
parseArgument(isStatusMessageTerminal, z.boolean().optional());
|
|
770
|
+
this.ensureActorInit('setStatusMessage');
|
|
577
771
|
const loggedStatusMessage = `[Status message]: ${statusMessage}`;
|
|
578
772
|
switch (level) {
|
|
579
773
|
case 'DEBUG':
|
|
@@ -589,21 +783,22 @@ export class Actor {
|
|
|
589
783
|
log.info(loggedStatusMessage);
|
|
590
784
|
break;
|
|
591
785
|
}
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
if (run) {
|
|
603
|
-
return run;
|
|
604
|
-
}
|
|
786
|
+
return this.#updateRunStatusMessage(statusMessage, isStatusMessageTerminal);
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Propagates a status message to the current run, without logging it locally.
|
|
790
|
+
* Resolves `undefined` when there is no run to update, or when the update failed or timed out.
|
|
791
|
+
*/
|
|
792
|
+
async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
|
|
793
|
+
const runId = this.configuration.actorRunId;
|
|
794
|
+
if (!runId) {
|
|
795
|
+
return undefined;
|
|
605
796
|
}
|
|
606
|
-
|
|
797
|
+
// just to be sure, this should be fast
|
|
798
|
+
return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
|
|
799
|
+
log.warning(e.message);
|
|
800
|
+
return undefined;
|
|
801
|
+
});
|
|
607
802
|
}
|
|
608
803
|
/**
|
|
609
804
|
* Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
|
|
@@ -625,27 +820,67 @@ export class Actor {
|
|
|
625
820
|
* **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
|
|
626
821
|
* otherwise the Actor process might finish before the data are stored!
|
|
627
822
|
*
|
|
823
|
+
* Inside a crawlee storage transaction, the items are stored - and charged for - at commit time,
|
|
824
|
+
* so the returned counts are zero and charging for an explicit `eventName` is rejected outright.
|
|
825
|
+
*
|
|
628
826
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
629
827
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
630
828
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
829
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
631
830
|
* @ignore
|
|
632
831
|
*/
|
|
633
832
|
async pushData(item, eventName) {
|
|
634
|
-
this.
|
|
833
|
+
this.ensureActorInit('pushData');
|
|
635
834
|
if (eventName?.startsWith('apify-')) {
|
|
636
835
|
throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
|
|
637
836
|
}
|
|
837
|
+
if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
|
|
838
|
+
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.');
|
|
839
|
+
}
|
|
840
|
+
if (eventName !== undefined) {
|
|
841
|
+
rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
|
|
842
|
+
'so a rolled-back request would be billed for items that were never stored.');
|
|
843
|
+
}
|
|
638
844
|
const dataset = await this.openDataset();
|
|
639
|
-
|
|
640
|
-
//
|
|
641
|
-
//
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
if (this.usesPushDataInterception(dataset)) {
|
|
646
|
-
return await this.pushDataViaInterceptedClient(dataset, item, eventName);
|
|
845
|
+
const items = Array.isArray(item) ? item : [item];
|
|
846
|
+
// `Actor.pushData()` historically worked even without calling `Actor.init()`.
|
|
847
|
+
// In that case, charging isn't configured, so just push the data through.
|
|
848
|
+
if (!this.#chargingManager.isInitialized) {
|
|
849
|
+
await dataset.pushData(items);
|
|
850
|
+
return { eventChargeLimitReached: false, chargedCount: 0, chargeableWithinLimit: {} };
|
|
647
851
|
}
|
|
648
|
-
|
|
852
|
+
// The reservation below and the charge that acts on it have to stay under one lock, so that
|
|
853
|
+
// a concurrent push cannot charge in between. The dataset backend re-enters the same lock to
|
|
854
|
+
// charge the synthetic per-item event.
|
|
855
|
+
return await this.#chargingManager.withChargeLock(async () => {
|
|
856
|
+
if (eventName === undefined) {
|
|
857
|
+
// Nothing to charge here - the dataset backend charges the synthetic event for
|
|
858
|
+
// whatever it stores, so the result is read back off the charging state.
|
|
859
|
+
const chargedBefore = this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT);
|
|
860
|
+
await dataset.pushData(items);
|
|
861
|
+
return {
|
|
862
|
+
eventChargeLimitReached: this.#chargingManager.isEventChargeLimitReached(DEFAULT_DATASET_ITEM_EVENT),
|
|
863
|
+
chargedCount: this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT) - chargedBefore,
|
|
864
|
+
chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
const limit = this.#chargingManager.calculatePushDataLimit(items.length, {
|
|
868
|
+
eventName,
|
|
869
|
+
// Pushing one item charges the synthetic per-item event too when the dataset backend
|
|
870
|
+
// is the charging one, so that price is part of what an item costs here. Only the Actor's
|
|
871
|
+
// own backend wraps the default dataset for charging, a caller-supplied one is left as is.
|
|
872
|
+
isDefaultDataset: serviceLocator.getStorageBackend() === this.#cachedStorageBackend,
|
|
873
|
+
});
|
|
874
|
+
if (limit === 0) {
|
|
875
|
+
return {
|
|
876
|
+
eventChargeLimitReached: items.length > 0,
|
|
877
|
+
chargedCount: 0,
|
|
878
|
+
chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
await dataset.pushData(limit < items.length ? items.slice(0, limit) : items);
|
|
882
|
+
return await this.#chargingManager.charge({ eventName, count: limit });
|
|
883
|
+
});
|
|
649
884
|
}
|
|
650
885
|
/**
|
|
651
886
|
* Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
|
|
@@ -659,50 +894,24 @@ export class Actor {
|
|
|
659
894
|
* @param [datasetIdOrName]
|
|
660
895
|
* ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
|
|
661
896
|
* the function returns the default dataset associated with the Actor run.
|
|
662
|
-
* You can also pass `{ alias: '
|
|
663
|
-
*
|
|
897
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
898
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
664
899
|
* @param [options]
|
|
665
900
|
* @ignore
|
|
666
901
|
*/
|
|
667
902
|
async openDataset(datasetIdOrName, options = {}) {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
903
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
904
|
+
this.ensureActorInit('openDataset');
|
|
905
|
+
return Dataset.open(datasetIdOrName ?? null, {
|
|
906
|
+
storageBackend: options.forceCloud
|
|
907
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
908
|
+
: undefined,
|
|
909
|
+
});
|
|
673
910
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
*
|
|
677
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
678
|
-
* For example, calling the following code:
|
|
679
|
-
* ```js
|
|
680
|
-
* const value = await Actor.getValue('my-key');
|
|
681
|
-
* ```
|
|
682
|
-
*
|
|
683
|
-
* is equivalent to:
|
|
684
|
-
* ```js
|
|
685
|
-
* const store = await Actor.openKeyValueStore();
|
|
686
|
-
* const value = await store.getValue('my-key');
|
|
687
|
-
* ```
|
|
688
|
-
*
|
|
689
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
690
|
-
*
|
|
691
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
692
|
-
* and {@link KeyValueStore.getValue}.
|
|
693
|
-
*
|
|
694
|
-
* @param key Unique record key.
|
|
695
|
-
* @returns
|
|
696
|
-
* Returns a promise that resolves to an object, string
|
|
697
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
698
|
-
* on the MIME content type of the record, or `null`
|
|
699
|
-
* if the record is missing.
|
|
700
|
-
* @ignore
|
|
701
|
-
*/
|
|
702
|
-
async getValue(key) {
|
|
703
|
-
this._ensureActorInit('getValue');
|
|
911
|
+
async getValue(key, defaultValue) {
|
|
912
|
+
this.ensureActorInit('getValue');
|
|
704
913
|
const store = await this.openKeyValueStore();
|
|
705
|
-
return store.getValue(key);
|
|
914
|
+
return store.getValue(key, defaultValue);
|
|
706
915
|
}
|
|
707
916
|
/**
|
|
708
917
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -736,24 +945,28 @@ export class Actor {
|
|
|
736
945
|
* @ignore
|
|
737
946
|
*/
|
|
738
947
|
async setValue(key, value, options = {}) {
|
|
739
|
-
this.
|
|
948
|
+
this.ensureActorInit('setValue');
|
|
740
949
|
const store = await this.openKeyValueStore();
|
|
741
950
|
return store.setValue(key, value, options);
|
|
742
951
|
}
|
|
743
952
|
/**
|
|
744
953
|
* Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
|
|
745
954
|
*
|
|
746
|
-
*
|
|
747
|
-
*
|
|
748
|
-
*
|
|
749
|
-
* const input = await Actor.getInput();
|
|
750
|
-
* ```
|
|
955
|
+
* The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`).
|
|
956
|
+
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
957
|
+
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
751
958
|
*
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
959
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
960
|
+
* working directory. A storage backend that doesn't read the default key-value store's directory under
|
|
961
|
+
* the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
|
|
962
|
+
*
|
|
963
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
964
|
+
* replaced with the links of their CSV exports.
|
|
965
|
+
*
|
|
966
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
967
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
968
|
+
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
969
|
+
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
|
|
757
970
|
*
|
|
758
971
|
* Note that the `getInput()` function does not cache the value read from the key-value store.
|
|
759
972
|
* If you need to use the input multiple times in your Actor,
|
|
@@ -765,39 +978,85 @@ export class Actor {
|
|
|
765
978
|
* @returns
|
|
766
979
|
* Returns a promise that resolves to an object, string
|
|
767
980
|
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
768
|
-
* on the MIME content type of the record
|
|
769
|
-
*
|
|
981
|
+
* on the MIME content type of the record.
|
|
982
|
+
* @throws {ActorInputError} When the input cannot be produced; see `code`.
|
|
770
983
|
* @ignore
|
|
771
984
|
*/
|
|
772
985
|
async getInput() {
|
|
773
|
-
this.
|
|
774
|
-
const { inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase } = this.
|
|
775
|
-
|
|
986
|
+
this.ensureActorInit('getInput');
|
|
987
|
+
const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
|
|
988
|
+
// Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
|
|
989
|
+
const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
|
|
990
|
+
const store = await this.openKeyValueStore();
|
|
991
|
+
const record = await store.getRecord(inputKey);
|
|
992
|
+
// Not a conflict check: under the file-system backend the record *is* the store directory's file.
|
|
993
|
+
const storeInput = record
|
|
994
|
+
? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
|
|
995
|
+
: await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
|
|
996
|
+
const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
|
|
997
|
+
if (storeInput != null && cwdInput != null) {
|
|
998
|
+
throw new ActorInputError('MULTIPLE_FILES', `Found the input both in the default key-value store and in a "${inputKey}" or "${inputKey}.json" file in the working directory. Keep only one of them.`);
|
|
999
|
+
}
|
|
1000
|
+
const rawInput = storeInput ?? cwdInput;
|
|
1001
|
+
if (rawInput == null) {
|
|
1002
|
+
const locations = [`the "${inputKey}" record of the default key-value store`];
|
|
1003
|
+
if (!this.configuration.isAtHome) {
|
|
1004
|
+
locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
|
|
1005
|
+
}
|
|
1006
|
+
throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
|
|
1007
|
+
}
|
|
776
1008
|
let input = rawInput;
|
|
777
|
-
if (
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
1009
|
+
if (isNonEmptyObject(rawInput) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
|
|
1010
|
+
try {
|
|
1011
|
+
const privateKey = createPrivateKey({
|
|
1012
|
+
key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
|
|
1013
|
+
passphrase: inputSecretsPrivateKeyPassphrase,
|
|
1014
|
+
});
|
|
1015
|
+
input = decryptInputSecrets({ input: rawInput, privateKey });
|
|
1016
|
+
}
|
|
1017
|
+
catch (cause) {
|
|
1018
|
+
throw new ActorInputError('DECRYPTION_FAILED', 'Failed to decrypt the secret fields of the input.', {
|
|
1019
|
+
cause,
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
785
1022
|
}
|
|
786
|
-
if (
|
|
787
|
-
input = await this.inferDefaultsFromInputSchema(input);
|
|
1023
|
+
if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
|
|
1024
|
+
input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
|
|
788
1025
|
}
|
|
789
1026
|
return input;
|
|
790
1027
|
}
|
|
791
1028
|
/**
|
|
792
|
-
*
|
|
793
|
-
*
|
|
1029
|
+
* Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
|
|
1030
|
+
* whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
|
|
1031
|
+
* such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
|
|
1032
|
+
* {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
|
|
1033
|
+
*
|
|
1034
|
+
* @returns `undefined` when running on the platform or when neither file exists.
|
|
794
1035
|
*/
|
|
795
|
-
async
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
throw new Error('Input does not exist');
|
|
1036
|
+
async readInputFromDirectory(inputKey, directory, label) {
|
|
1037
|
+
if (this.configuration.isAtHome) {
|
|
1038
|
+
return undefined;
|
|
799
1039
|
}
|
|
800
|
-
|
|
1040
|
+
const candidates = [
|
|
1041
|
+
{ filename: inputKey, contentType: BINARY_CONTENT_TYPE },
|
|
1042
|
+
{ filename: `${inputKey}.json`, contentType: JSON_CONTENT_TYPE },
|
|
1043
|
+
];
|
|
1044
|
+
const found = [];
|
|
1045
|
+
for (const candidate of candidates) {
|
|
1046
|
+
const path = join(directory, candidate.filename);
|
|
1047
|
+
const stats = await stat(path).catch(() => null);
|
|
1048
|
+
if (stats?.isFile()) {
|
|
1049
|
+
found.push({ ...candidate, path });
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (found.length > 1) {
|
|
1053
|
+
throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
|
|
1054
|
+
}
|
|
1055
|
+
if (found.length === 0) {
|
|
1056
|
+
return undefined;
|
|
1057
|
+
}
|
|
1058
|
+
const [file] = found;
|
|
1059
|
+
return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
|
|
801
1060
|
}
|
|
802
1061
|
/**
|
|
803
1062
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
@@ -809,18 +1068,21 @@ export class Actor {
|
|
|
809
1068
|
* For more details and code examples, see the {@link KeyValueStore} class.
|
|
810
1069
|
*
|
|
811
1070
|
* @param [storeIdOrName]
|
|
812
|
-
* ID or
|
|
1071
|
+
* ID, name, or alias of the key-value store to be opened. If `null` or `undefined`,
|
|
813
1072
|
* the function returns the default key-value store associated with the Actor run.
|
|
814
|
-
* You can also pass `{
|
|
1073
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1074
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
815
1075
|
* @param [options]
|
|
816
1076
|
* @ignore
|
|
817
1077
|
*/
|
|
818
1078
|
async openKeyValueStore(storeIdOrName, options = {}) {
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1079
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
1080
|
+
this.ensureActorInit('openKeyValueStore');
|
|
1081
|
+
return KeyValueStore.open(storeIdOrName ?? null, {
|
|
1082
|
+
storageBackend: options.forceCloud
|
|
1083
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
1084
|
+
: undefined,
|
|
1085
|
+
});
|
|
824
1086
|
}
|
|
825
1087
|
/**
|
|
826
1088
|
* Opens a request queue and returns a promise resolving to an instance
|
|
@@ -834,21 +1096,21 @@ export class Actor {
|
|
|
834
1096
|
* For more details and code examples, see the {@link RequestQueue} class.
|
|
835
1097
|
*
|
|
836
1098
|
* @param [queueIdOrName]
|
|
837
|
-
* ID or
|
|
1099
|
+
* ID, name, or alias of the request queue to be opened. If `null` or `undefined`,
|
|
838
1100
|
* the function returns the default request queue associated with the Actor run.
|
|
839
|
-
* You can also pass `{
|
|
1101
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1102
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
840
1103
|
* @param [options]
|
|
841
1104
|
* @ignore
|
|
842
1105
|
*/
|
|
843
1106
|
async openRequestQueue(queueIdOrName, options = {}) {
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
return queue;
|
|
1107
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
1108
|
+
this.ensureActorInit('openRequestQueue');
|
|
1109
|
+
return RequestQueue.open(queueIdOrName ?? null, {
|
|
1110
|
+
storageBackend: options.forceCloud
|
|
1111
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
1112
|
+
: undefined,
|
|
1113
|
+
});
|
|
852
1114
|
}
|
|
853
1115
|
/**
|
|
854
1116
|
* Creates a proxy configuration and returns a promise resolving to an instance
|
|
@@ -899,7 +1161,7 @@ export class Actor {
|
|
|
899
1161
|
if (dontUseApifyProxy && dontUseCustomProxies) {
|
|
900
1162
|
return undefined;
|
|
901
1163
|
}
|
|
902
|
-
const proxyConfiguration = new ProxyConfiguration(options, this.
|
|
1164
|
+
const proxyConfiguration = new ProxyConfiguration(options, this.configuration);
|
|
903
1165
|
if (await proxyConfiguration.initialize({ checkAccess })) {
|
|
904
1166
|
return proxyConfiguration;
|
|
905
1167
|
}
|
|
@@ -919,66 +1181,58 @@ export class Actor {
|
|
|
919
1181
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
920
1182
|
* and avoids situations where more work is requested than the budget allows.
|
|
921
1183
|
*
|
|
1184
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1185
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1186
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1187
|
+
*
|
|
922
1188
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
923
1189
|
* @ignore
|
|
924
1190
|
*/
|
|
925
1191
|
async charge(options) {
|
|
926
|
-
this.
|
|
927
|
-
return this
|
|
1192
|
+
this.ensureActorInit('charge');
|
|
1193
|
+
return this.#chargingManager.charge(options);
|
|
928
1194
|
}
|
|
929
1195
|
/**
|
|
930
1196
|
* Retrieve the charging manager to access granular pricing information.
|
|
931
1197
|
* @ignore
|
|
932
1198
|
*/
|
|
933
1199
|
getChargingManager() {
|
|
934
|
-
this.
|
|
935
|
-
return this
|
|
1200
|
+
this.ensureActorInit('getChargingManager');
|
|
1201
|
+
return this.#chargingManager;
|
|
936
1202
|
}
|
|
937
1203
|
/**
|
|
938
|
-
*
|
|
1204
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1205
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1206
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
939
1207
|
*/
|
|
940
|
-
|
|
941
|
-
const
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
1208
|
+
async getCurrentRun() {
|
|
1209
|
+
const runId = this.configuration.actorRunId;
|
|
1210
|
+
if (!runId) {
|
|
1211
|
+
return undefined;
|
|
1212
|
+
}
|
|
1213
|
+
this.#runPromise ??= this.apifyClient
|
|
1214
|
+
.run(runId)
|
|
1215
|
+
.get()
|
|
1216
|
+
.catch((err) => {
|
|
1217
|
+
this.#runPromise = undefined;
|
|
1218
|
+
throw err;
|
|
950
1219
|
});
|
|
951
|
-
return
|
|
1220
|
+
return this.#runPromise;
|
|
952
1221
|
}
|
|
953
|
-
/**
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
* If some variables are not defined or are invalid, the corresponding value in the resulting object will be null.
|
|
959
|
-
* @ignore
|
|
960
|
-
*/
|
|
961
|
-
getEnv() {
|
|
962
|
-
// NOTE: Don't throw if env vars are invalid to simplify local development and debugging of Actors
|
|
963
|
-
const env = process.env || {};
|
|
964
|
-
const envVars = {};
|
|
965
|
-
for (const [shortName, fullName] of Object.entries({
|
|
966
|
-
...APIFY_ENV_VARS,
|
|
967
|
-
...this.getModifiedActorEnvVars(),
|
|
968
|
-
})) {
|
|
969
|
-
const camelCaseName = snakeCaseToCamelCase(shortName);
|
|
970
|
-
let value = env[fullName];
|
|
971
|
-
// Parse dates and integers.
|
|
972
|
-
if (value && fullName.endsWith('_AT')) {
|
|
973
|
-
const unix = Date.parse(value);
|
|
974
|
-
value = unix > 0 ? new Date(unix) : undefined;
|
|
975
|
-
}
|
|
976
|
-
else if (INTEGER_ENV_VARS.includes(fullName)) {
|
|
977
|
-
value = parseInt(value, 10);
|
|
978
|
-
}
|
|
979
|
-
Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
|
|
1222
|
+
/** Cached for the lifetime of the Actor; only the charging manager needs it. */
|
|
1223
|
+
async #getCurrentActor() {
|
|
1224
|
+
const { actorId } = this.configuration;
|
|
1225
|
+
if (!actorId) {
|
|
1226
|
+
return undefined;
|
|
980
1227
|
}
|
|
981
|
-
|
|
1228
|
+
this.#actorPromise ??= this.apifyClient
|
|
1229
|
+
.actor(actorId)
|
|
1230
|
+
.get()
|
|
1231
|
+
.catch((err) => {
|
|
1232
|
+
this.#actorPromise = undefined;
|
|
1233
|
+
throw err;
|
|
1234
|
+
});
|
|
1235
|
+
return this.#actorPromise;
|
|
982
1236
|
}
|
|
983
1237
|
/**
|
|
984
1238
|
* Returns a new instance of the Apify API client. The `ApifyClient` class is provided
|
|
@@ -989,12 +1243,12 @@ export class Actor {
|
|
|
989
1243
|
* @ignore
|
|
990
1244
|
*/
|
|
991
1245
|
newClient(options = {}) {
|
|
992
|
-
const { storageDir, ...storageClientOptions } = (this.
|
|
1246
|
+
const { storageDir, ...storageClientOptions } = (this.configuration.storageClientOptions ?? {});
|
|
993
1247
|
const { apifyVersion, crawleeVersion } = getSystemInfo();
|
|
994
1248
|
return new ApifyClient({
|
|
995
|
-
baseUrl: this.
|
|
996
|
-
publicBaseUrl: this.
|
|
997
|
-
token: this.
|
|
1249
|
+
baseUrl: this.configuration.apiBaseUrl,
|
|
1250
|
+
publicBaseUrl: this.configuration.apiPublicBaseUrl,
|
|
1251
|
+
token: this.configuration.token,
|
|
998
1252
|
userAgentSuffix: [`SDK/${apifyVersion}`, `Crawlee/${crawleeVersion}`],
|
|
999
1253
|
...storageClientOptions,
|
|
1000
1254
|
...options, // allow overriding the instance configuration
|
|
@@ -1017,9 +1271,9 @@ export class Actor {
|
|
|
1017
1271
|
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
|
|
1018
1272
|
*/
|
|
1019
1273
|
async useState(name, defaultValue = {}, options) {
|
|
1020
|
-
this.
|
|
1274
|
+
this.ensureActorInit('useState');
|
|
1021
1275
|
const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
|
|
1022
|
-
|
|
1276
|
+
configuration: options?.configuration ?? this.configuration,
|
|
1023
1277
|
});
|
|
1024
1278
|
return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
|
|
1025
1279
|
}
|
|
@@ -1070,24 +1324,22 @@ export class Actor {
|
|
|
1070
1324
|
*
|
|
1071
1325
|
* If the user function returns a promise, it is considered asynchronous:
|
|
1072
1326
|
* ```js
|
|
1073
|
-
* import { gotScraping } from 'got-scraping';
|
|
1074
|
-
*
|
|
1075
1327
|
* await Actor.main(() => {
|
|
1076
1328
|
* // My asynchronous function that returns a promise
|
|
1077
|
-
* return
|
|
1078
|
-
*
|
|
1079
|
-
*
|
|
1329
|
+
* return fetch('http://www.example.com')
|
|
1330
|
+
* .then((response) => response.text())
|
|
1331
|
+
* .then((html) => {
|
|
1332
|
+
* console.log(html);
|
|
1333
|
+
* });
|
|
1080
1334
|
* });
|
|
1081
1335
|
* ```
|
|
1082
1336
|
*
|
|
1083
1337
|
* To simplify your code, you can take advantage of the `async`/`await` keywords:
|
|
1084
1338
|
*
|
|
1085
1339
|
* ```js
|
|
1086
|
-
* import { gotScraping } from 'got-scraping';
|
|
1087
|
-
*
|
|
1088
1340
|
* await Actor.main(async () => {
|
|
1089
1341
|
* // My asynchronous function
|
|
1090
|
-
* const html = await
|
|
1342
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
1091
1343
|
* console.log(html);
|
|
1092
1344
|
* });
|
|
1093
1345
|
* ```
|
|
@@ -1115,11 +1367,9 @@ export class Actor {
|
|
|
1115
1367
|
* behavior by setting `options.gracefulShutdown` to `false`.
|
|
1116
1368
|
*
|
|
1117
1369
|
* ```js
|
|
1118
|
-
* import { gotScraping } from 'got-scraping';
|
|
1119
|
-
*
|
|
1120
1370
|
* await Actor.init();
|
|
1121
1371
|
*
|
|
1122
|
-
* const html = await
|
|
1372
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
1123
1373
|
* console.log(html);
|
|
1124
1374
|
*
|
|
1125
1375
|
* await Actor.exit();
|
|
@@ -1170,9 +1420,8 @@ export class Actor {
|
|
|
1170
1420
|
* @param actorId
|
|
1171
1421
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
1172
1422
|
* @param [input]
|
|
1173
|
-
* Input for the Actor.
|
|
1174
|
-
*
|
|
1175
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
1423
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1424
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1176
1425
|
* @param [options]
|
|
1177
1426
|
*/
|
|
1178
1427
|
static async call(actorId, input, options = {}) {
|
|
@@ -1206,6 +1455,31 @@ export class Actor {
|
|
|
1206
1455
|
static async callTask(taskId, input, options = {}) {
|
|
1207
1456
|
return Actor.getDefaultInstance().callTask(taskId, input, options);
|
|
1208
1457
|
}
|
|
1458
|
+
/**
|
|
1459
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1460
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
1461
|
+
*
|
|
1462
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1463
|
+
*
|
|
1464
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
1465
|
+
*
|
|
1466
|
+
* **Example usage:**
|
|
1467
|
+
*
|
|
1468
|
+
* ```js
|
|
1469
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
1470
|
+
* ```
|
|
1471
|
+
*
|
|
1472
|
+
* @param taskId
|
|
1473
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
1474
|
+
* @param [input]
|
|
1475
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
1476
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
1477
|
+
* Provided input will be merged with Actor task input.
|
|
1478
|
+
* @param [options]
|
|
1479
|
+
*/
|
|
1480
|
+
static async startTask(taskId, input, options = {}) {
|
|
1481
|
+
return Actor.getDefaultInstance().startTask(taskId, input, options);
|
|
1482
|
+
}
|
|
1209
1483
|
/**
|
|
1210
1484
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1211
1485
|
* unlike `Actor.call`, this method just starts the run without waiting for finish.
|
|
@@ -1224,14 +1498,28 @@ export class Actor {
|
|
|
1224
1498
|
* @param actorId
|
|
1225
1499
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
1226
1500
|
* @param [input]
|
|
1227
|
-
* Input for the Actor.
|
|
1228
|
-
*
|
|
1229
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
1501
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1502
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1230
1503
|
* @param [options]
|
|
1231
1504
|
*/
|
|
1232
1505
|
static async start(actorId, input, options = {}) {
|
|
1233
1506
|
return Actor.getDefaultInstance().start(actorId, input, options);
|
|
1234
1507
|
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
1510
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
1511
|
+
*
|
|
1512
|
+
* ```js
|
|
1513
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
1514
|
+
* ```
|
|
1515
|
+
*
|
|
1516
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
1517
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
1518
|
+
* under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
|
|
1519
|
+
*/
|
|
1520
|
+
static get childRuns() {
|
|
1521
|
+
return Actor.getDefaultInstance().childRuns;
|
|
1522
|
+
}
|
|
1235
1523
|
/**
|
|
1236
1524
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1237
1525
|
*
|
|
@@ -1249,6 +1537,26 @@ export class Actor {
|
|
|
1249
1537
|
static async abort(runId, options = {}) {
|
|
1250
1538
|
return Actor.getDefaultInstance().abort(runId, options);
|
|
1251
1539
|
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1542
|
+
*
|
|
1543
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
1544
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
1545
|
+
*
|
|
1546
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1547
|
+
*
|
|
1548
|
+
* For more information about Actors, read the
|
|
1549
|
+
* [documentation](https://docs.apify.com/actor).
|
|
1550
|
+
*
|
|
1551
|
+
* **Example usage:**
|
|
1552
|
+
*
|
|
1553
|
+
* ```js
|
|
1554
|
+
* const run = await Actor.resurrect(runId);
|
|
1555
|
+
* ```
|
|
1556
|
+
*/
|
|
1557
|
+
static async resurrect(runId, options = {}) {
|
|
1558
|
+
return Actor.getDefaultInstance().resurrect(runId, options);
|
|
1559
|
+
}
|
|
1252
1560
|
/**
|
|
1253
1561
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
1254
1562
|
* the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
|
|
@@ -1257,9 +1565,8 @@ export class Actor {
|
|
|
1257
1565
|
* @param targetActorId
|
|
1258
1566
|
* Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
|
|
1259
1567
|
* @param [input]
|
|
1260
|
-
* Input for the Actor.
|
|
1261
|
-
*
|
|
1262
|
-
* Otherwise, the `options.contentType` parameter must be provided.
|
|
1568
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1569
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1263
1570
|
* @param [options]
|
|
1264
1571
|
*/
|
|
1265
1572
|
static async metamorph(targetActorId, input, options = {}) {
|
|
@@ -1294,7 +1601,8 @@ export class Actor {
|
|
|
1294
1601
|
* @param [options]
|
|
1295
1602
|
* @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
|
|
1296
1603
|
* This is required for the last status message of the run. Default value is `false`.
|
|
1297
|
-
* @returns The
|
|
1604
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
1605
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
1298
1606
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
1299
1607
|
*/
|
|
1300
1608
|
static async setStatusMessage(statusMessage, options) {
|
|
@@ -1323,6 +1631,7 @@ export class Actor {
|
|
|
1323
1631
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
1324
1632
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
1325
1633
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
1634
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
1326
1635
|
*/
|
|
1327
1636
|
static async pushData(item, eventName) {
|
|
1328
1637
|
if (eventName === undefined) {
|
|
@@ -1342,42 +1651,15 @@ export class Actor {
|
|
|
1342
1651
|
* @param [datasetIdOrName]
|
|
1343
1652
|
* ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
|
|
1344
1653
|
* the function returns the default dataset associated with the Actor run.
|
|
1345
|
-
* You can also pass `{ alias: '
|
|
1346
|
-
*
|
|
1654
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1655
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
1347
1656
|
* @param [options]
|
|
1348
1657
|
*/
|
|
1349
1658
|
static async openDataset(datasetIdOrName, options = {}) {
|
|
1350
1659
|
return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
|
|
1351
1660
|
}
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
*
|
|
1355
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
1356
|
-
* For example, calling the following code:
|
|
1357
|
-
* ```js
|
|
1358
|
-
* const value = await Actor.getValue('my-key');
|
|
1359
|
-
* ```
|
|
1360
|
-
*
|
|
1361
|
-
* is equivalent to:
|
|
1362
|
-
* ```js
|
|
1363
|
-
* const store = await Actor.openKeyValueStore();
|
|
1364
|
-
* const value = await store.getValue('my-key');
|
|
1365
|
-
* ```
|
|
1366
|
-
*
|
|
1367
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
1368
|
-
*
|
|
1369
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
1370
|
-
* and {@link KeyValueStore.getValue}.
|
|
1371
|
-
*
|
|
1372
|
-
* @param key Unique record key.
|
|
1373
|
-
* @returns
|
|
1374
|
-
* Returns a promise that resolves to an object, string
|
|
1375
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
1376
|
-
* on the MIME content type of the record, or `null`
|
|
1377
|
-
* if the record is missing.
|
|
1378
|
-
*/
|
|
1379
|
-
static async getValue(key) {
|
|
1380
|
-
return Actor.getDefaultInstance().getValue(key);
|
|
1661
|
+
static async getValue(key, defaultValue) {
|
|
1662
|
+
return Actor.getDefaultInstance().getValue(key, defaultValue);
|
|
1381
1663
|
}
|
|
1382
1664
|
/**
|
|
1383
1665
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -1415,16 +1697,31 @@ export class Actor {
|
|
|
1415
1697
|
/**
|
|
1416
1698
|
* Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
|
|
1417
1699
|
*
|
|
1418
|
-
*
|
|
1419
|
-
* For example, calling the following code:
|
|
1700
|
+
* The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`):
|
|
1420
1701
|
* ```js
|
|
1421
1702
|
* const input = await Actor.getInput();
|
|
1422
1703
|
* ```
|
|
1423
1704
|
*
|
|
1424
|
-
* is
|
|
1705
|
+
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
1706
|
+
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
1707
|
+
*
|
|
1708
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
1709
|
+
* working directory.
|
|
1710
|
+
*
|
|
1711
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
1712
|
+
* replaced with the links of their CSV exports.
|
|
1713
|
+
*
|
|
1714
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
1715
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
1716
|
+
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
1717
|
+
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
|
|
1425
1718
|
* ```js
|
|
1426
|
-
*
|
|
1427
|
-
*
|
|
1719
|
+
* let input = {};
|
|
1720
|
+
* try {
|
|
1721
|
+
* input = await Actor.getInput();
|
|
1722
|
+
* } catch (error) {
|
|
1723
|
+
* if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
|
|
1724
|
+
* }
|
|
1428
1725
|
* ```
|
|
1429
1726
|
*
|
|
1430
1727
|
* Note that the `getInput()` function does not cache the value read from the key-value store.
|
|
@@ -1436,19 +1733,12 @@ export class Actor {
|
|
|
1436
1733
|
* @returns
|
|
1437
1734
|
* Returns a promise that resolves to an object, string
|
|
1438
1735
|
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
1439
|
-
* on the MIME content type of the record
|
|
1440
|
-
*
|
|
1736
|
+
* on the MIME content type of the record.
|
|
1737
|
+
* @throws {ActorInputError} When the input cannot be produced; see `code`.
|
|
1441
1738
|
*/
|
|
1442
1739
|
static async getInput() {
|
|
1443
1740
|
return Actor.getDefaultInstance().getInput();
|
|
1444
1741
|
}
|
|
1445
|
-
/**
|
|
1446
|
-
* Gets the Actor input value just like the {@link Actor.getInput} method,
|
|
1447
|
-
* but throws if it is not found.
|
|
1448
|
-
*/
|
|
1449
|
-
static async getInputOrThrow() {
|
|
1450
|
-
return Actor.getDefaultInstance().getInputOrThrow();
|
|
1451
|
-
}
|
|
1452
1742
|
/**
|
|
1453
1743
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
1454
1744
|
*
|
|
@@ -1542,6 +1832,10 @@ export class Actor {
|
|
|
1542
1832
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1543
1833
|
* and avoids situations where more work is requested than the budget allows.
|
|
1544
1834
|
*
|
|
1835
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1836
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1837
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1838
|
+
*
|
|
1545
1839
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1546
1840
|
*/
|
|
1547
1841
|
static async charge(options) {
|
|
@@ -1553,16 +1847,6 @@ export class Actor {
|
|
|
1553
1847
|
static getChargingManager() {
|
|
1554
1848
|
return Actor.getDefaultInstance().getChargingManager();
|
|
1555
1849
|
}
|
|
1556
|
-
/**
|
|
1557
|
-
* Returns a new {@link ApifyEnv} object which contains information parsed from all the Apify environment variables.
|
|
1558
|
-
*
|
|
1559
|
-
* For the list of the Apify environment variables, see
|
|
1560
|
-
* [Actor documentation](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables).
|
|
1561
|
-
* If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.
|
|
1562
|
-
*/
|
|
1563
|
-
static getEnv() {
|
|
1564
|
-
return Actor.getDefaultInstance().getEnv();
|
|
1565
|
-
}
|
|
1566
1850
|
/**
|
|
1567
1851
|
* Returns a new instance of the Apify API client. The `ApifyClient` class is provided
|
|
1568
1852
|
* by the [apify-client](https://www.npmjs.com/package/apify-client)
|
|
@@ -1579,88 +1863,121 @@ export class Actor {
|
|
|
1579
1863
|
static isAtHome() {
|
|
1580
1864
|
return Actor.getDefaultInstance().isAtHome();
|
|
1581
1865
|
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1868
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1869
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1870
|
+
*/
|
|
1871
|
+
static async getCurrentRun() {
|
|
1872
|
+
return Actor.getDefaultInstance().getCurrentRun();
|
|
1873
|
+
}
|
|
1582
1874
|
/** Default {@link ApifyClient} instance. */
|
|
1583
1875
|
static get apifyClient() {
|
|
1584
1876
|
return Actor.getDefaultInstance().apifyClient;
|
|
1585
1877
|
}
|
|
1586
1878
|
/** Default {@link Configuration} instance. */
|
|
1587
|
-
static get
|
|
1588
|
-
return Actor.getDefaultInstance().
|
|
1879
|
+
static get configuration() {
|
|
1880
|
+
return Actor.getDefaultInstance().configuration;
|
|
1589
1881
|
}
|
|
1590
1882
|
/** @internal */
|
|
1591
1883
|
static getDefaultInstance() {
|
|
1592
|
-
|
|
1593
|
-
return
|
|
1884
|
+
Actor.#instance ??= new Actor();
|
|
1885
|
+
return Actor.#instance;
|
|
1594
1886
|
}
|
|
1595
|
-
|
|
1596
|
-
|
|
1887
|
+
/**
|
|
1888
|
+
* Replaces or clears the cached default instance returned by {@link Actor.getDefaultInstance}.
|
|
1889
|
+
* @internal
|
|
1890
|
+
*/
|
|
1891
|
+
static setDefaultInstance(instance) {
|
|
1892
|
+
Actor.#instance = instance;
|
|
1597
1893
|
}
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1894
|
+
/**
|
|
1895
|
+
* The backend the Actor installs unless the caller brings one: Apify platform storage on the
|
|
1896
|
+
* platform, crawlee's local default outside of it.
|
|
1897
|
+
*
|
|
1898
|
+
* Both sides are wrapped for dataset-item charging - crawlee's local default stands in for
|
|
1899
|
+
* Apify storage, so local pay-per-event testing stays faithful. A caller-supplied backend
|
|
1900
|
+
* (`Actor.init({ storage })`) is billed nothing and is installed unwrapped, in place of this.
|
|
1901
|
+
*
|
|
1902
|
+
* One instance per Actor: a second platform backend would mint unnamed storages of its own for
|
|
1903
|
+
* aliases this one has already resolved.
|
|
1904
|
+
*/
|
|
1905
|
+
get #storageBackend() {
|
|
1906
|
+
const charging = {
|
|
1907
|
+
configuration: this.configuration,
|
|
1908
|
+
getChargingManager: () => this.#chargingManager,
|
|
1603
1909
|
};
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
});
|
|
1910
|
+
return (this.#cachedStorageBackend ??= new SmartApifyStorageBackend({
|
|
1911
|
+
cloudStorageBackend: new ChargingStorageBackend(new ApifyStorageBackend(this.apifyClient, {
|
|
1912
|
+
configuration: this.configuration,
|
|
1913
|
+
requestQueueAccess: this.#requestQueueAccess,
|
|
1914
|
+
}), charging),
|
|
1915
|
+
localStorageBackend: new ChargingStorageBackend(this.createLocalStorageBackend(), charging),
|
|
1916
|
+
configuration: this.configuration,
|
|
1917
|
+
}));
|
|
1612
1918
|
}
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
};
|
|
1919
|
+
/**
|
|
1920
|
+
* The same choice crawlee's `ServiceLocator` makes for its implicit default backend, with the
|
|
1921
|
+
* input-aware {@link ApifyFileSystemStorageBackend} in place of crawlee's — crawlee has no
|
|
1922
|
+
* notion of a run input.
|
|
1923
|
+
*/
|
|
1924
|
+
createLocalStorageBackend() {
|
|
1925
|
+
const { persistStorage, storageDir, inputKey } = this.configuration;
|
|
1926
|
+
const logger = serviceLocator.getLogger();
|
|
1927
|
+
if (!persistStorage) {
|
|
1928
|
+
return new MemoryStorageBackend({ logger: logger.child({ prefix: 'MemoryStorageBackend' }) });
|
|
1623
1929
|
}
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
eventName: explicitEventName,
|
|
1629
|
-
isDefaultDataset,
|
|
1630
|
-
pushFn: async (limitedItems) => dataset.pushData(limitedItems),
|
|
1930
|
+
return new ApifyFileSystemStorageBackend({
|
|
1931
|
+
localDataDirectory: storageDir,
|
|
1932
|
+
inputKey,
|
|
1933
|
+
logger: logger.child({ prefix: 'ApifyFileSystemStorageBackend' }),
|
|
1631
1934
|
});
|
|
1632
1935
|
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
? new ApifyStorageClient(this.apifyClient, this.config, () => this.chargingManager)
|
|
1638
|
-
: undefined,
|
|
1639
|
-
purgedStorageAliases: this.purgedStorageAliases,
|
|
1640
|
-
});
|
|
1936
|
+
/** Whether items reaching the run's default dataset are counted for pay-per-event charging. */
|
|
1937
|
+
#chargesDefaultDatasetItems() {
|
|
1938
|
+
const installed = serviceLocator.getStorageBackend();
|
|
1939
|
+
return installed instanceof SmartApifyStorageBackend || installed instanceof ChargingStorageBackend;
|
|
1641
1940
|
}
|
|
1642
|
-
|
|
1941
|
+
/**
|
|
1942
|
+
* crawlee's service locator is set-once, so a backend registered before `init()` wins and the
|
|
1943
|
+
* Actor cannot install its own over it. Replaces the resulting `ServiceConflictError` with the
|
|
1944
|
+
* way out.
|
|
1945
|
+
*/
|
|
1946
|
+
installStorageBackend(backend) {
|
|
1947
|
+
try {
|
|
1948
|
+
serviceLocator.setStorageBackend(backend);
|
|
1949
|
+
}
|
|
1950
|
+
catch (error) {
|
|
1951
|
+
throw new Error('A storage backend is already registered with crawlee, so the Actor cannot install its own. Pass it ' +
|
|
1952
|
+
'as `Actor.init({ storage })` instead of calling `serviceLocator.setStorageBackend()`.', { cause: error });
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
ensureActorInit(methodCalled) {
|
|
1643
1956
|
// If we already warned the user once, don't do it again to prevent spam
|
|
1644
|
-
if (this
|
|
1957
|
+
if (this.#warnedAboutMissingInitCall) {
|
|
1645
1958
|
return;
|
|
1646
1959
|
}
|
|
1647
1960
|
if (this.initialized) {
|
|
1648
1961
|
return;
|
|
1649
1962
|
}
|
|
1650
|
-
this
|
|
1963
|
+
this.#warnedAboutMissingInitCall = true;
|
|
1651
1964
|
log.warning([
|
|
1652
1965
|
`Actor.${methodCalled}() was called but the Actor instance was not initialized.`,
|
|
1653
1966
|
'Did you forget to call Actor.init()?',
|
|
1654
1967
|
].join('\n'));
|
|
1655
1968
|
}
|
|
1656
1969
|
/**
|
|
1657
|
-
* Get time remaining from the Actor run timeout
|
|
1658
|
-
*
|
|
1970
|
+
* Get time remaining from the Actor run timeout in seconds, rounded up to whole seconds with minimum value of 1 second.
|
|
1971
|
+
*
|
|
1972
|
+
* The API treats a 0 second timeout as no timeout, the minimum acceptable timeout is 1 second.
|
|
1973
|
+
*
|
|
1974
|
+
* Returns `undefined` if not on the Apify platform or the current run was started without a timeout.
|
|
1659
1975
|
*/
|
|
1660
|
-
|
|
1661
|
-
const
|
|
1662
|
-
|
|
1663
|
-
|
|
1976
|
+
getRemainingTimeSecs() {
|
|
1977
|
+
const { timeoutAt } = this.configuration;
|
|
1978
|
+
const MINIMUM_API_TIMEOUT_SECS = 1;
|
|
1979
|
+
if (this.isAtHome() && timeoutAt !== undefined) {
|
|
1980
|
+
return Math.max(Math.ceil((timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
|
|
1664
1981
|
}
|
|
1665
1982
|
log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
|
|
1666
1983
|
'timeout for the Actor run is set.');
|