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
package/dist/actor.js
CHANGED
|
@@ -1,31 +1,54 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
import { createPrivateKey } from 'node:crypto';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
|
|
5
|
+
import { sleep } from '@crawlee/utils';
|
|
6
|
+
import { ApifyClient } from 'apify-client';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, } from '@apify/consts';
|
|
9
|
+
import { decryptInputSecrets } from '@apify/input_secrets';
|
|
10
|
+
import log from '@apify/log';
|
|
11
|
+
import { addTimeoutToPromise } from '@apify/timeout';
|
|
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';
|
|
18
|
+
import { Configuration } from './configuration.js';
|
|
19
|
+
import { ActorInputError } from './errors.js';
|
|
20
|
+
import { fixGoogleSheetsUrls } from './google_sheets.js';
|
|
21
|
+
import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
|
|
22
|
+
import { PlatformEventManager } from './platform_event_manager.js';
|
|
23
|
+
import { ProxyConfiguration } from './proxy_configuration.js';
|
|
24
|
+
import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
|
|
25
|
+
import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, snakeCaseToCamelCase, } from './utils.js';
|
|
26
|
+
// `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
|
|
27
|
+
const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
|
|
28
|
+
// Still listed in `@apify/consts`, but no longer read by the SDK.
|
|
29
|
+
const IGNORED_ENV_VARS = [
|
|
30
|
+
APIFY_ENV_VARS.DISABLE_OUTDATED_WARNING,
|
|
31
|
+
APIFY_ENV_VARS.SDK_LATEST_VERSION,
|
|
32
|
+
];
|
|
33
|
+
/**
|
|
34
|
+
* {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
|
|
35
|
+
* JSON input reports where it came from.
|
|
36
|
+
*/
|
|
37
|
+
function parseInput(value, contentType, source) {
|
|
38
|
+
try {
|
|
39
|
+
return parseInputValue(value, contentType);
|
|
40
|
+
}
|
|
41
|
+
catch (cause) {
|
|
42
|
+
throw new ActorInputError('PARSE_FAILED', `The input in ${source} is not valid JSON.`, { cause });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
22
45
|
/**
|
|
23
46
|
* Exit codes for the Actor process.
|
|
24
47
|
* The error codes must be in the range 1-128, to avoid collision with signal exits
|
|
25
48
|
* and to ensure Docker will handle them correctly!
|
|
26
49
|
* @internal should be removed if we decide to remove `Actor.main()`
|
|
27
50
|
*/
|
|
28
|
-
|
|
51
|
+
export const EXIT_CODES = {
|
|
29
52
|
SUCCESS: 0,
|
|
30
53
|
ERROR_USER_FUNCTION_THREW: 91,
|
|
31
54
|
ERROR_UNKNOWN: 92,
|
|
@@ -35,106 +58,87 @@ exports.EXIT_CODES = {
|
|
|
35
58
|
* that will be used on the instance methods. Environment variables will have precedence over this configuration.
|
|
36
59
|
* See {@link Configuration} for details about what can be configured and what are the default values.
|
|
37
60
|
*/
|
|
38
|
-
class Actor {
|
|
61
|
+
export class Actor {
|
|
62
|
+
/** @internal */
|
|
63
|
+
static #instance;
|
|
64
|
+
#childRunTracker;
|
|
65
|
+
/**
|
|
66
|
+
* Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
|
|
67
|
+
* @internal
|
|
68
|
+
*/
|
|
69
|
+
configuration;
|
|
70
|
+
/**
|
|
71
|
+
* Default {@link ApifyClient} instance.
|
|
72
|
+
* @internal
|
|
73
|
+
*/
|
|
74
|
+
apifyClient;
|
|
75
|
+
/**
|
|
76
|
+
* Default {@link EventManager} instance.
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
eventManager;
|
|
80
|
+
/**
|
|
81
|
+
* Whether the Actor instance was initialized. This is set by calling {@link Actor.init}.
|
|
82
|
+
*/
|
|
83
|
+
initialized = false;
|
|
84
|
+
/**
|
|
85
|
+
* Set if the Actor called a method that requires the instance to be initialized, but did not do so.
|
|
86
|
+
* A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
|
|
87
|
+
*/
|
|
88
|
+
#warnedAboutMissingInitCall = false;
|
|
89
|
+
/**
|
|
90
|
+
* Set if the Actor is currently rebooting.
|
|
91
|
+
*/
|
|
92
|
+
#isRebooting = false;
|
|
93
|
+
/**
|
|
94
|
+
* Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
|
|
95
|
+
*/
|
|
96
|
+
#isExiting = false;
|
|
97
|
+
/**
|
|
98
|
+
* References to graceful shutdown handlers so they can be removed during cleanup.
|
|
99
|
+
*/
|
|
100
|
+
#gracefulShutdownHandlers = {};
|
|
101
|
+
/**
|
|
102
|
+
* Reference to the crawlee status message forwarder, so it can be removed during cleanup.
|
|
103
|
+
*/
|
|
104
|
+
#statusMessageForwarder;
|
|
105
|
+
#chargingManager;
|
|
106
|
+
/** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
|
|
107
|
+
#abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
|
|
108
|
+
/** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
|
|
109
|
+
#requestQueueAccess = 'single';
|
|
110
|
+
/** Lazily built by the `#storageBackend` getter. */
|
|
111
|
+
#cachedStorageBackend;
|
|
112
|
+
/** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
|
|
113
|
+
#pendingListeners = [];
|
|
39
114
|
constructor(options = {}) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
Object.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
* Default {@link EventManager} instance.
|
|
62
|
-
* @internal
|
|
63
|
-
*/
|
|
64
|
-
Object.defineProperty(this, "eventManager", {
|
|
65
|
-
enumerable: true,
|
|
66
|
-
configurable: true,
|
|
67
|
-
writable: true,
|
|
68
|
-
value: void 0
|
|
69
|
-
});
|
|
70
|
-
/**
|
|
71
|
-
* Whether the Actor instance was initialized. This is set by calling {@link Actor.init}.
|
|
72
|
-
*/
|
|
73
|
-
Object.defineProperty(this, "initialized", {
|
|
74
|
-
enumerable: true,
|
|
75
|
-
configurable: true,
|
|
76
|
-
writable: true,
|
|
77
|
-
value: false
|
|
78
|
-
});
|
|
79
|
-
/**
|
|
80
|
-
* Set if the Actor called a method that requires the instance to be initialized, but did not do so.
|
|
81
|
-
* A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
|
|
82
|
-
*/
|
|
83
|
-
Object.defineProperty(this, "warnedAboutMissingInitCall", {
|
|
84
|
-
enumerable: true,
|
|
85
|
-
configurable: true,
|
|
86
|
-
writable: true,
|
|
87
|
-
value: false
|
|
88
|
-
});
|
|
89
|
-
/**
|
|
90
|
-
* Set if the Actor is currently rebooting.
|
|
91
|
-
*/
|
|
92
|
-
Object.defineProperty(this, "isRebooting", {
|
|
93
|
-
enumerable: true,
|
|
94
|
-
configurable: true,
|
|
95
|
-
writable: true,
|
|
96
|
-
value: false
|
|
97
|
-
});
|
|
98
|
-
/**
|
|
99
|
-
* Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
|
|
100
|
-
*/
|
|
101
|
-
Object.defineProperty(this, "isExiting", {
|
|
102
|
-
enumerable: true,
|
|
103
|
-
configurable: true,
|
|
104
|
-
writable: true,
|
|
105
|
-
value: false
|
|
106
|
-
});
|
|
107
|
-
/**
|
|
108
|
-
* References to graceful shutdown handlers so they can be removed during cleanup.
|
|
109
|
-
*/
|
|
110
|
-
Object.defineProperty(this, "gracefulShutdownHandlers", {
|
|
111
|
-
enumerable: true,
|
|
112
|
-
configurable: true,
|
|
113
|
-
writable: true,
|
|
114
|
-
value: {}
|
|
115
|
-
});
|
|
116
|
-
Object.defineProperty(this, "chargingManager", {
|
|
117
|
-
enumerable: true,
|
|
118
|
-
configurable: true,
|
|
119
|
-
writable: true,
|
|
120
|
-
value: void 0
|
|
121
|
-
});
|
|
122
|
-
/**
|
|
123
|
-
* Tracks which aliased storages have been purged during this session,
|
|
124
|
-
* so we only purge them once (on first open) when running locally.
|
|
125
|
-
* @internal
|
|
126
|
-
*/
|
|
127
|
-
Object.defineProperty(this, "purgedStorageAliases", {
|
|
128
|
-
enumerable: true,
|
|
129
|
-
configurable: true,
|
|
130
|
-
writable: true,
|
|
131
|
-
value: new Set()
|
|
132
|
-
});
|
|
133
|
-
// use default configuration object if nothing overridden (it fallbacks to env vars)
|
|
134
|
-
this.config = Object.keys(options).length === 0 ? configuration_js_1.Configuration.getGlobalConfig() : new configuration_js_1.Configuration(options);
|
|
115
|
+
const { configuration, ...configOptions } = options;
|
|
116
|
+
if (configuration) {
|
|
117
|
+
// BYO Configuration takes precedence; field-level overrides are
|
|
118
|
+
// ignored to keep the contract unambiguous. It must be the SDK's
|
|
119
|
+
// Configuration subclass, not a bare crawlee one — env-var
|
|
120
|
+
// resolution is driven by the subclass's `static fields`
|
|
121
|
+
// (`apifyConfigFields`) at construction, so a crawlee instance
|
|
122
|
+
// would silently expose none of the `APIFY_*`/`ACTOR_*` values.
|
|
123
|
+
if (!(configuration instanceof Configuration)) {
|
|
124
|
+
throw new Error('Actor `configuration` must be an Apify SDK Configuration (imported from `apify`), ' +
|
|
125
|
+
'not a crawlee Configuration, otherwise APIFY_*/ACTOR_* environment variables are not resolved.');
|
|
126
|
+
}
|
|
127
|
+
this.configuration = configuration;
|
|
128
|
+
}
|
|
129
|
+
else if (Object.keys(configOptions).length === 0) {
|
|
130
|
+
// use default configuration object if nothing overridden (it fallbacks to env vars)
|
|
131
|
+
this.configuration = Configuration.getGlobalConfiguration();
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
this.configuration = new Configuration(configOptions);
|
|
135
|
+
}
|
|
135
136
|
this.apifyClient = this.newClient();
|
|
136
|
-
this.eventManager = new
|
|
137
|
-
|
|
137
|
+
this.eventManager = new PlatformEventManager(this.configuration, {
|
|
138
|
+
[ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
|
|
139
|
+
});
|
|
140
|
+
this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
|
|
141
|
+
this.#childRunTracker = new ChildRunTracker();
|
|
138
142
|
}
|
|
139
143
|
/**
|
|
140
144
|
* Runs the main user function that performs the job of the Actor
|
|
@@ -171,24 +175,22 @@ class Actor {
|
|
|
171
175
|
*
|
|
172
176
|
* If the user function returns a promise, it is considered asynchronous:
|
|
173
177
|
* ```js
|
|
174
|
-
* import { gotScraping } from 'got-scraping';
|
|
175
|
-
*
|
|
176
178
|
* await Actor.main(() => {
|
|
177
179
|
* // My asynchronous function that returns a promise
|
|
178
|
-
* return
|
|
179
|
-
*
|
|
180
|
-
*
|
|
180
|
+
* return fetch('http://www.example.com')
|
|
181
|
+
* .then((response) => response.text())
|
|
182
|
+
* .then((html) => {
|
|
183
|
+
* console.log(html);
|
|
184
|
+
* });
|
|
181
185
|
* });
|
|
182
186
|
* ```
|
|
183
187
|
*
|
|
184
188
|
* To simplify your code, you can take advantage of the `async`/`await` keywords:
|
|
185
189
|
*
|
|
186
190
|
* ```js
|
|
187
|
-
* import { gotScraping } from 'got-scraping';
|
|
188
|
-
*
|
|
189
191
|
* await Actor.main(async () => {
|
|
190
192
|
* // My asynchronous function
|
|
191
|
-
* const html = await
|
|
193
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
192
194
|
* console.log(html);
|
|
193
195
|
* });
|
|
194
196
|
* ```
|
|
@@ -210,10 +212,8 @@ class Actor {
|
|
|
210
212
|
await this.exit(options);
|
|
211
213
|
}
|
|
212
214
|
catch (err) {
|
|
213
|
-
|
|
214
|
-
await this.exit({
|
|
215
|
-
exitCode: exports.EXIT_CODES.ERROR_USER_FUNCTION_THREW,
|
|
216
|
-
});
|
|
215
|
+
log.exception(err, err.message);
|
|
216
|
+
await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
|
|
217
217
|
}
|
|
218
218
|
return ret;
|
|
219
219
|
})();
|
|
@@ -223,99 +223,121 @@ class Actor {
|
|
|
223
223
|
*/
|
|
224
224
|
async init(options = {}) {
|
|
225
225
|
if (this.initialized) {
|
|
226
|
-
|
|
226
|
+
log.debug(`Actor SDK was already initialized`);
|
|
227
227
|
return;
|
|
228
228
|
}
|
|
229
229
|
// If the warning about forgotten init call was emitted, we will not continue the init procedure.
|
|
230
|
-
if (this
|
|
230
|
+
if (this.#warnedAboutMissingInitCall) {
|
|
231
231
|
throw new Error([
|
|
232
232
|
'Actor.init() was called after a method that would access a storage client was used.',
|
|
233
233
|
'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
|
|
234
234
|
].join('\n'));
|
|
235
235
|
}
|
|
236
236
|
this.initialized = true;
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
//
|
|
240
|
-
|
|
237
|
+
checkCrawleeVersion();
|
|
238
|
+
log.info('System info', getSystemInfo());
|
|
239
|
+
// Register this Actor's config as the global one so crawlee storages and
|
|
240
|
+
// the event manager resolve the same instance (`availableMemoryRatio` /
|
|
241
|
+
// `disableBrowserSandbox` at-home defaults now live in `Configuration`).
|
|
242
|
+
serviceLocator.setConfiguration(this.configuration);
|
|
243
|
+
this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
|
|
241
244
|
if (this.isAtHome()) {
|
|
242
|
-
this.
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
this.
|
|
245
|
+
serviceLocator.setEventManager(this.eventManager);
|
|
246
|
+
}
|
|
247
|
+
if (!serviceLocator.getServicesIfSet().storageBackend) {
|
|
248
|
+
this.installStorageBackend(options.storage ?? this.#storageBackend);
|
|
246
249
|
}
|
|
247
250
|
else if (options.storage) {
|
|
248
|
-
this.
|
|
251
|
+
this.installStorageBackend(options.storage);
|
|
249
252
|
}
|
|
250
|
-
// Init the event manager the config uses
|
|
251
|
-
await this.config.getEventManager().init();
|
|
252
|
-
log_1.default.debug(`Events initialized`);
|
|
253
253
|
// Register handlers for aborting and migrating events for automatic graceful shutdown.
|
|
254
254
|
// - aborting: calls Actor.exit() to terminate the run gracefully
|
|
255
255
|
// - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
|
|
256
256
|
// Using setTimeout to avoid deadlock with waitForAllListenersToComplete() in exit()/reboot()
|
|
257
257
|
if (options.gracefulShutdown !== false) {
|
|
258
258
|
const delay = options.gracefulShutdownDelayMillis ?? 0;
|
|
259
|
-
this
|
|
259
|
+
this.#gracefulShutdownHandlers.aborting = () => {
|
|
260
260
|
setTimeout(() => {
|
|
261
261
|
this.exit().catch((err) => {
|
|
262
|
-
|
|
262
|
+
log.exception(err, 'Failed to exit gracefully');
|
|
263
263
|
});
|
|
264
264
|
}, delay);
|
|
265
265
|
};
|
|
266
|
-
this.on(
|
|
267
|
-
this
|
|
266
|
+
this.on(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
|
|
267
|
+
this.#gracefulShutdownHandlers.migrating = () => {
|
|
268
268
|
setTimeout(() => {
|
|
269
269
|
this.reboot().catch((err) => {
|
|
270
|
-
|
|
270
|
+
log.exception(err, 'Failed to reboot on migration');
|
|
271
271
|
});
|
|
272
272
|
}, delay);
|
|
273
273
|
};
|
|
274
|
-
this.on(
|
|
274
|
+
this.on(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
|
|
275
|
+
}
|
|
276
|
+
// Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
|
|
277
|
+
this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
|
|
278
|
+
this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
|
|
279
|
+
// Attach listeners queued before init(), then connect to the platform events only after all handlers
|
|
280
|
+
// are registered, so that an event sent right after the connection opens (e.g. an already pending
|
|
281
|
+
// `aborting`) is not missed.
|
|
282
|
+
const events = serviceLocator.getEventManager();
|
|
283
|
+
if (this.#pendingListeners.length > 0) {
|
|
284
|
+
for (const [event, listener] of this.#pendingListeners) {
|
|
285
|
+
events.on(event, listener);
|
|
286
|
+
}
|
|
287
|
+
log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
|
|
288
|
+
this.#pendingListeners = [];
|
|
275
289
|
}
|
|
276
|
-
await (
|
|
277
|
-
|
|
290
|
+
await events.init();
|
|
291
|
+
log.debug(`Events initialized`);
|
|
292
|
+
await purgeDefaultStorages({
|
|
293
|
+
configuration: this.configuration,
|
|
278
294
|
onlyPurgeOnce: true,
|
|
279
295
|
});
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
await this
|
|
283
|
-
|
|
296
|
+
log.debug(`Default storages purged`);
|
|
297
|
+
await this.#childRunTracker.load();
|
|
298
|
+
await this.#chargingManager.init();
|
|
299
|
+
log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
|
|
300
|
+
// Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
|
|
301
|
+
// registered with crawlee directly; the storages the Actor installs itself are wrapped.
|
|
302
|
+
if (this.#chargingManager.isPayPerEvent && !this.#chargesDefaultDatasetItems()) {
|
|
303
|
+
log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
|
|
304
|
+
'storage - the platform only counts items it stores itself.');
|
|
305
|
+
}
|
|
284
306
|
}
|
|
285
307
|
/**
|
|
286
308
|
* @ignore
|
|
287
309
|
*/
|
|
288
310
|
async exit(messageOrOptions, options = {}) {
|
|
289
311
|
// Prevent double-exit from graceful shutdown handlers
|
|
290
|
-
if (this
|
|
291
|
-
|
|
312
|
+
if (this.#isExiting) {
|
|
313
|
+
log.debug('Actor.exit() called while already exiting, skipping');
|
|
292
314
|
return;
|
|
293
315
|
}
|
|
294
|
-
this
|
|
316
|
+
this.#isExiting = true;
|
|
295
317
|
options =
|
|
296
318
|
typeof messageOrOptions === 'string'
|
|
297
319
|
? { ...options, statusMessage: messageOrOptions }
|
|
298
320
|
: { ...messageOrOptions, ...options };
|
|
299
|
-
options.exit
|
|
300
|
-
options.exitCode
|
|
301
|
-
options.timeoutSecs
|
|
302
|
-
this.
|
|
303
|
-
const client =
|
|
304
|
-
const events =
|
|
321
|
+
options.exit ??= true;
|
|
322
|
+
options.exitCode ??= EXIT_CODES.SUCCESS;
|
|
323
|
+
options.timeoutSecs ??= 30;
|
|
324
|
+
this.ensureActorInit('exit');
|
|
325
|
+
const client = serviceLocator.getStorageBackend();
|
|
326
|
+
const events = serviceLocator.getEventManager();
|
|
305
327
|
// Remove graceful shutdown handlers to prevent them from interfering with exit
|
|
306
|
-
if (this
|
|
307
|
-
this.off(
|
|
328
|
+
if (this.#gracefulShutdownHandlers.aborting) {
|
|
329
|
+
this.off(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
|
|
308
330
|
}
|
|
309
|
-
if (this
|
|
310
|
-
this.off(
|
|
331
|
+
if (this.#gracefulShutdownHandlers.migrating) {
|
|
332
|
+
this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
|
|
311
333
|
}
|
|
312
334
|
// Close the event manager and emit the final PERSIST_STATE event
|
|
313
335
|
await events.close();
|
|
314
|
-
|
|
336
|
+
log.debug(`Events closed`);
|
|
315
337
|
// Emit the exit event
|
|
316
|
-
events.emit(
|
|
338
|
+
events.emit(EventType.EXIT, options);
|
|
317
339
|
// Wait for all event listeners to be processed
|
|
318
|
-
|
|
340
|
+
log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
|
|
319
341
|
if (options.exit) {
|
|
320
342
|
// `addTimeoutToPromise` is a cooperative timeout. This ensures that the process exits
|
|
321
343
|
// after the timeout, even if the event listeners don't trigger the timeout.
|
|
@@ -323,13 +345,18 @@ class Actor {
|
|
|
323
345
|
process.exit(options.exitCode);
|
|
324
346
|
}, options.timeoutSecs * 1000);
|
|
325
347
|
}
|
|
326
|
-
await
|
|
348
|
+
await addTimeoutToPromise(async () => {
|
|
327
349
|
await events.waitForAllListenersToComplete();
|
|
350
|
+
// The final status messages have been forwarded by now; stop listening so
|
|
351
|
+
// that a periodic one can't overwrite the terminal message set below.
|
|
352
|
+
if (this.#statusMessageForwarder) {
|
|
353
|
+
this.off(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
|
|
354
|
+
}
|
|
328
355
|
if (client.teardown) {
|
|
329
356
|
let finished = false;
|
|
330
357
|
setTimeout(() => {
|
|
331
358
|
if (!finished) {
|
|
332
|
-
|
|
359
|
+
log.info('Waiting for the storage to write its state to file system.');
|
|
333
360
|
}
|
|
334
361
|
}, 1000);
|
|
335
362
|
await client.teardown();
|
|
@@ -341,7 +368,7 @@ class Actor {
|
|
|
341
368
|
level: options.exitCode > 0 ? 'ERROR' : 'INFO',
|
|
342
369
|
});
|
|
343
370
|
// Waiting 1ms is enough for the network request to be sent. We don't need to wait for the response.
|
|
344
|
-
await Promise.race([statusMessagePromise,
|
|
371
|
+
await Promise.race([statusMessagePromise, sleep(1)]);
|
|
345
372
|
}
|
|
346
373
|
}, options.timeoutSecs * 1000, `Waiting for all event listeners to complete their execution timed out after ${options.timeoutSecs} seconds`).catch(() => {
|
|
347
374
|
if (options.exit) {
|
|
@@ -350,7 +377,7 @@ class Actor {
|
|
|
350
377
|
});
|
|
351
378
|
// Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
|
|
352
379
|
// When process.exit() actually terminates the process, this line is never reached - which is fine.
|
|
353
|
-
this
|
|
380
|
+
this.#isExiting = false;
|
|
354
381
|
if (!options.exit) {
|
|
355
382
|
return;
|
|
356
383
|
}
|
|
@@ -360,19 +387,30 @@ class Actor {
|
|
|
360
387
|
* @ignore
|
|
361
388
|
*/
|
|
362
389
|
async fail(messageOrOptions, options = {}) {
|
|
363
|
-
|
|
390
|
+
const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
|
|
391
|
+
return this.exit(messageOrOptions, { ...options, exitCode });
|
|
364
392
|
}
|
|
365
393
|
/**
|
|
366
394
|
* @ignore
|
|
367
395
|
*/
|
|
368
396
|
on(event, listener) {
|
|
369
|
-
|
|
397
|
+
// Before init() the service locator must stay untouched, otherwise it
|
|
398
|
+
// creates a default Configuration that init() then conflicts with.
|
|
399
|
+
if (!this.initialized) {
|
|
400
|
+
this.#pendingListeners.push([event, listener]);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
serviceLocator.getEventManager().on(event, listener);
|
|
370
404
|
}
|
|
371
405
|
/**
|
|
372
406
|
* @ignore
|
|
373
407
|
*/
|
|
374
408
|
off(event, listener) {
|
|
375
|
-
this.
|
|
409
|
+
if (!this.initialized) {
|
|
410
|
+
this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
serviceLocator.getEventManager().off(event, listener);
|
|
376
414
|
}
|
|
377
415
|
/**
|
|
378
416
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -392,17 +430,33 @@ class Actor {
|
|
|
392
430
|
* @param actorId
|
|
393
431
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
394
432
|
* @param [input]
|
|
395
|
-
* Input for the Actor.
|
|
396
|
-
*
|
|
397
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
433
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
434
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
398
435
|
* @param [options]
|
|
399
436
|
* @ignore
|
|
400
437
|
*/
|
|
401
438
|
async call(actorId, input, options = {}) {
|
|
402
|
-
const
|
|
403
|
-
const { token, ...rest } = options;
|
|
439
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
440
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
404
441
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
405
|
-
|
|
442
|
+
if (abortWithParent && !runName)
|
|
443
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
444
|
+
if (!runName)
|
|
445
|
+
return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
|
|
446
|
+
const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
447
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
448
|
+
const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
449
|
+
// The earlier part of a resumed run's log was already redirected before the migration.
|
|
450
|
+
const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
|
|
451
|
+
streamedLog?.start();
|
|
452
|
+
try {
|
|
453
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
454
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
455
|
+
return finishedRun;
|
|
456
|
+
}
|
|
457
|
+
finally {
|
|
458
|
+
await streamedLog?.stop();
|
|
459
|
+
}
|
|
406
460
|
}
|
|
407
461
|
/**
|
|
408
462
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
@@ -422,17 +476,22 @@ class Actor {
|
|
|
422
476
|
* @param actorId
|
|
423
477
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
424
478
|
* @param [input]
|
|
425
|
-
* Input for the Actor.
|
|
426
|
-
*
|
|
427
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
479
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
480
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
428
481
|
* @param [options]
|
|
429
482
|
* @ignore
|
|
430
483
|
*/
|
|
431
484
|
async start(actorId, input, options = {}) {
|
|
432
|
-
const
|
|
433
|
-
const { token, ...rest } = options;
|
|
485
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
486
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
434
487
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
435
|
-
|
|
488
|
+
if (abortWithParent && !runName)
|
|
489
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
490
|
+
if (!runName)
|
|
491
|
+
return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
|
|
492
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
493
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
|
|
494
|
+
return run;
|
|
436
495
|
}
|
|
437
496
|
/**
|
|
438
497
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -452,12 +511,35 @@ class Actor {
|
|
|
452
511
|
async abort(runId, options = {}) {
|
|
453
512
|
const { token, statusMessage, ...rest } = options;
|
|
454
513
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
514
|
+
const runClient = client.run(runId);
|
|
455
515
|
if (statusMessage) {
|
|
456
|
-
await
|
|
457
|
-
isStatusMessageTerminal: true,
|
|
458
|
-
});
|
|
516
|
+
await runClient.update({ statusMessage, isStatusMessageTerminal: true });
|
|
459
517
|
}
|
|
460
|
-
return
|
|
518
|
+
return runClient.abort(rest);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
522
|
+
*
|
|
523
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
524
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
525
|
+
*
|
|
526
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
527
|
+
*
|
|
528
|
+
* For more information about Actors, read the
|
|
529
|
+
* [documentation](https://docs.apify.com/actor).
|
|
530
|
+
*
|
|
531
|
+
* **Example usage:**
|
|
532
|
+
*
|
|
533
|
+
* ```js
|
|
534
|
+
* const run = await Actor.resurrect(runId);
|
|
535
|
+
* ```
|
|
536
|
+
* @ignore
|
|
537
|
+
*/
|
|
538
|
+
async resurrect(runId, options = {}) {
|
|
539
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
540
|
+
const { token, timeout: _timeout, ...rest } = options;
|
|
541
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
542
|
+
return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
|
|
461
543
|
}
|
|
462
544
|
/**
|
|
463
545
|
* Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
@@ -486,10 +568,70 @@ class Actor {
|
|
|
486
568
|
* @ignore
|
|
487
569
|
*/
|
|
488
570
|
async callTask(taskId, input, options = {}) {
|
|
489
|
-
const
|
|
490
|
-
const { token, ...rest } = options;
|
|
571
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
572
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
491
573
|
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
492
|
-
|
|
574
|
+
if (abortWithParent && !runName)
|
|
575
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
576
|
+
if (!runName)
|
|
577
|
+
return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
|
|
578
|
+
const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
|
|
579
|
+
const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
|
|
580
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
581
|
+
const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
|
|
582
|
+
await this.#childRunTracker.update(runName, finishedRun);
|
|
583
|
+
return finishedRun;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
587
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
588
|
+
*
|
|
589
|
+
* ```js
|
|
590
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
591
|
+
* ```
|
|
592
|
+
*
|
|
593
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
594
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
595
|
+
* under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
|
|
596
|
+
*/
|
|
597
|
+
get childRuns() {
|
|
598
|
+
this.ensureActorInit('childRuns');
|
|
599
|
+
return this.#childRunTracker.getRunClients(this.apifyClient);
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
603
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
604
|
+
*
|
|
605
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
606
|
+
*
|
|
607
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
608
|
+
*
|
|
609
|
+
* **Example usage:**
|
|
610
|
+
*
|
|
611
|
+
* ```js
|
|
612
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
613
|
+
* ```
|
|
614
|
+
*
|
|
615
|
+
* @param taskId
|
|
616
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
617
|
+
* @param [input]
|
|
618
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
619
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
620
|
+
* Provided input will be merged with Actor task input.
|
|
621
|
+
* @param [options]
|
|
622
|
+
* @ignore
|
|
623
|
+
*/
|
|
624
|
+
async startTask(taskId, input, options = {}) {
|
|
625
|
+
const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
|
|
626
|
+
const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
|
|
627
|
+
const client = token ? this.newClient({ token }) : this.apifyClient;
|
|
628
|
+
if (abortWithParent && !runName)
|
|
629
|
+
throw new Error('`abortWithParent` requires `runName`.');
|
|
630
|
+
if (!runName)
|
|
631
|
+
return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
|
|
632
|
+
const startOptions = { ...rest, runTimeoutSecs };
|
|
633
|
+
const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
|
|
634
|
+
return run;
|
|
493
635
|
}
|
|
494
636
|
/**
|
|
495
637
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
@@ -499,22 +641,21 @@ class Actor {
|
|
|
499
641
|
* @param targetActorId
|
|
500
642
|
* Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
|
|
501
643
|
* @param [input]
|
|
502
|
-
* Input for the Actor.
|
|
503
|
-
*
|
|
504
|
-
* Otherwise, the `options.contentType` parameter must be provided.
|
|
644
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
645
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
505
646
|
* @param [options]
|
|
506
647
|
* @ignore
|
|
507
648
|
*/
|
|
508
649
|
async metamorph(targetActorId, input, options = {}) {
|
|
509
650
|
if (!this.isAtHome()) {
|
|
510
|
-
|
|
651
|
+
log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
|
|
511
652
|
return;
|
|
512
653
|
}
|
|
513
|
-
const { customAfterSleepMillis = this.
|
|
514
|
-
const runId = this.
|
|
654
|
+
const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
|
|
655
|
+
const runId = this.configuration.actorRunId;
|
|
515
656
|
await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
|
|
516
657
|
// Wait some time for container to be stopped.
|
|
517
|
-
await
|
|
658
|
+
await sleep(customAfterSleepMillis);
|
|
518
659
|
}
|
|
519
660
|
/**
|
|
520
661
|
* Internally reboots this Actor. The system stops the current container and starts
|
|
@@ -524,34 +665,34 @@ class Actor {
|
|
|
524
665
|
* @ignore
|
|
525
666
|
*/
|
|
526
667
|
async reboot(options = {}) {
|
|
527
|
-
this.
|
|
668
|
+
this.ensureActorInit('reboot');
|
|
528
669
|
if (!this.isAtHome()) {
|
|
529
|
-
|
|
670
|
+
log.warning('Actor.reboot() is only supported when running on the Apify platform.');
|
|
530
671
|
return;
|
|
531
672
|
}
|
|
532
|
-
if (this
|
|
533
|
-
|
|
673
|
+
if (this.#isRebooting) {
|
|
674
|
+
log.debug('Actor is already rebooting, skipping the additional reboot call.');
|
|
534
675
|
return;
|
|
535
676
|
}
|
|
536
|
-
this
|
|
677
|
+
this.#isRebooting = true;
|
|
537
678
|
// Waiting for all the listeners to finish, as `.reboot()` kills the container.
|
|
538
679
|
await Promise.all([
|
|
539
680
|
// `persistState` for individual RequestLists, RequestQueue... instances to be persisted
|
|
540
|
-
...
|
|
681
|
+
...serviceLocator
|
|
541
682
|
.getEventManager()
|
|
542
|
-
.listeners(
|
|
683
|
+
.listeners(EventType.PERSIST_STATE)
|
|
543
684
|
.map(async (x) => x({})),
|
|
544
685
|
// `migrating` to pause Apify crawlers
|
|
545
|
-
...
|
|
686
|
+
...serviceLocator
|
|
546
687
|
.getEventManager()
|
|
547
|
-
.listeners(
|
|
688
|
+
.listeners(EventType.MIGRATING)
|
|
548
689
|
.map(async (x) => x({})),
|
|
549
690
|
]);
|
|
550
|
-
const runId = this.
|
|
691
|
+
const runId = this.configuration.actorRunId;
|
|
551
692
|
await this.apifyClient.run(runId).reboot();
|
|
552
693
|
// Wait some time for container to be stopped.
|
|
553
|
-
const { customAfterSleepMillis = this.
|
|
554
|
-
await
|
|
694
|
+
const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
|
|
695
|
+
await sleep(customAfterSleepMillis);
|
|
555
696
|
}
|
|
556
697
|
/**
|
|
557
698
|
* Creates an ad-hoc webhook for the current Actor run, which lets you receive a notification when the Actor run finished or failed.
|
|
@@ -566,25 +707,27 @@ class Actor {
|
|
|
566
707
|
* @ignore
|
|
567
708
|
*/
|
|
568
709
|
async addWebhook(options) {
|
|
569
|
-
(
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
710
|
+
parseArgument(options, z
|
|
711
|
+
.object({
|
|
712
|
+
eventTypes: z.array(z.string()),
|
|
713
|
+
requestUrl: z.string(),
|
|
714
|
+
payloadTemplate: z.string().optional(),
|
|
715
|
+
idempotencyKey: z.string().optional(),
|
|
716
|
+
headersTemplate: z.string().optional(),
|
|
717
|
+
description: z.string().optional(),
|
|
718
|
+
ignoreSslErrors: z.boolean().optional(),
|
|
719
|
+
doNotRetry: z.boolean().optional(),
|
|
720
|
+
shouldInterpolateStrings: z.boolean().optional(),
|
|
721
|
+
isApifyIntegration: z.boolean().optional(),
|
|
722
|
+
})
|
|
723
|
+
.strict());
|
|
581
724
|
if (!this.isAtHome()) {
|
|
582
|
-
|
|
725
|
+
log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
|
|
583
726
|
return undefined;
|
|
584
727
|
}
|
|
585
|
-
const runId = this.
|
|
728
|
+
const runId = this.configuration.actorRunId;
|
|
586
729
|
if (!runId) {
|
|
587
|
-
throw new Error(`Environment variable ${
|
|
730
|
+
throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
|
|
588
731
|
}
|
|
589
732
|
return this.apifyClient.webhooks().create({
|
|
590
733
|
...options,
|
|
@@ -597,45 +740,47 @@ class Actor {
|
|
|
597
740
|
/**
|
|
598
741
|
* Sets the status message for the current Actor run.
|
|
599
742
|
*
|
|
600
|
-
* @returns The
|
|
743
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
744
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
601
745
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
602
746
|
* @ignore
|
|
603
747
|
*/
|
|
604
748
|
async setStatusMessage(statusMessage, options) {
|
|
605
749
|
const { isStatusMessageTerminal, level } = options || {};
|
|
606
|
-
(
|
|
607
|
-
(
|
|
608
|
-
this.
|
|
750
|
+
parseArgument(statusMessage, z.string());
|
|
751
|
+
parseArgument(isStatusMessageTerminal, z.boolean().optional());
|
|
752
|
+
this.ensureActorInit('setStatusMessage');
|
|
609
753
|
const loggedStatusMessage = `[Status message]: ${statusMessage}`;
|
|
610
754
|
switch (level) {
|
|
611
755
|
case 'DEBUG':
|
|
612
|
-
|
|
756
|
+
log.debug(loggedStatusMessage);
|
|
613
757
|
break;
|
|
614
758
|
case 'WARNING':
|
|
615
|
-
|
|
759
|
+
log.warning(loggedStatusMessage);
|
|
616
760
|
break;
|
|
617
761
|
case 'ERROR':
|
|
618
|
-
|
|
762
|
+
log.error(loggedStatusMessage);
|
|
619
763
|
break;
|
|
620
764
|
default:
|
|
621
|
-
|
|
765
|
+
log.info(loggedStatusMessage);
|
|
622
766
|
break;
|
|
623
767
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
if (run) {
|
|
635
|
-
return run;
|
|
636
|
-
}
|
|
768
|
+
return this.#updateRunStatusMessage(statusMessage, isStatusMessageTerminal);
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Propagates a status message to the current run, without logging it locally.
|
|
772
|
+
* Resolves `undefined` when there is no run to update, or when the update failed or timed out.
|
|
773
|
+
*/
|
|
774
|
+
async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
|
|
775
|
+
const runId = this.configuration.actorRunId;
|
|
776
|
+
if (!runId) {
|
|
777
|
+
return undefined;
|
|
637
778
|
}
|
|
638
|
-
|
|
779
|
+
// just to be sure, this should be fast
|
|
780
|
+
return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
|
|
781
|
+
log.warning(e.message);
|
|
782
|
+
return undefined;
|
|
783
|
+
});
|
|
639
784
|
}
|
|
640
785
|
/**
|
|
641
786
|
* Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
|
|
@@ -657,27 +802,63 @@ class Actor {
|
|
|
657
802
|
* **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
|
|
658
803
|
* otherwise the Actor process might finish before the data are stored!
|
|
659
804
|
*
|
|
805
|
+
* Inside a crawlee storage transaction, the items are stored - and charged for - at commit time,
|
|
806
|
+
* so the returned counts are zero and charging for an explicit `eventName` is rejected outright.
|
|
807
|
+
*
|
|
660
808
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
661
809
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
662
810
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
663
811
|
* @ignore
|
|
664
812
|
*/
|
|
665
813
|
async pushData(item, eventName) {
|
|
666
|
-
this.
|
|
814
|
+
this.ensureActorInit('pushData');
|
|
667
815
|
if (eventName?.startsWith('apify-')) {
|
|
668
816
|
throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
|
|
669
817
|
}
|
|
818
|
+
if (eventName !== undefined) {
|
|
819
|
+
rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
|
|
820
|
+
'so a rolled-back request would be billed for items that were never stored.');
|
|
821
|
+
}
|
|
670
822
|
const dataset = await this.openDataset();
|
|
671
|
-
|
|
672
|
-
//
|
|
673
|
-
//
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
if (this.usesPushDataInterception(dataset)) {
|
|
678
|
-
return await this.pushDataViaInterceptedClient(dataset, item, eventName);
|
|
823
|
+
const items = Array.isArray(item) ? item : [item];
|
|
824
|
+
// `Actor.pushData()` historically worked even without calling `Actor.init()`.
|
|
825
|
+
// In that case, charging isn't configured, so just push the data through.
|
|
826
|
+
if (!this.#chargingManager.isInitialized) {
|
|
827
|
+
await dataset.pushData(items);
|
|
828
|
+
return { eventChargeLimitReached: false, chargedCount: 0, chargeableWithinLimit: {} };
|
|
679
829
|
}
|
|
680
|
-
|
|
830
|
+
// The reservation below and the charge that acts on it have to stay under one lock, so that
|
|
831
|
+
// a concurrent push cannot charge in between. The dataset backend re-enters the same lock to
|
|
832
|
+
// charge the synthetic per-item event.
|
|
833
|
+
return await this.#chargingManager.withChargeLock(async () => {
|
|
834
|
+
if (eventName === undefined) {
|
|
835
|
+
// Nothing to charge here - the dataset backend charges the synthetic event for
|
|
836
|
+
// whatever it stores, so the result is read back off the charging state.
|
|
837
|
+
const chargedBefore = this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT);
|
|
838
|
+
await dataset.pushData(items);
|
|
839
|
+
return {
|
|
840
|
+
eventChargeLimitReached: this.#chargingManager.isEventChargeLimitReached(DEFAULT_DATASET_ITEM_EVENT),
|
|
841
|
+
chargedCount: this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT) - chargedBefore,
|
|
842
|
+
chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
const limit = this.#chargingManager.calculatePushDataLimit(items.length, {
|
|
846
|
+
eventName,
|
|
847
|
+
// Pushing one item charges the synthetic per-item event too when the dataset backend
|
|
848
|
+
// is the charging one, so that price is part of what an item costs here. Only the Actor's
|
|
849
|
+
// own backend wraps the default dataset for charging, a caller-supplied one is left as is.
|
|
850
|
+
isDefaultDataset: serviceLocator.getStorageBackend() === this.#cachedStorageBackend,
|
|
851
|
+
});
|
|
852
|
+
if (limit === 0) {
|
|
853
|
+
return {
|
|
854
|
+
eventChargeLimitReached: items.length > 0,
|
|
855
|
+
chargedCount: 0,
|
|
856
|
+
chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
await dataset.pushData(limit < items.length ? items.slice(0, limit) : items);
|
|
860
|
+
return await this.#chargingManager.charge({ eventName, count: limit });
|
|
861
|
+
});
|
|
681
862
|
}
|
|
682
863
|
/**
|
|
683
864
|
* Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
|
|
@@ -691,50 +872,24 @@ class Actor {
|
|
|
691
872
|
* @param [datasetIdOrName]
|
|
692
873
|
* ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
|
|
693
874
|
* the function returns the default dataset associated with the Actor run.
|
|
694
|
-
* You can also pass `{ alias: '
|
|
695
|
-
*
|
|
875
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
876
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
696
877
|
* @param [options]
|
|
697
878
|
* @ignore
|
|
698
879
|
*/
|
|
699
880
|
async openDataset(datasetIdOrName, options = {}) {
|
|
700
|
-
(
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
881
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
882
|
+
this.ensureActorInit('openDataset');
|
|
883
|
+
return Dataset.open(datasetIdOrName ?? null, {
|
|
884
|
+
storageBackend: options.forceCloud
|
|
885
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
886
|
+
: undefined,
|
|
887
|
+
});
|
|
705
888
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
*
|
|
709
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
710
|
-
* For example, calling the following code:
|
|
711
|
-
* ```js
|
|
712
|
-
* const value = await Actor.getValue('my-key');
|
|
713
|
-
* ```
|
|
714
|
-
*
|
|
715
|
-
* is equivalent to:
|
|
716
|
-
* ```js
|
|
717
|
-
* const store = await Actor.openKeyValueStore();
|
|
718
|
-
* const value = await store.getValue('my-key');
|
|
719
|
-
* ```
|
|
720
|
-
*
|
|
721
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
722
|
-
*
|
|
723
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
724
|
-
* and {@link KeyValueStore.getValue}.
|
|
725
|
-
*
|
|
726
|
-
* @param key Unique record key.
|
|
727
|
-
* @returns
|
|
728
|
-
* Returns a promise that resolves to an object, string
|
|
729
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
730
|
-
* on the MIME content type of the record, or `null`
|
|
731
|
-
* if the record is missing.
|
|
732
|
-
* @ignore
|
|
733
|
-
*/
|
|
734
|
-
async getValue(key) {
|
|
735
|
-
this._ensureActorInit('getValue');
|
|
889
|
+
async getValue(key, defaultValue) {
|
|
890
|
+
this.ensureActorInit('getValue');
|
|
736
891
|
const store = await this.openKeyValueStore();
|
|
737
|
-
return store.getValue(key);
|
|
892
|
+
return store.getValue(key, defaultValue);
|
|
738
893
|
}
|
|
739
894
|
/**
|
|
740
895
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -768,24 +923,28 @@ class Actor {
|
|
|
768
923
|
* @ignore
|
|
769
924
|
*/
|
|
770
925
|
async setValue(key, value, options = {}) {
|
|
771
|
-
this.
|
|
926
|
+
this.ensureActorInit('setValue');
|
|
772
927
|
const store = await this.openKeyValueStore();
|
|
773
928
|
return store.setValue(key, value, options);
|
|
774
929
|
}
|
|
775
930
|
/**
|
|
776
931
|
* Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
|
|
777
932
|
*
|
|
778
|
-
*
|
|
779
|
-
*
|
|
780
|
-
*
|
|
781
|
-
* const input = await Actor.getInput();
|
|
782
|
-
* ```
|
|
933
|
+
* The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`).
|
|
934
|
+
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
935
|
+
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
783
936
|
*
|
|
784
|
-
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
*
|
|
937
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
938
|
+
* working directory. A storage backend that doesn't read the default key-value store's directory under
|
|
939
|
+
* the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
|
|
940
|
+
*
|
|
941
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
942
|
+
* replaced with the links of their CSV exports.
|
|
943
|
+
*
|
|
944
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
945
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
946
|
+
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
947
|
+
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
|
|
789
948
|
*
|
|
790
949
|
* Note that the `getInput()` function does not cache the value read from the key-value store.
|
|
791
950
|
* If you need to use the input multiple times in your Actor,
|
|
@@ -797,40 +956,85 @@ class Actor {
|
|
|
797
956
|
* @returns
|
|
798
957
|
* Returns a promise that resolves to an object, string
|
|
799
958
|
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
800
|
-
* on the MIME content type of the record
|
|
801
|
-
*
|
|
959
|
+
* on the MIME content type of the record.
|
|
960
|
+
* @throws {ActorInputError} When the input cannot be produced; see `code`.
|
|
802
961
|
* @ignore
|
|
803
962
|
*/
|
|
804
963
|
async getInput() {
|
|
805
|
-
this.
|
|
806
|
-
const inputSecretsPrivateKeyFile = this.
|
|
807
|
-
|
|
808
|
-
const
|
|
964
|
+
this.ensureActorInit('getInput');
|
|
965
|
+
const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
|
|
966
|
+
// Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
|
|
967
|
+
const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
|
|
968
|
+
const store = await this.openKeyValueStore();
|
|
969
|
+
const record = await store.getRecord(inputKey);
|
|
970
|
+
// Not a conflict check: under the file-system backend the record *is* the store directory's file.
|
|
971
|
+
const storeInput = record
|
|
972
|
+
? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
|
|
973
|
+
: await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
|
|
974
|
+
const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
|
|
975
|
+
if (storeInput != null && cwdInput != null) {
|
|
976
|
+
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.`);
|
|
977
|
+
}
|
|
978
|
+
const rawInput = storeInput ?? cwdInput;
|
|
979
|
+
if (rawInput == null) {
|
|
980
|
+
const locations = [`the "${inputKey}" record of the default key-value store`];
|
|
981
|
+
if (!this.configuration.isAtHome) {
|
|
982
|
+
locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
|
|
983
|
+
}
|
|
984
|
+
throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
|
|
985
|
+
}
|
|
809
986
|
let input = rawInput;
|
|
810
|
-
if (
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
987
|
+
if (isNonEmptyObject(rawInput) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
|
|
988
|
+
try {
|
|
989
|
+
const privateKey = createPrivateKey({
|
|
990
|
+
key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
|
|
991
|
+
passphrase: inputSecretsPrivateKeyPassphrase,
|
|
992
|
+
});
|
|
993
|
+
input = decryptInputSecrets({ input: rawInput, privateKey });
|
|
994
|
+
}
|
|
995
|
+
catch (cause) {
|
|
996
|
+
throw new ActorInputError('DECRYPTION_FAILED', 'Failed to decrypt the secret fields of the input.', {
|
|
997
|
+
cause,
|
|
998
|
+
});
|
|
999
|
+
}
|
|
818
1000
|
}
|
|
819
|
-
if (
|
|
820
|
-
input = await this.inferDefaultsFromInputSchema(input);
|
|
1001
|
+
if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
|
|
1002
|
+
input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
|
|
821
1003
|
}
|
|
822
1004
|
return input;
|
|
823
1005
|
}
|
|
824
1006
|
/**
|
|
825
|
-
*
|
|
826
|
-
*
|
|
1007
|
+
* Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
|
|
1008
|
+
* whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
|
|
1009
|
+
* such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
|
|
1010
|
+
* {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
|
|
1011
|
+
*
|
|
1012
|
+
* @returns `undefined` when running on the platform or when neither file exists.
|
|
827
1013
|
*/
|
|
828
|
-
async
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
throw new Error('Input does not exist');
|
|
1014
|
+
async readInputFromDirectory(inputKey, directory, label) {
|
|
1015
|
+
if (this.configuration.isAtHome) {
|
|
1016
|
+
return undefined;
|
|
832
1017
|
}
|
|
833
|
-
|
|
1018
|
+
const candidates = [
|
|
1019
|
+
{ filename: inputKey, contentType: BINARY_CONTENT_TYPE },
|
|
1020
|
+
{ filename: `${inputKey}.json`, contentType: JSON_CONTENT_TYPE },
|
|
1021
|
+
];
|
|
1022
|
+
const found = [];
|
|
1023
|
+
for (const candidate of candidates) {
|
|
1024
|
+
const path = join(directory, candidate.filename);
|
|
1025
|
+
const stats = await stat(path).catch(() => null);
|
|
1026
|
+
if (stats?.isFile()) {
|
|
1027
|
+
found.push({ ...candidate, path });
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
if (found.length > 1) {
|
|
1031
|
+
throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
|
|
1032
|
+
}
|
|
1033
|
+
if (found.length === 0) {
|
|
1034
|
+
return undefined;
|
|
1035
|
+
}
|
|
1036
|
+
const [file] = found;
|
|
1037
|
+
return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
|
|
834
1038
|
}
|
|
835
1039
|
/**
|
|
836
1040
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
@@ -842,18 +1046,21 @@ class Actor {
|
|
|
842
1046
|
* For more details and code examples, see the {@link KeyValueStore} class.
|
|
843
1047
|
*
|
|
844
1048
|
* @param [storeIdOrName]
|
|
845
|
-
* ID or
|
|
1049
|
+
* ID, name, or alias of the key-value store to be opened. If `null` or `undefined`,
|
|
846
1050
|
* the function returns the default key-value store associated with the Actor run.
|
|
847
|
-
* You can also pass `{
|
|
1051
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1052
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
848
1053
|
* @param [options]
|
|
849
1054
|
* @ignore
|
|
850
1055
|
*/
|
|
851
1056
|
async openKeyValueStore(storeIdOrName, options = {}) {
|
|
852
|
-
(
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
1057
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
1058
|
+
this.ensureActorInit('openKeyValueStore');
|
|
1059
|
+
return KeyValueStore.open(storeIdOrName ?? null, {
|
|
1060
|
+
storageBackend: options.forceCloud
|
|
1061
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
1062
|
+
: undefined,
|
|
1063
|
+
});
|
|
857
1064
|
}
|
|
858
1065
|
/**
|
|
859
1066
|
* Opens a request queue and returns a promise resolving to an instance
|
|
@@ -867,21 +1074,21 @@ class Actor {
|
|
|
867
1074
|
* For more details and code examples, see the {@link RequestQueue} class.
|
|
868
1075
|
*
|
|
869
1076
|
* @param [queueIdOrName]
|
|
870
|
-
* ID or
|
|
1077
|
+
* ID, name, or alias of the request queue to be opened. If `null` or `undefined`,
|
|
871
1078
|
* the function returns the default request queue associated with the Actor run.
|
|
872
|
-
* You can also pass `{
|
|
1079
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1080
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
873
1081
|
* @param [options]
|
|
874
1082
|
* @ignore
|
|
875
1083
|
*/
|
|
876
1084
|
async openRequestQueue(queueIdOrName, options = {}) {
|
|
877
|
-
(
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
return queue;
|
|
1085
|
+
parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
|
|
1086
|
+
this.ensureActorInit('openRequestQueue');
|
|
1087
|
+
return RequestQueue.open(queueIdOrName ?? null, {
|
|
1088
|
+
storageBackend: options.forceCloud
|
|
1089
|
+
? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
|
|
1090
|
+
: undefined,
|
|
1091
|
+
});
|
|
885
1092
|
}
|
|
886
1093
|
/**
|
|
887
1094
|
* Creates a proxy configuration and returns a promise resolving to an instance
|
|
@@ -932,7 +1139,7 @@ class Actor {
|
|
|
932
1139
|
if (dontUseApifyProxy && dontUseCustomProxies) {
|
|
933
1140
|
return undefined;
|
|
934
1141
|
}
|
|
935
|
-
const proxyConfiguration = new
|
|
1142
|
+
const proxyConfiguration = new ProxyConfiguration(options, this.configuration);
|
|
936
1143
|
if (await proxyConfiguration.initialize({ checkAccess })) {
|
|
937
1144
|
return proxyConfiguration;
|
|
938
1145
|
}
|
|
@@ -956,23 +1163,23 @@ class Actor {
|
|
|
956
1163
|
* @ignore
|
|
957
1164
|
*/
|
|
958
1165
|
async charge(options) {
|
|
959
|
-
this.
|
|
960
|
-
return this
|
|
1166
|
+
this.ensureActorInit('charge');
|
|
1167
|
+
return this.#chargingManager.charge(options);
|
|
961
1168
|
}
|
|
962
1169
|
/**
|
|
963
1170
|
* Retrieve the charging manager to access granular pricing information.
|
|
964
1171
|
* @ignore
|
|
965
1172
|
*/
|
|
966
1173
|
getChargingManager() {
|
|
967
|
-
this.
|
|
968
|
-
return this
|
|
1174
|
+
this.ensureActorInit('getChargingManager');
|
|
1175
|
+
return this.#chargingManager;
|
|
969
1176
|
}
|
|
970
1177
|
/**
|
|
971
1178
|
* Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
|
|
972
1179
|
*/
|
|
973
1180
|
getModifiedActorEnvVars() {
|
|
974
1181
|
const modifiedActorEnvVars = {};
|
|
975
|
-
Object.entries(
|
|
1182
|
+
Object.entries(ACTOR_ENV_VARS).forEach(([k, v]) => {
|
|
976
1183
|
// Prepend `ACTOR_` to env vars so ApifyEnv structure is preserved
|
|
977
1184
|
if (['ID', 'RUN_ID', 'TASK_ID'].includes(k)) {
|
|
978
1185
|
modifiedActorEnvVars[`ACTOR_${k}`] = v;
|
|
@@ -996,20 +1203,25 @@ class Actor {
|
|
|
996
1203
|
const env = process.env || {};
|
|
997
1204
|
const envVars = {};
|
|
998
1205
|
for (const [shortName, fullName] of Object.entries({
|
|
999
|
-
...
|
|
1206
|
+
...APIFY_ENV_VARS,
|
|
1000
1207
|
...this.getModifiedActorEnvVars(),
|
|
1001
1208
|
})) {
|
|
1002
|
-
|
|
1209
|
+
if (IGNORED_ENV_VARS.includes(fullName))
|
|
1210
|
+
continue;
|
|
1211
|
+
const camelCaseName = snakeCaseToCamelCase(shortName);
|
|
1003
1212
|
let value = env[fullName];
|
|
1004
|
-
// Parse dates and integers.
|
|
1005
|
-
if (
|
|
1213
|
+
// Parse booleans, dates and integers.
|
|
1214
|
+
if (BOOLEAN_ENV_VARS.includes(fullName)) {
|
|
1215
|
+
value = !!value && coerceBoolean.parse(value);
|
|
1216
|
+
}
|
|
1217
|
+
else if (value && fullName.endsWith('_AT')) {
|
|
1006
1218
|
const unix = Date.parse(value);
|
|
1007
1219
|
value = unix > 0 ? new Date(unix) : undefined;
|
|
1008
1220
|
}
|
|
1009
|
-
else if (
|
|
1221
|
+
else if (INTEGER_ENV_VARS.includes(fullName)) {
|
|
1010
1222
|
value = parseInt(value, 10);
|
|
1011
1223
|
}
|
|
1012
|
-
Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
|
|
1224
|
+
Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
|
|
1013
1225
|
}
|
|
1014
1226
|
return envVars;
|
|
1015
1227
|
}
|
|
@@ -1022,20 +1234,15 @@ class Actor {
|
|
|
1022
1234
|
* @ignore
|
|
1023
1235
|
*/
|
|
1024
1236
|
newClient(options = {}) {
|
|
1025
|
-
const { storageDir, ...storageClientOptions } = this.
|
|
1026
|
-
const { apifyVersion, crawleeVersion } =
|
|
1027
|
-
return
|
|
1028
|
-
baseUrl: this.
|
|
1029
|
-
publicBaseUrl: this.
|
|
1030
|
-
token: this.
|
|
1237
|
+
const { storageDir, ...storageClientOptions } = (this.configuration.storageClientOptions ?? {});
|
|
1238
|
+
const { apifyVersion, crawleeVersion } = getSystemInfo();
|
|
1239
|
+
return new ApifyClient({
|
|
1240
|
+
baseUrl: this.configuration.apiBaseUrl,
|
|
1241
|
+
publicBaseUrl: this.configuration.apiPublicBaseUrl,
|
|
1242
|
+
token: this.configuration.token,
|
|
1031
1243
|
userAgentSuffix: [`SDK/${apifyVersion}`, `Crawlee/${crawleeVersion}`],
|
|
1032
1244
|
...storageClientOptions,
|
|
1033
1245
|
...options, // allow overriding the instance configuration
|
|
1034
|
-
}, {
|
|
1035
|
-
config: this.config,
|
|
1036
|
-
// Hand over the raw manager rather than the public getChargingManager(), which
|
|
1037
|
-
// warns about a missing init() — a standalone client is a supported use case.
|
|
1038
|
-
getChargingManager: () => this.chargingManager,
|
|
1039
1246
|
});
|
|
1040
1247
|
}
|
|
1041
1248
|
/**
|
|
@@ -1043,7 +1250,7 @@ class Actor {
|
|
|
1043
1250
|
* @ignore
|
|
1044
1251
|
*/
|
|
1045
1252
|
isAtHome() {
|
|
1046
|
-
return !!process.env[
|
|
1253
|
+
return !!process.env[APIFY_ENV_VARS.IS_AT_HOME];
|
|
1047
1254
|
}
|
|
1048
1255
|
/**
|
|
1049
1256
|
* Easily create and manage state values. All state values are automatically persisted.
|
|
@@ -1055,9 +1262,9 @@ class Actor {
|
|
|
1055
1262
|
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
|
|
1056
1263
|
*/
|
|
1057
1264
|
async useState(name, defaultValue = {}, options) {
|
|
1058
|
-
this.
|
|
1059
|
-
const kvStore = await
|
|
1060
|
-
|
|
1265
|
+
this.ensureActorInit('useState');
|
|
1266
|
+
const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
|
|
1267
|
+
configuration: options?.configuration ?? this.configuration,
|
|
1061
1268
|
});
|
|
1062
1269
|
return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
|
|
1063
1270
|
}
|
|
@@ -1108,24 +1315,22 @@ class Actor {
|
|
|
1108
1315
|
*
|
|
1109
1316
|
* If the user function returns a promise, it is considered asynchronous:
|
|
1110
1317
|
* ```js
|
|
1111
|
-
* import { gotScraping } from 'got-scraping';
|
|
1112
|
-
*
|
|
1113
1318
|
* await Actor.main(() => {
|
|
1114
1319
|
* // My asynchronous function that returns a promise
|
|
1115
|
-
* return
|
|
1116
|
-
*
|
|
1117
|
-
*
|
|
1320
|
+
* return fetch('http://www.example.com')
|
|
1321
|
+
* .then((response) => response.text())
|
|
1322
|
+
* .then((html) => {
|
|
1323
|
+
* console.log(html);
|
|
1324
|
+
* });
|
|
1118
1325
|
* });
|
|
1119
1326
|
* ```
|
|
1120
1327
|
*
|
|
1121
1328
|
* To simplify your code, you can take advantage of the `async`/`await` keywords:
|
|
1122
1329
|
*
|
|
1123
1330
|
* ```js
|
|
1124
|
-
* import { gotScraping } from 'got-scraping';
|
|
1125
|
-
*
|
|
1126
1331
|
* await Actor.main(async () => {
|
|
1127
1332
|
* // My asynchronous function
|
|
1128
|
-
* const html = await
|
|
1333
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
1129
1334
|
* console.log(html);
|
|
1130
1335
|
* });
|
|
1131
1336
|
* ```
|
|
@@ -1153,11 +1358,9 @@ class Actor {
|
|
|
1153
1358
|
* behavior by setting `options.gracefulShutdown` to `false`.
|
|
1154
1359
|
*
|
|
1155
1360
|
* ```js
|
|
1156
|
-
* import { gotScraping } from 'got-scraping';
|
|
1157
|
-
*
|
|
1158
1361
|
* await Actor.init();
|
|
1159
1362
|
*
|
|
1160
|
-
* const html = await
|
|
1363
|
+
* const html = await fetch('http://www.example.com').then((response) => response.text());
|
|
1161
1364
|
* console.log(html);
|
|
1162
1365
|
*
|
|
1163
1366
|
* await Actor.exit();
|
|
@@ -1208,9 +1411,8 @@ class Actor {
|
|
|
1208
1411
|
* @param actorId
|
|
1209
1412
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
1210
1413
|
* @param [input]
|
|
1211
|
-
* Input for the Actor.
|
|
1212
|
-
*
|
|
1213
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
1414
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1415
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1214
1416
|
* @param [options]
|
|
1215
1417
|
*/
|
|
1216
1418
|
static async call(actorId, input, options = {}) {
|
|
@@ -1244,6 +1446,31 @@ class Actor {
|
|
|
1244
1446
|
static async callTask(taskId, input, options = {}) {
|
|
1245
1447
|
return Actor.getDefaultInstance().callTask(taskId, input, options);
|
|
1246
1448
|
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1451
|
+
* unlike `Actor.callTask`, this method just starts the run without waiting for finish.
|
|
1452
|
+
*
|
|
1453
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1454
|
+
*
|
|
1455
|
+
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
|
|
1456
|
+
*
|
|
1457
|
+
* **Example usage:**
|
|
1458
|
+
*
|
|
1459
|
+
* ```js
|
|
1460
|
+
* const run = await Actor.startTask('bob/some-task');
|
|
1461
|
+
* ```
|
|
1462
|
+
*
|
|
1463
|
+
* @param taskId
|
|
1464
|
+
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
|
|
1465
|
+
* @param [input]
|
|
1466
|
+
* Input overrides for the Actor task. If it is an object, it will be stringified to
|
|
1467
|
+
* JSON and its content type set to `application/json; charset=utf-8`.
|
|
1468
|
+
* Provided input will be merged with Actor task input.
|
|
1469
|
+
* @param [options]
|
|
1470
|
+
*/
|
|
1471
|
+
static async startTask(taskId, input, options = {}) {
|
|
1472
|
+
return Actor.getDefaultInstance().startTask(taskId, input, options);
|
|
1473
|
+
}
|
|
1247
1474
|
/**
|
|
1248
1475
|
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
|
|
1249
1476
|
* unlike `Actor.call`, this method just starts the run without waiting for finish.
|
|
@@ -1262,14 +1489,28 @@ class Actor {
|
|
|
1262
1489
|
* @param actorId
|
|
1263
1490
|
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
|
|
1264
1491
|
* @param [input]
|
|
1265
|
-
* Input for the Actor.
|
|
1266
|
-
*
|
|
1267
|
-
* Otherwise the `options.contentType` parameter must be provided.
|
|
1492
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1493
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1268
1494
|
* @param [options]
|
|
1269
1495
|
*/
|
|
1270
1496
|
static async start(actorId, input, options = {}) {
|
|
1271
1497
|
return Actor.getDefaultInstance().start(actorId, input, options);
|
|
1272
1498
|
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
|
|
1501
|
+
* before a migration or resurrection of this run. Each client points to the current run under its name.
|
|
1502
|
+
*
|
|
1503
|
+
* ```js
|
|
1504
|
+
* await Actor.childRuns['my-child'].waitForFinish();
|
|
1505
|
+
* ```
|
|
1506
|
+
*
|
|
1507
|
+
* A run started with a custom `token` uses that token, except for a run started before a migration or
|
|
1508
|
+
* resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
|
|
1509
|
+
* under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
|
|
1510
|
+
*/
|
|
1511
|
+
static get childRuns() {
|
|
1512
|
+
return Actor.getDefaultInstance().childRuns;
|
|
1513
|
+
}
|
|
1273
1514
|
/**
|
|
1274
1515
|
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1275
1516
|
*
|
|
@@ -1287,6 +1528,26 @@ class Actor {
|
|
|
1287
1528
|
static async abort(runId, options = {}) {
|
|
1288
1529
|
return Actor.getDefaultInstance().abort(runId, options);
|
|
1289
1530
|
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
|
|
1533
|
+
*
|
|
1534
|
+
* Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
|
|
1535
|
+
* status and keeps its default storages. Options you leave out keep the values of the original run.
|
|
1536
|
+
*
|
|
1537
|
+
* The result of the function is an {@link ActorRun} object that contains details about the Actor run.
|
|
1538
|
+
*
|
|
1539
|
+
* For more information about Actors, read the
|
|
1540
|
+
* [documentation](https://docs.apify.com/actor).
|
|
1541
|
+
*
|
|
1542
|
+
* **Example usage:**
|
|
1543
|
+
*
|
|
1544
|
+
* ```js
|
|
1545
|
+
* const run = await Actor.resurrect(runId);
|
|
1546
|
+
* ```
|
|
1547
|
+
*/
|
|
1548
|
+
static async resurrect(runId, options = {}) {
|
|
1549
|
+
return Actor.getDefaultInstance().resurrect(runId, options);
|
|
1550
|
+
}
|
|
1290
1551
|
/**
|
|
1291
1552
|
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
|
|
1292
1553
|
* the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
|
|
@@ -1295,9 +1556,8 @@ class Actor {
|
|
|
1295
1556
|
* @param targetActorId
|
|
1296
1557
|
* Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
|
|
1297
1558
|
* @param [input]
|
|
1298
|
-
* Input for the Actor.
|
|
1299
|
-
*
|
|
1300
|
-
* Otherwise, the `options.contentType` parameter must be provided.
|
|
1559
|
+
* Input for the Actor. A plain object is stringified to JSON with content type
|
|
1560
|
+
* `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
|
|
1301
1561
|
* @param [options]
|
|
1302
1562
|
*/
|
|
1303
1563
|
static async metamorph(targetActorId, input, options = {}) {
|
|
@@ -1332,7 +1592,8 @@ class Actor {
|
|
|
1332
1592
|
* @param [options]
|
|
1333
1593
|
* @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
|
|
1334
1594
|
* This is required for the last status message of the run. Default value is `false`.
|
|
1335
|
-
* @returns The
|
|
1595
|
+
* @returns The updated Run object, or `undefined` when no run was updated: when run locally,
|
|
1596
|
+
* or when the update failed or timed out (a warning is logged in that case).
|
|
1336
1597
|
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
|
|
1337
1598
|
*/
|
|
1338
1599
|
static async setStatusMessage(statusMessage, options) {
|
|
@@ -1380,42 +1641,15 @@ class Actor {
|
|
|
1380
1641
|
* @param [datasetIdOrName]
|
|
1381
1642
|
* ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
|
|
1382
1643
|
* the function returns the default dataset associated with the Actor run.
|
|
1383
|
-
* You can also pass `{ alias: '
|
|
1384
|
-
*
|
|
1644
|
+
* You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
|
|
1645
|
+
* explicit ID, or `{ name: 'abc' }` to open by explicit name.
|
|
1385
1646
|
* @param [options]
|
|
1386
1647
|
*/
|
|
1387
1648
|
static async openDataset(datasetIdOrName, options = {}) {
|
|
1388
1649
|
return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
|
|
1389
1650
|
}
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
*
|
|
1393
|
-
* This is just a convenient shortcut for {@link KeyValueStore.getValue}.
|
|
1394
|
-
* For example, calling the following code:
|
|
1395
|
-
* ```js
|
|
1396
|
-
* const value = await Actor.getValue('my-key');
|
|
1397
|
-
* ```
|
|
1398
|
-
*
|
|
1399
|
-
* is equivalent to:
|
|
1400
|
-
* ```js
|
|
1401
|
-
* const store = await Actor.openKeyValueStore();
|
|
1402
|
-
* const value = await store.getValue('my-key');
|
|
1403
|
-
* ```
|
|
1404
|
-
*
|
|
1405
|
-
* To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
|
|
1406
|
-
*
|
|
1407
|
-
* For more information, see {@link Actor.openKeyValueStore}
|
|
1408
|
-
* and {@link KeyValueStore.getValue}.
|
|
1409
|
-
*
|
|
1410
|
-
* @param key Unique record key.
|
|
1411
|
-
* @returns
|
|
1412
|
-
* Returns a promise that resolves to an object, string
|
|
1413
|
-
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
1414
|
-
* on the MIME content type of the record, or `null`
|
|
1415
|
-
* if the record is missing.
|
|
1416
|
-
*/
|
|
1417
|
-
static async getValue(key) {
|
|
1418
|
-
return Actor.getDefaultInstance().getValue(key);
|
|
1651
|
+
static async getValue(key, defaultValue) {
|
|
1652
|
+
return Actor.getDefaultInstance().getValue(key, defaultValue);
|
|
1419
1653
|
}
|
|
1420
1654
|
/**
|
|
1421
1655
|
* Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
|
|
@@ -1453,16 +1687,31 @@ class Actor {
|
|
|
1453
1687
|
/**
|
|
1454
1688
|
* Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
|
|
1455
1689
|
*
|
|
1456
|
-
*
|
|
1457
|
-
* For example, calling the following code:
|
|
1690
|
+
* The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`):
|
|
1458
1691
|
* ```js
|
|
1459
1692
|
* const input = await Actor.getInput();
|
|
1460
1693
|
* ```
|
|
1461
1694
|
*
|
|
1462
|
-
* is
|
|
1695
|
+
* A record stored as `application/octet-stream` — which is what a local input file without an
|
|
1696
|
+
* extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
|
|
1697
|
+
*
|
|
1698
|
+
* When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
|
|
1699
|
+
* working directory.
|
|
1700
|
+
*
|
|
1701
|
+
* Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
|
|
1702
|
+
* replaced with the links of their CSV exports.
|
|
1703
|
+
*
|
|
1704
|
+
* Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
|
|
1705
|
+
* found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
|
|
1706
|
+
* (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
|
|
1707
|
+
* Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
|
|
1463
1708
|
* ```js
|
|
1464
|
-
*
|
|
1465
|
-
*
|
|
1709
|
+
* let input = {};
|
|
1710
|
+
* try {
|
|
1711
|
+
* input = await Actor.getInput();
|
|
1712
|
+
* } catch (error) {
|
|
1713
|
+
* if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
|
|
1714
|
+
* }
|
|
1466
1715
|
* ```
|
|
1467
1716
|
*
|
|
1468
1717
|
* Note that the `getInput()` function does not cache the value read from the key-value store.
|
|
@@ -1474,19 +1723,12 @@ class Actor {
|
|
|
1474
1723
|
* @returns
|
|
1475
1724
|
* Returns a promise that resolves to an object, string
|
|
1476
1725
|
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
|
|
1477
|
-
* on the MIME content type of the record
|
|
1478
|
-
*
|
|
1726
|
+
* on the MIME content type of the record.
|
|
1727
|
+
* @throws {ActorInputError} When the input cannot be produced; see `code`.
|
|
1479
1728
|
*/
|
|
1480
1729
|
static async getInput() {
|
|
1481
1730
|
return Actor.getDefaultInstance().getInput();
|
|
1482
1731
|
}
|
|
1483
|
-
/**
|
|
1484
|
-
* Gets the Actor input value just like the {@link Actor.getInput} method,
|
|
1485
|
-
* but throws if it is not found.
|
|
1486
|
-
*/
|
|
1487
|
-
static async getInputOrThrow() {
|
|
1488
|
-
return Actor.getDefaultInstance().getInputOrThrow();
|
|
1489
|
-
}
|
|
1490
1732
|
/**
|
|
1491
1733
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
1492
1734
|
*
|
|
@@ -1622,69 +1864,92 @@ class Actor {
|
|
|
1622
1864
|
return Actor.getDefaultInstance().apifyClient;
|
|
1623
1865
|
}
|
|
1624
1866
|
/** Default {@link Configuration} instance. */
|
|
1625
|
-
static get
|
|
1626
|
-
return Actor.getDefaultInstance().
|
|
1867
|
+
static get configuration() {
|
|
1868
|
+
return Actor.getDefaultInstance().configuration;
|
|
1627
1869
|
}
|
|
1628
1870
|
/** @internal */
|
|
1629
1871
|
static getDefaultInstance() {
|
|
1630
|
-
|
|
1631
|
-
return
|
|
1872
|
+
Actor.#instance ??= new Actor();
|
|
1873
|
+
return Actor.#instance;
|
|
1632
1874
|
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1875
|
+
/**
|
|
1876
|
+
* Replaces or clears the cached default instance returned by {@link Actor.getDefaultInstance}.
|
|
1877
|
+
* @internal
|
|
1878
|
+
*/
|
|
1879
|
+
static setDefaultInstance(instance) {
|
|
1880
|
+
Actor.#instance = instance;
|
|
1635
1881
|
}
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1882
|
+
/**
|
|
1883
|
+
* The backend the Actor installs unless the caller brings one: Apify platform storage on the
|
|
1884
|
+
* platform, crawlee's local default outside of it.
|
|
1885
|
+
*
|
|
1886
|
+
* Both sides are wrapped for dataset-item charging - crawlee's local default stands in for
|
|
1887
|
+
* Apify storage, so local pay-per-event testing stays faithful. A caller-supplied backend
|
|
1888
|
+
* (`Actor.init({ storage })`) is billed nothing and is installed unwrapped, in place of this.
|
|
1889
|
+
*
|
|
1890
|
+
* One instance per Actor: a second platform backend would mint unnamed storages of its own for
|
|
1891
|
+
* aliases this one has already resolved.
|
|
1892
|
+
*/
|
|
1893
|
+
get #storageBackend() {
|
|
1894
|
+
const charging = {
|
|
1895
|
+
configuration: this.configuration,
|
|
1896
|
+
getChargingManager: () => this.#chargingManager,
|
|
1641
1897
|
};
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
});
|
|
1898
|
+
return (this.#cachedStorageBackend ??= new SmartApifyStorageBackend({
|
|
1899
|
+
cloudStorageBackend: new ChargingStorageBackend(new ApifyStorageBackend(this.apifyClient, {
|
|
1900
|
+
configuration: this.configuration,
|
|
1901
|
+
requestQueueAccess: this.#requestQueueAccess,
|
|
1902
|
+
}), charging),
|
|
1903
|
+
localStorageBackend: new ChargingStorageBackend(this.createLocalStorageBackend(), charging),
|
|
1904
|
+
configuration: this.configuration,
|
|
1905
|
+
}));
|
|
1650
1906
|
}
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
};
|
|
1907
|
+
/**
|
|
1908
|
+
* The same choice crawlee's `ServiceLocator` makes for its implicit default backend, with the
|
|
1909
|
+
* input-aware {@link ApifyFileSystemStorageBackend} in place of crawlee's — crawlee has no
|
|
1910
|
+
* notion of a run input.
|
|
1911
|
+
*/
|
|
1912
|
+
createLocalStorageBackend() {
|
|
1913
|
+
const { persistStorage, storageDir, inputKey } = this.configuration;
|
|
1914
|
+
const logger = serviceLocator.getLogger();
|
|
1915
|
+
if (!persistStorage) {
|
|
1916
|
+
return new MemoryStorageBackend({ logger: logger.child({ prefix: 'MemoryStorageBackend' }) });
|
|
1661
1917
|
}
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
eventName: explicitEventName,
|
|
1667
|
-
isDefaultDataset,
|
|
1668
|
-
pushFn: async (limitedItems) => dataset.pushData(limitedItems),
|
|
1918
|
+
return new ApifyFileSystemStorageBackend({
|
|
1919
|
+
localDataDirectory: storageDir,
|
|
1920
|
+
inputKey,
|
|
1921
|
+
logger: logger.child({ prefix: 'ApifyFileSystemStorageBackend' }),
|
|
1669
1922
|
});
|
|
1670
1923
|
}
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1924
|
+
/** Whether items reaching the run's default dataset are counted for pay-per-event charging. */
|
|
1925
|
+
#chargesDefaultDatasetItems() {
|
|
1926
|
+
const installed = serviceLocator.getStorageBackend();
|
|
1927
|
+
return installed instanceof SmartApifyStorageBackend || installed instanceof ChargingStorageBackend;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* crawlee's service locator is set-once, so a backend registered before `init()` wins and the
|
|
1931
|
+
* Actor cannot install its own over it. Replaces the resulting `ServiceConflictError` with the
|
|
1932
|
+
* way out.
|
|
1933
|
+
*/
|
|
1934
|
+
installStorageBackend(backend) {
|
|
1935
|
+
try {
|
|
1936
|
+
serviceLocator.setStorageBackend(backend);
|
|
1937
|
+
}
|
|
1938
|
+
catch (error) {
|
|
1939
|
+
throw new Error('A storage backend is already registered with crawlee, so the Actor cannot install its own. Pass it ' +
|
|
1940
|
+
'as `Actor.init({ storage })` instead of calling `serviceLocator.setStorageBackend()`.', { cause: error });
|
|
1941
|
+
}
|
|
1677
1942
|
}
|
|
1678
|
-
|
|
1943
|
+
ensureActorInit(methodCalled) {
|
|
1679
1944
|
// If we already warned the user once, don't do it again to prevent spam
|
|
1680
|
-
if (this
|
|
1945
|
+
if (this.#warnedAboutMissingInitCall) {
|
|
1681
1946
|
return;
|
|
1682
1947
|
}
|
|
1683
1948
|
if (this.initialized) {
|
|
1684
1949
|
return;
|
|
1685
1950
|
}
|
|
1686
|
-
this
|
|
1687
|
-
|
|
1951
|
+
this.#warnedAboutMissingInitCall = true;
|
|
1952
|
+
log.warning([
|
|
1688
1953
|
`Actor.${methodCalled}() was called but the Actor instance was not initialized.`,
|
|
1689
1954
|
'Did you forget to call Actor.init()?',
|
|
1690
1955
|
].join('\n'));
|
|
@@ -1702,7 +1967,7 @@ class Actor {
|
|
|
1702
1967
|
if (this.isAtHome() && env.timeoutAt !== null) {
|
|
1703
1968
|
return Math.max(Math.ceil((env.timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
|
|
1704
1969
|
}
|
|
1705
|
-
|
|
1970
|
+
log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
|
|
1706
1971
|
'timeout for the Actor run is set.');
|
|
1707
1972
|
return undefined;
|
|
1708
1973
|
}
|
|
@@ -1713,17 +1978,16 @@ class Actor {
|
|
|
1713
1978
|
return input;
|
|
1714
1979
|
}
|
|
1715
1980
|
// On local, we can get the input schema from the local config
|
|
1716
|
-
const inputSchema =
|
|
1981
|
+
const inputSchema = readInputSchema();
|
|
1717
1982
|
// Don't emit warning if there is no input schema defined
|
|
1718
|
-
if (inputSchema ===
|
|
1983
|
+
if (inputSchema === noActorInputSchemaDefinedMarker) {
|
|
1719
1984
|
return input;
|
|
1720
1985
|
}
|
|
1721
1986
|
if (!inputSchema) {
|
|
1722
|
-
|
|
1987
|
+
log.warning('Failed to find the input schema for the local run of this Actor. Your input will be missing fields that have default values set if they are missing from the input you are using.');
|
|
1723
1988
|
return input;
|
|
1724
1989
|
}
|
|
1725
|
-
const defaults =
|
|
1990
|
+
const defaults = getDefaultsFromInputSchema(inputSchema);
|
|
1726
1991
|
return { ...defaults, ...input };
|
|
1727
1992
|
}
|
|
1728
1993
|
}
|
|
1729
|
-
exports.Actor = Actor;
|