apify 4.0.0-beta.15 → 4.0.0-beta.150
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -2
- package/dist/actor.d.ts +416 -281
- package/dist/actor.js +743 -417
- package/dist/apify_dataset_backend.d.ts +22 -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 +26 -0
- package/dist/apify_key_value_store_backend.js +57 -0
- package/dist/apify_request_queue_backend.d.ts +88 -0
- package/dist/apify_request_queue_backend.js +123 -0
- package/dist/apify_request_queue_shared_backend.d.ts +31 -0
- package/dist/apify_request_queue_shared_backend.js +201 -0
- package/dist/apify_request_queue_single_backend.d.ts +43 -0
- package/dist/apify_request_queue_single_backend.js +265 -0
- package/dist/apify_storage_backend.d.ts +95 -0
- package/dist/apify_storage_backend.js +219 -0
- package/dist/charging.d.ts +77 -47
- package/dist/charging.js +348 -226
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +109 -0
- package/dist/child_run_tracker.d.ts +110 -0
- package/dist/child_run_tracker.js +333 -0
- package/dist/configuration.d.ts +48 -28
- package/dist/configuration.js +66 -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 +13 -4
- package/dist/index.js +8 -3
- package/dist/input-schemas.d.ts +1 -1
- package/dist/platform_event_manager.d.ts +24 -9
- package/dist/platform_event_manager.js +213 -43
- package/dist/proxy_configuration.d.ts +32 -21
- package/dist/proxy_configuration.js +137 -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
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { DatasetBackend, DatasetBackendListOptions, DatasetInfo, Dictionary, KeyValueStoreBackend, PaginatedList, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
|
|
2
|
+
import type { ChargingManager } from './charging.js';
|
|
3
|
+
import type { Configuration } from './configuration.js';
|
|
4
|
+
export interface ChargingStorageBackendOptions {
|
|
5
|
+
/** Supplies the run's default dataset id, which is the only dataset charged for. */
|
|
6
|
+
configuration: Configuration;
|
|
7
|
+
/** Resolved per push, as the charging manager only knows the pricing once `Actor.init()` has run. */
|
|
8
|
+
getChargingManager: () => ChargingManager;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Charges the synthetic `apify-default-dataset-item` event for the items it stores, trimming a push
|
|
12
|
+
* that the remaining budget cannot cover.
|
|
13
|
+
*
|
|
14
|
+
* It wraps the whole dataset backend rather than its API calls, so that a push split into several
|
|
15
|
+
* payload-sized requests is still counted and charged exactly once.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
export declare class ChargingDatasetBackend implements DatasetBackend {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(inner: DatasetBackend, getChargingManager: () => ChargingManager);
|
|
22
|
+
getMetadata(): Promise<DatasetInfo>;
|
|
23
|
+
drop(): Promise<void>;
|
|
24
|
+
purge(): Promise<void>;
|
|
25
|
+
getData(options?: DatasetBackendListOptions): Promise<PaginatedList<Dictionary>>;
|
|
26
|
+
pushData(items: Dictionary[]): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Wraps another storage backend so that items pushed to the run's default dataset are charged for
|
|
30
|
+
* under the pay-per-event pricing model.
|
|
31
|
+
*
|
|
32
|
+
* Charging belongs here rather than in `Actor.pushData()` because `Dataset.pushData()` is also
|
|
33
|
+
* called directly - by user code and by crawlee itself (`context.pushData()`) - and every item that
|
|
34
|
+
* reaches the default dataset is billed by the platform regardless of who pushed it.
|
|
35
|
+
*
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
export declare class ChargingStorageBackend implements StorageBackend {
|
|
39
|
+
#private;
|
|
40
|
+
storageExists?: StorageBackend['storageExists'];
|
|
41
|
+
purge?: StorageBackend['purge'];
|
|
42
|
+
teardown?: StorageBackend['teardown'];
|
|
43
|
+
constructor(inner: StorageBackend, options: ChargingStorageBackendOptions);
|
|
44
|
+
get stats(): {
|
|
45
|
+
rateLimitErrors: number[];
|
|
46
|
+
} | undefined;
|
|
47
|
+
/** Repeats crawlee's own fallback, so that wrapping a backend does not change how storages are cached. */
|
|
48
|
+
getStorageBackendCacheKey(): string;
|
|
49
|
+
createDatasetBackend(options?: StorageIdentifier): Promise<DatasetBackend>;
|
|
50
|
+
createKeyValueStoreBackend(options?: StorageIdentifier): Promise<KeyValueStoreBackend>;
|
|
51
|
+
createRequestQueueBackend(options?: StorageIdentifier): Promise<RequestQueueBackend>;
|
|
52
|
+
private isDefaultDataset;
|
|
53
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
|
|
2
|
+
import { DEFAULT_STORAGE_ALIAS } from './apify_storage_backend.js';
|
|
3
|
+
/**
|
|
4
|
+
* Charges the synthetic `apify-default-dataset-item` event for the items it stores, trimming a push
|
|
5
|
+
* that the remaining budget cannot cover.
|
|
6
|
+
*
|
|
7
|
+
* It wraps the whole dataset backend rather than its API calls, so that a push split into several
|
|
8
|
+
* payload-sized requests is still counted and charged exactly once.
|
|
9
|
+
*
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
export class ChargingDatasetBackend {
|
|
13
|
+
#inner;
|
|
14
|
+
#getChargingManager;
|
|
15
|
+
constructor(inner, getChargingManager) {
|
|
16
|
+
this.#inner = inner;
|
|
17
|
+
this.#getChargingManager = getChargingManager;
|
|
18
|
+
}
|
|
19
|
+
async getMetadata() {
|
|
20
|
+
return await this.#inner.getMetadata();
|
|
21
|
+
}
|
|
22
|
+
async drop() {
|
|
23
|
+
await this.#inner.drop();
|
|
24
|
+
}
|
|
25
|
+
async purge() {
|
|
26
|
+
await this.#inner.purge();
|
|
27
|
+
}
|
|
28
|
+
async getData(options) {
|
|
29
|
+
return await this.#inner.getData(options);
|
|
30
|
+
}
|
|
31
|
+
async pushData(items) {
|
|
32
|
+
const chargingManager = this.#getChargingManager();
|
|
33
|
+
// `Dataset.pushData()` also works without `Actor.init()`, where there is no charging state yet. Multi-tenant
|
|
34
|
+
// runs charge per request only, so dataset writes charge nothing there.
|
|
35
|
+
if (items.length === 0 ||
|
|
36
|
+
!chargingManager.isInitialized ||
|
|
37
|
+
!chargingManager.isPayPerEvent ||
|
|
38
|
+
chargingManager.isMultiTenant) {
|
|
39
|
+
await this.#inner.pushData(items);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await chargingManager.withChargeLock(async () => {
|
|
43
|
+
const limit = chargingManager.calculatePushDataLimit(items.length, { isDefaultDataset: true });
|
|
44
|
+
if (limit === 0) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
await this.#inner.pushData(limit < items.length ? items.slice(0, limit) : items);
|
|
48
|
+
await chargingManager.charge({ eventName: DEFAULT_DATASET_ITEM_EVENT, count: limit });
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Wraps another storage backend so that items pushed to the run's default dataset are charged for
|
|
54
|
+
* under the pay-per-event pricing model.
|
|
55
|
+
*
|
|
56
|
+
* Charging belongs here rather than in `Actor.pushData()` because `Dataset.pushData()` is also
|
|
57
|
+
* called directly - by user code and by crawlee itself (`context.pushData()`) - and every item that
|
|
58
|
+
* reaches the default dataset is billed by the platform regardless of who pushed it.
|
|
59
|
+
*
|
|
60
|
+
* @internal
|
|
61
|
+
*/
|
|
62
|
+
export class ChargingStorageBackend {
|
|
63
|
+
storageExists;
|
|
64
|
+
purge;
|
|
65
|
+
teardown;
|
|
66
|
+
#inner;
|
|
67
|
+
#options;
|
|
68
|
+
constructor(inner, options) {
|
|
69
|
+
this.#inner = inner;
|
|
70
|
+
this.#options = options;
|
|
71
|
+
// Crawlee branches on the presence of these, so they have to stay absent when `inner` lacks them.
|
|
72
|
+
const { storageExists, purge, teardown } = inner;
|
|
73
|
+
if (storageExists)
|
|
74
|
+
this.storageExists = async (id, type) => storageExists.call(inner, id, type);
|
|
75
|
+
if (purge)
|
|
76
|
+
this.purge = async () => purge.call(inner);
|
|
77
|
+
if (teardown)
|
|
78
|
+
this.teardown = async () => teardown.call(inner);
|
|
79
|
+
}
|
|
80
|
+
get stats() {
|
|
81
|
+
return this.#inner.stats;
|
|
82
|
+
}
|
|
83
|
+
/** Repeats crawlee's own fallback, so that wrapping a backend does not change how storages are cached. */
|
|
84
|
+
getStorageBackendCacheKey() {
|
|
85
|
+
return this.#inner.getStorageBackendCacheKey?.() ?? this.#inner.constructor.name;
|
|
86
|
+
}
|
|
87
|
+
async createDatasetBackend(options) {
|
|
88
|
+
const backend = await this.#inner.createDatasetBackend(options);
|
|
89
|
+
if (!this.isDefaultDataset(options)) {
|
|
90
|
+
return backend;
|
|
91
|
+
}
|
|
92
|
+
return new ChargingDatasetBackend(backend, this.#options.getChargingManager);
|
|
93
|
+
}
|
|
94
|
+
async createKeyValueStoreBackend(options) {
|
|
95
|
+
return await this.#inner.createKeyValueStoreBackend(options);
|
|
96
|
+
}
|
|
97
|
+
async createRequestQueueBackend(options) {
|
|
98
|
+
return await this.#inner.createRequestQueueBackend(options);
|
|
99
|
+
}
|
|
100
|
+
isDefaultDataset(options) {
|
|
101
|
+
if (!options)
|
|
102
|
+
return true;
|
|
103
|
+
if (options.alias !== undefined)
|
|
104
|
+
return options.alias === DEFAULT_STORAGE_ALIAS;
|
|
105
|
+
if (options.id !== undefined)
|
|
106
|
+
return options.id === this.#options.configuration.defaultDatasetId;
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { Run as ActorRun } from 'apify-client';
|
|
2
|
+
import type { ChildRunClient, InitOptions } from './actor.js';
|
|
3
|
+
import type { ApifyClient } from './index.js';
|
|
4
|
+
/**
|
|
5
|
+
* How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
|
|
6
|
+
* run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
|
|
7
|
+
*/
|
|
8
|
+
export declare const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10000;
|
|
9
|
+
/** How long `waitForStartsInFlight()` waits for the started runs to be recorded. */
|
|
10
|
+
export declare const STARTS_IN_FLIGHT_TIMEOUT_MILLIS = 10000;
|
|
11
|
+
/** Number of recorded runs above which a warning about the size of the registry is logged, once per process. */
|
|
12
|
+
export declare const EXCESSIVE_CHILD_RUNS_THRESHOLD = 50;
|
|
13
|
+
/**
|
|
14
|
+
* Records every child run of this run in the default key-value store, so that it can be listed, aborted together with
|
|
15
|
+
* this run and counted against the concurrency limit, also after a migration, reboot or resurrection of this run.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ChildRunTracker {
|
|
18
|
+
private readonly defaultClient;
|
|
19
|
+
/** Set by `configure()` in `Actor.init()`. Child runs started before it are not tracked. */
|
|
20
|
+
private enabled?;
|
|
21
|
+
private warnOnExcessiveRuns;
|
|
22
|
+
private warnedExcessiveRuns;
|
|
23
|
+
private maxConcurrentRuns?;
|
|
24
|
+
private registry;
|
|
25
|
+
private loading?;
|
|
26
|
+
private lastWrite;
|
|
27
|
+
/** A write that is queued and not started yet, which the changes made in the meantime join. */
|
|
28
|
+
private queuedWrite?;
|
|
29
|
+
/** Client each run was started with in this process, if it is not the default one. */
|
|
30
|
+
private clients;
|
|
31
|
+
/** When the status of each record was last returned by the API, in this process. */
|
|
32
|
+
private observedAt;
|
|
33
|
+
/** Starts whose runs are not recorded yet. */
|
|
34
|
+
private startsInFlight;
|
|
35
|
+
/** Start requests that have not returned yet, which the concurrency limit counts. */
|
|
36
|
+
private pendingStartRequests;
|
|
37
|
+
private admissionLock;
|
|
38
|
+
/** Set once this run starts aborting its child runs, after which no run with `abortWithParent` is started. */
|
|
39
|
+
private aborting?;
|
|
40
|
+
constructor(defaultClient: ApifyClient);
|
|
41
|
+
/**
|
|
42
|
+
* Applies the options of `Actor.init()`, before the registry is loaded.
|
|
43
|
+
*/
|
|
44
|
+
configure({ trackChildRuns, disableExcessiveChildRunWarning, maxConcurrentChildRuns, }: Pick<InitOptions, 'trackChildRuns' | 'disableExcessiveChildRunWarning' | 'maxConcurrentChildRuns'>): void;
|
|
45
|
+
/**
|
|
46
|
+
* Starts a child run using `start`, and records it before returning it. Waits for a slot first, if the concurrency
|
|
47
|
+
* limit is set.
|
|
48
|
+
*/
|
|
49
|
+
startChildRun(client: ApifyClient, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<ActorRun>;
|
|
50
|
+
/**
|
|
51
|
+
* Records the latest observed status of a child run.
|
|
52
|
+
*/
|
|
53
|
+
update(run: ActorRun): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Returns a client for every recorded run, in recording order. The client is the one the run was started with in
|
|
56
|
+
* this process, or the default one (e.g. for a run recorded before a migration).
|
|
57
|
+
*/
|
|
58
|
+
getRunClients(): Promise<ChildRunClient[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Gracefully aborts each recorded run with `abortWithParent` and an active recorded status, once, and makes any
|
|
61
|
+
* later start with `abortWithParent` throw. The starts in flight are waited for, so the runs they start are
|
|
62
|
+
* aborted too. Resolves after {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in
|
|
63
|
+
* progress to go on.
|
|
64
|
+
*/
|
|
65
|
+
abortRunsWithParent(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Lets runs with `abortWithParent` start again, and makes the next exit abort them, after `Actor.exit()` that did
|
|
68
|
+
* not end the process.
|
|
69
|
+
*/
|
|
70
|
+
resetAbort(): void;
|
|
71
|
+
/**
|
|
72
|
+
* Waits for the starts in flight to be recorded, for {@link STARTS_IN_FLIGHT_TIMEOUT_MILLIS} at most.
|
|
73
|
+
*/
|
|
74
|
+
waitForStartsInFlight(): Promise<void>;
|
|
75
|
+
/**
|
|
76
|
+
* Loads the registry from the default key-value store, once.
|
|
77
|
+
*/
|
|
78
|
+
load(): Promise<{
|
|
79
|
+
[x: string]: unknown;
|
|
80
|
+
runs: Record<string, {
|
|
81
|
+
[x: string]: unknown;
|
|
82
|
+
runId: string;
|
|
83
|
+
status: string;
|
|
84
|
+
abortWithParent: boolean;
|
|
85
|
+
}>;
|
|
86
|
+
}>;
|
|
87
|
+
private abortMarkedRuns;
|
|
88
|
+
/**
|
|
89
|
+
* Waits while the active runs and the pending start requests are at the concurrency limit. Throws instead of
|
|
90
|
+
* waiting once this run is being aborted or is exiting.
|
|
91
|
+
*/
|
|
92
|
+
private waitForSlot;
|
|
93
|
+
/**
|
|
94
|
+
* Counts the recorded runs with an active status. A status older than {@link STATUS_MAX_AGE_MILLIS}, or recorded
|
|
95
|
+
* by an earlier process, is fetched from the API first.
|
|
96
|
+
*/
|
|
97
|
+
private countActiveRuns;
|
|
98
|
+
private clientFor;
|
|
99
|
+
/**
|
|
100
|
+
* Records `record` under `key`. Its status must be one just returned by the API.
|
|
101
|
+
*/
|
|
102
|
+
private record;
|
|
103
|
+
/**
|
|
104
|
+
* Writes the registry once the write in progress finishes. The changes made until then are written together. A
|
|
105
|
+
* failed write is logged, not thrown, since the run is already started, and the next write saves the change too.
|
|
106
|
+
*/
|
|
107
|
+
private persist;
|
|
108
|
+
private warnIfExcessive;
|
|
109
|
+
private assertEnabled;
|
|
110
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { KeyValueStore, withDirectStorageAccess } from '@crawlee/core';
|
|
3
|
+
import { ApifyApiError, NotFoundError } from 'apify-client';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { ACTOR_JOB_STATUSES } from '@apify/consts';
|
|
6
|
+
import log from '@apify/log';
|
|
7
|
+
import { addTimeoutToPromise } from '@apify/timeout';
|
|
8
|
+
import { ReentrantAsyncLock } from './utils.js';
|
|
9
|
+
const CHILD_RUNS_KVS_KEY = 'APIFY_ACTOR_CHILD_RUNS';
|
|
10
|
+
const RUN_KEY_PREFIX = 'run:';
|
|
11
|
+
// Members this SDK does not know, e.g. written by a newer SDK before a metamorph, are kept.
|
|
12
|
+
const registrySchema = z.looseObject({
|
|
13
|
+
runs: z.record(z.string(), z.looseObject({
|
|
14
|
+
runId: z.string(),
|
|
15
|
+
/** Last status observed by this run. It can be out of date. */
|
|
16
|
+
status: z.string(),
|
|
17
|
+
abortWithParent: z.boolean(),
|
|
18
|
+
})),
|
|
19
|
+
});
|
|
20
|
+
const { READY, RUNNING, ABORTING, ABORTED, TIMING_OUT } = ACTOR_JOB_STATUSES;
|
|
21
|
+
const ACTIVE_STATUSES = [READY, RUNNING, ABORTING, TIMING_OUT];
|
|
22
|
+
const ABORTED_STATUSES = [ABORTING, ABORTED];
|
|
23
|
+
/**
|
|
24
|
+
* How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
|
|
25
|
+
* run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
|
|
26
|
+
*/
|
|
27
|
+
export const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10_000;
|
|
28
|
+
/** How long `waitForStartsInFlight()` waits for the started runs to be recorded. */
|
|
29
|
+
export const STARTS_IN_FLIGHT_TIMEOUT_MILLIS = 10_000;
|
|
30
|
+
/** Number of recorded runs above which a warning about the size of the registry is logged, once per process. */
|
|
31
|
+
export const EXCESSIVE_CHILD_RUNS_THRESHOLD = 50;
|
|
32
|
+
/** How old a recorded active status can be before the concurrency limit fetches the run again. */
|
|
33
|
+
const STATUS_MAX_AGE_MILLIS = 10_000;
|
|
34
|
+
/** How often a start waiting for a concurrency slot counts the active runs again. */
|
|
35
|
+
const CONCURRENCY_POLL_INTERVAL_MILLIS = 1_000;
|
|
36
|
+
/**
|
|
37
|
+
* Records every child run of this run in the default key-value store, so that it can be listed, aborted together with
|
|
38
|
+
* this run and counted against the concurrency limit, also after a migration, reboot or resurrection of this run.
|
|
39
|
+
*/
|
|
40
|
+
export class ChildRunTracker {
|
|
41
|
+
defaultClient;
|
|
42
|
+
/** Set by `configure()` in `Actor.init()`. Child runs started before it are not tracked. */
|
|
43
|
+
enabled;
|
|
44
|
+
warnOnExcessiveRuns = true;
|
|
45
|
+
warnedExcessiveRuns = false;
|
|
46
|
+
maxConcurrentRuns;
|
|
47
|
+
registry = { runs: {} };
|
|
48
|
+
loading;
|
|
49
|
+
lastWrite = Promise.resolve();
|
|
50
|
+
/** A write that is queued and not started yet, which the changes made in the meantime join. */
|
|
51
|
+
queuedWrite;
|
|
52
|
+
/** Client each run was started with in this process, if it is not the default one. */
|
|
53
|
+
clients = new Map();
|
|
54
|
+
/** When the status of each record was last returned by the API, in this process. */
|
|
55
|
+
observedAt = new Map();
|
|
56
|
+
/** Starts whose runs are not recorded yet. */
|
|
57
|
+
startsInFlight = new Set();
|
|
58
|
+
/** Start requests that have not returned yet, which the concurrency limit counts. */
|
|
59
|
+
pendingStartRequests = 0;
|
|
60
|
+
admissionLock = new ReentrantAsyncLock();
|
|
61
|
+
/** Set once this run starts aborting its child runs, after which no run with `abortWithParent` is started. */
|
|
62
|
+
aborting;
|
|
63
|
+
constructor(defaultClient) {
|
|
64
|
+
this.defaultClient = defaultClient;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Applies the options of `Actor.init()`, before the registry is loaded.
|
|
68
|
+
*/
|
|
69
|
+
configure({ trackChildRuns = true, disableExcessiveChildRunWarning = false, maxConcurrentChildRuns, }) {
|
|
70
|
+
if (maxConcurrentChildRuns != null) {
|
|
71
|
+
if (!Number.isInteger(maxConcurrentChildRuns) || maxConcurrentChildRuns < 1) {
|
|
72
|
+
throw new Error('`maxConcurrentChildRuns` must be a positive integer.');
|
|
73
|
+
}
|
|
74
|
+
if (!trackChildRuns) {
|
|
75
|
+
throw new Error('`maxConcurrentChildRuns` requires child run tracking, which is turned off with `trackChildRuns: false`.');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
this.enabled = trackChildRuns;
|
|
79
|
+
this.warnOnExcessiveRuns = !disableExcessiveChildRunWarning;
|
|
80
|
+
this.maxConcurrentRuns = maxConcurrentChildRuns ?? undefined;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Starts a child run using `start`, and records it before returning it. Waits for a slot first, if the concurrency
|
|
84
|
+
* limit is set.
|
|
85
|
+
*/
|
|
86
|
+
async startChildRun(client, abortWithParent, start) {
|
|
87
|
+
if (abortWithParent)
|
|
88
|
+
this.assertEnabled('`abortWithParent`');
|
|
89
|
+
// A later process would abort the run with the default client.
|
|
90
|
+
if (abortWithParent && client !== this.defaultClient) {
|
|
91
|
+
throw new Error('`abortWithParent` cannot be combined with `token`, since the token is not stored.');
|
|
92
|
+
}
|
|
93
|
+
if (!this.enabled)
|
|
94
|
+
return start();
|
|
95
|
+
await this.load();
|
|
96
|
+
// One start at a time is admitted, so that it is counted before the next one checks the limit.
|
|
97
|
+
const { starting } = await this.admissionLock.runExclusive(async () => {
|
|
98
|
+
await this.waitForSlot();
|
|
99
|
+
if (abortWithParent && this.aborting) {
|
|
100
|
+
throw new Error('A child run with `abortWithParent` was not started, because this run is being aborted or is exiting.');
|
|
101
|
+
}
|
|
102
|
+
this.pendingStartRequests++;
|
|
103
|
+
const started = (async () => {
|
|
104
|
+
let run;
|
|
105
|
+
try {
|
|
106
|
+
run = await start();
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
// The run is recorded right after this, so it never counts twice or not at all.
|
|
110
|
+
this.pendingStartRequests--;
|
|
111
|
+
}
|
|
112
|
+
const key = RUN_KEY_PREFIX + run.id;
|
|
113
|
+
if (client !== this.defaultClient)
|
|
114
|
+
this.clients.set(key, client);
|
|
115
|
+
await this.record(key, { runId: run.id, status: run.status, abortWithParent });
|
|
116
|
+
return run;
|
|
117
|
+
})();
|
|
118
|
+
this.startsInFlight.add(started);
|
|
119
|
+
return { starting: started };
|
|
120
|
+
});
|
|
121
|
+
try {
|
|
122
|
+
return await starting;
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
this.startsInFlight.delete(starting);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Records the latest observed status of a child run.
|
|
130
|
+
*/
|
|
131
|
+
async update(run) {
|
|
132
|
+
if (!this.enabled)
|
|
133
|
+
return;
|
|
134
|
+
const key = RUN_KEY_PREFIX + run.id;
|
|
135
|
+
const recorded = (await this.load()).runs[key];
|
|
136
|
+
if (recorded)
|
|
137
|
+
await this.record(key, { ...recorded, status: run.status });
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Returns a client for every recorded run, in recording order. The client is the one the run was started with in
|
|
141
|
+
* this process, or the default one (e.g. for a run recorded before a migration).
|
|
142
|
+
*/
|
|
143
|
+
async getRunClients() {
|
|
144
|
+
// Nothing is recorded before `Actor.init()`, whose missing call `Actor.childRuns()` warns about.
|
|
145
|
+
if (this.enabled === undefined)
|
|
146
|
+
return [];
|
|
147
|
+
this.assertEnabled('`Actor.childRuns()`');
|
|
148
|
+
const { runs } = await this.load();
|
|
149
|
+
return Object.entries(runs).map(([key, { runId, abortWithParent }]) => Object.defineProperty(this.clientFor(key).run(runId), 'abortWithParent', {
|
|
150
|
+
value: abortWithParent,
|
|
151
|
+
enumerable: true,
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Gracefully aborts each recorded run with `abortWithParent` and an active recorded status, once, and makes any
|
|
156
|
+
* later start with `abortWithParent` throw. The starts in flight are waited for, so the runs they start are
|
|
157
|
+
* aborted too. Resolves after {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in
|
|
158
|
+
* progress to go on.
|
|
159
|
+
*/
|
|
160
|
+
async abortRunsWithParent() {
|
|
161
|
+
if (!this.enabled)
|
|
162
|
+
return;
|
|
163
|
+
this.aborting ??= this.abortMarkedRuns();
|
|
164
|
+
await this.aborting;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Lets runs with `abortWithParent` start again, and makes the next exit abort them, after `Actor.exit()` that did
|
|
168
|
+
* not end the process.
|
|
169
|
+
*/
|
|
170
|
+
resetAbort() {
|
|
171
|
+
this.aborting = undefined;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Waits for the starts in flight to be recorded, for {@link STARTS_IN_FLIGHT_TIMEOUT_MILLIS} at most.
|
|
175
|
+
*/
|
|
176
|
+
async waitForStartsInFlight() {
|
|
177
|
+
if (this.startsInFlight.size === 0)
|
|
178
|
+
return;
|
|
179
|
+
await addTimeoutToPromise(async () => Promise.allSettled([...this.startsInFlight]), STARTS_IN_FLIGHT_TIMEOUT_MILLIS, `Waiting for the child runs being started timed out after ${STARTS_IN_FLIGHT_TIMEOUT_MILLIS / 1000}s`).catch((error) => log.warning(error.message));
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Loads the registry from the default key-value store, once.
|
|
183
|
+
*/
|
|
184
|
+
async load() {
|
|
185
|
+
if (!this.enabled)
|
|
186
|
+
return this.registry;
|
|
187
|
+
this.loading ??= KeyValueStore.open()
|
|
188
|
+
.then(async (store) => store.getValue(CHILD_RUNS_KVS_KEY))
|
|
189
|
+
.then((stored) => {
|
|
190
|
+
const parsed = registrySchema.safeParse(stored ?? { runs: {} });
|
|
191
|
+
if (!parsed.success) {
|
|
192
|
+
throw new Error(`The child runs stored under the "${CHILD_RUNS_KVS_KEY}" key in the default key-value store are malformed.`, { cause: parsed.error });
|
|
193
|
+
}
|
|
194
|
+
this.registry = parsed.data;
|
|
195
|
+
this.warnIfExcessive();
|
|
196
|
+
})
|
|
197
|
+
.catch((error) => {
|
|
198
|
+
this.loading = undefined;
|
|
199
|
+
throw error;
|
|
200
|
+
});
|
|
201
|
+
await this.loading;
|
|
202
|
+
return this.registry;
|
|
203
|
+
}
|
|
204
|
+
async abortMarkedRuns() {
|
|
205
|
+
const startsInFlight = [...this.startsInFlight];
|
|
206
|
+
const aborts = (async () => {
|
|
207
|
+
await Promise.allSettled(startsInFlight);
|
|
208
|
+
const { runs } = await this.load();
|
|
209
|
+
await Promise.all(Object.entries(runs)
|
|
210
|
+
.filter(([, { abortWithParent, status }]) => abortWithParent && ACTIVE_STATUSES.includes(status))
|
|
211
|
+
.map(async ([key, { runId }]) => {
|
|
212
|
+
try {
|
|
213
|
+
const run = await this.clientFor(key).run(runId).abort({ gracefully: true });
|
|
214
|
+
if (ABORTED_STATUSES.includes(run.status)) {
|
|
215
|
+
log.info('Aborted child run with the parent', { runId });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (error instanceof NotFoundError) {
|
|
220
|
+
log.warning('Child run to abort with the parent was not found', { runId });
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
log.exception(error, 'Failed to abort child run', { runId });
|
|
224
|
+
}
|
|
225
|
+
}));
|
|
226
|
+
})();
|
|
227
|
+
// `Actor.exit()` waits for this without a timeout of its own.
|
|
228
|
+
await addTimeoutToPromise(async () => aborts, ABORT_WITH_PARENT_TIMEOUT_MILLIS, `Aborting the child runs with the parent timed out after ${ABORT_WITH_PARENT_TIMEOUT_MILLIS / 1000}s`).catch((error) => log.warning(error.message));
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Waits while the active runs and the pending start requests are at the concurrency limit. Throws instead of
|
|
232
|
+
* waiting once this run is being aborted or is exiting.
|
|
233
|
+
*/
|
|
234
|
+
async waitForSlot() {
|
|
235
|
+
const maxRuns = this.maxConcurrentRuns;
|
|
236
|
+
if (maxRuns === undefined)
|
|
237
|
+
return;
|
|
238
|
+
const isAtLimit = (activeRuns) => activeRuns + this.pendingStartRequests >= maxRuns;
|
|
239
|
+
const recordedActiveRuns = () => Object.values(this.registry.runs).filter(({ status }) => ACTIVE_STATUSES.includes(status)).length;
|
|
240
|
+
// The recorded active statuses are refreshed only when they would block, since a refresh can only lower them.
|
|
241
|
+
while (isAtLimit(recordedActiveRuns()) && isAtLimit(await this.countActiveRuns())) {
|
|
242
|
+
if (this.aborting) {
|
|
243
|
+
throw new Error('The child run was not started, because this run is being aborted or is exiting.');
|
|
244
|
+
}
|
|
245
|
+
// Unlike `sleep()` from `@crawlee/utils`, which uses `node:timers/promises`, a global timer can be faked.
|
|
246
|
+
await new Promise((resolve) => {
|
|
247
|
+
setTimeout(resolve, CONCURRENCY_POLL_INTERVAL_MILLIS);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Counts the recorded runs with an active status. A status older than {@link STATUS_MAX_AGE_MILLIS}, or recorded
|
|
253
|
+
* by an earlier process, is fetched from the API first.
|
|
254
|
+
*/
|
|
255
|
+
async countActiveRuns() {
|
|
256
|
+
const active = await Promise.all(Object.entries(this.registry.runs).map(async ([key, recorded]) => {
|
|
257
|
+
if (!ACTIVE_STATUSES.includes(recorded.status))
|
|
258
|
+
return false;
|
|
259
|
+
if (Date.now() - (this.observedAt.get(key) ?? -Infinity) <= STATUS_MAX_AGE_MILLIS)
|
|
260
|
+
return true;
|
|
261
|
+
let run;
|
|
262
|
+
try {
|
|
263
|
+
run = await this.clientFor(key).run(recorded.runId).get();
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
// E.g. a run started with another token in an earlier process, which would block the limit forever.
|
|
267
|
+
if (error instanceof ApifyApiError && [401, 403].includes(error.statusCode))
|
|
268
|
+
return false;
|
|
269
|
+
log.warning('Failed to refresh the status of a child run, counting it as active', {
|
|
270
|
+
runId: recorded.runId,
|
|
271
|
+
error: error.message,
|
|
272
|
+
});
|
|
273
|
+
this.observedAt.set(key, Date.now());
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
if (!run)
|
|
277
|
+
return false;
|
|
278
|
+
await this.record(key, { ...recorded, status: run.status });
|
|
279
|
+
return ACTIVE_STATUSES.includes(run.status);
|
|
280
|
+
}));
|
|
281
|
+
return active.filter(Boolean).length;
|
|
282
|
+
}
|
|
283
|
+
clientFor(key) {
|
|
284
|
+
return this.clients.get(key) ?? this.defaultClient;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Records `record` under `key`. Its status must be one just returned by the API.
|
|
288
|
+
*/
|
|
289
|
+
async record(key, record) {
|
|
290
|
+
this.observedAt.set(key, Date.now());
|
|
291
|
+
if (isDeepStrictEqual(this.registry.runs[key], record))
|
|
292
|
+
return;
|
|
293
|
+
this.registry.runs[key] = record;
|
|
294
|
+
this.warnIfExcessive();
|
|
295
|
+
await this.persist();
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Writes the registry once the write in progress finishes. The changes made until then are written together. A
|
|
299
|
+
* failed write is logged, not thrown, since the run is already started, and the next write saves the change too.
|
|
300
|
+
*/
|
|
301
|
+
async persist() {
|
|
302
|
+
if (!this.queuedWrite) {
|
|
303
|
+
this.queuedWrite = this.lastWrite.then(async () => {
|
|
304
|
+
this.queuedWrite = undefined;
|
|
305
|
+
await withDirectStorageAccess(async () => {
|
|
306
|
+
const store = await KeyValueStore.open();
|
|
307
|
+
await store.setValue(CHILD_RUNS_KVS_KEY, this.registry);
|
|
308
|
+
}).catch((error) => log.exception(error, 'Failed to write the child run registry'));
|
|
309
|
+
});
|
|
310
|
+
this.lastWrite = this.queuedWrite;
|
|
311
|
+
}
|
|
312
|
+
await this.queuedWrite;
|
|
313
|
+
}
|
|
314
|
+
warnIfExcessive() {
|
|
315
|
+
if (!this.warnOnExcessiveRuns || this.warnedExcessiveRuns)
|
|
316
|
+
return;
|
|
317
|
+
const count = Object.keys(this.registry.runs).length;
|
|
318
|
+
if (count <= EXCESSIVE_CHILD_RUNS_THRESHOLD)
|
|
319
|
+
return;
|
|
320
|
+
this.warnedExcessiveRuns = true;
|
|
321
|
+
log.warning(`Too many child runs (${count}). Tracking them can cause performance issues and excessive key-value store ` +
|
|
322
|
+
'usage. Turn child run tracking off with `trackChildRuns: false`, or mute this warning with ' +
|
|
323
|
+
'`disableExcessiveChildRunWarning: true`.');
|
|
324
|
+
}
|
|
325
|
+
assertEnabled(feature) {
|
|
326
|
+
if (this.enabled === undefined) {
|
|
327
|
+
throw new Error(`${feature} requires child run tracking, which starts in \`Actor.init()\`.`);
|
|
328
|
+
}
|
|
329
|
+
if (!this.enabled) {
|
|
330
|
+
throw new Error(`${feature} requires child run tracking, which is turned off with \`trackChildRuns: false\`.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|