apify 4.0.0-beta.14 → 4.0.0-beta.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +393 -281
  3. package/dist/actor.js +734 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +81 -0
  11. package/dist/apify_request_queue_backend.js +110 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +69 -47
  19. package/dist/charging.js +321 -223
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +67 -13
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +31 -21
  38. package/dist/proxy_configuration.js +136 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
@@ -0,0 +1,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,88 @@
1
+ import type { Run as ActorRun, RunClient, RunResurrectOptions } from 'apify-client';
2
+ import type { ApifyClient } from './index.js';
3
+ /**
4
+ * Status of a tracked child run. This copies the `ActorRun['status']` type,
5
+ * but adds `LOST` to mark a locally tracked run that the platform no longer returns.
6
+ *
7
+ * `LOST` runs can happen as a result of a manual removal or expiration.
8
+ */
9
+ export type ChildRunStatus = ActorRun['status'] | 'LOST';
10
+ export interface ChildRunInfo {
11
+ runId: string;
12
+ status: ChildRunStatus;
13
+ /** ISO 8601 timestamp. */
14
+ startedAt: string;
15
+ }
16
+ export interface TrackedChildRun extends ChildRunInfo {
17
+ /** Identifies the Actor / task and input the run was started with. */
18
+ checksum: string;
19
+ /** Earlier runs that were replaced under the same name, oldest first. */
20
+ history: ChildRunInfo[];
21
+ /** Whether the run is aborted when this run is gracefully aborted. */
22
+ abortWithParent: boolean;
23
+ }
24
+ export interface ChildRunRequest {
25
+ type: 'actor' | 'task';
26
+ id: string;
27
+ input?: unknown;
28
+ }
29
+ /**
30
+ * How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
31
+ * run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
32
+ */
33
+ export declare const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10000;
34
+ export declare class ChildRunTracker {
35
+ private trackedRuns;
36
+ private loading?;
37
+ /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
38
+ private clients;
39
+ private lastWrite;
40
+ private locks;
41
+ /** Set once this run is being gracefully aborted, after which no run with `abortWithParent` is started. */
42
+ private isParentAborting;
43
+ /**
44
+ * Throws if the run tracked under `runName` was started for a different Actor / task or input,
45
+ * as it would otherwise be silently returned or resurrected in place of the requested one.
46
+ */
47
+ verifyRequest(runName: string, request: ChildRunRequest): Promise<void>;
48
+ /**
49
+ * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
50
+ * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
51
+ * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
52
+ * keeping the previous one in the history. `abortWithParent` replaces the value tracked under `runName`.
53
+ */
54
+ startOrResumeChildRun(client: ApifyClient, runName: string, request: ChildRunRequest, startOptions: RunResurrectOptions, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<{
55
+ run: ActorRun;
56
+ resumed: boolean;
57
+ }>;
58
+ /**
59
+ * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
60
+ * history, with `replacedStatus` as its last known status.
61
+ */
62
+ track(runName: string, run: ActorRun, request: ChildRunRequest, replacedStatus: ChildRunStatus, abortWithParent: boolean): Promise<void>;
63
+ /**
64
+ * Records the latest observed state of the run tracked under `runName`.
65
+ */
66
+ update(runName: string, run: ActorRun): Promise<void>;
67
+ /**
68
+ * Returns the tracked run and its history for `runName`, if there is one.
69
+ */
70
+ get(runName: string): Promise<TrackedChildRun>;
71
+ /**
72
+ * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
73
+ * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
74
+ */
75
+ getRunClients(defaultClient: ApifyClient): Record<string, RunClient>;
76
+ /**
77
+ * Gracefully aborts the current run under each name tracked with `abortWithParent`, and makes any later start with
78
+ * `abortWithParent` throw. A start in flight is waited for, so the run it starts is aborted too. Resolves after
79
+ * {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in progress to go on.
80
+ */
81
+ abortRunsWithParent(defaultClient: ApifyClient): Promise<void>;
82
+ private getLock;
83
+ private persist;
84
+ /**
85
+ * Loads the tracked runs from the default key-value store, once.
86
+ */
87
+ load(): Promise<Record<string, TrackedChildRun>>;
88
+ }
@@ -0,0 +1,239 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { KeyValueStore, withDirectStorageAccess } from '@crawlee/core';
3
+ import { sleep } from '@crawlee/utils';
4
+ import { NotFoundError } from 'apify-client';
5
+ import { z } from 'zod';
6
+ import log from '@apify/log';
7
+ import { addTimeoutToPromise } from '@apify/timeout';
8
+ import { ReentrantAsyncLock } from './utils.js';
9
+ const sortKeys = (value) => {
10
+ if (Array.isArray(value))
11
+ return value.map(sortKeys);
12
+ if (value === null || typeof value !== 'object')
13
+ return value;
14
+ return Object.fromEntries(Object.entries(value)
15
+ .sort(([a], [b]) => Number(a > b) - Number(a < b))
16
+ .map(([key, nested]) => [key, sortKeys(nested)]));
17
+ };
18
+ // Hashes the JSON form that `apify-client` sends (`Date` -> ISO string, `URL` -> href, functions -> source),
19
+ // not the objects' own keys.
20
+ const toSentJson = (value) => JSON.parse(JSON.stringify(value, (_key, nested) => (typeof nested === 'function' ? nested.toString() : nested)));
21
+ const checksumRequest = ({ type, id, input }) => createHash('sha256')
22
+ .update(JSON.stringify(sortKeys(toSentJson({ type, id, input }))))
23
+ .digest('hex');
24
+ const toInfo = (run) => ({
25
+ runId: run.id,
26
+ status: run.status,
27
+ startedAt: run.startedAt.toISOString(),
28
+ });
29
+ const CHILD_RUNS_KVS_KEY = 'APIFY_ACTOR_CHILD_RUNS';
30
+ const childRunInfoSchema = z.object({ runId: z.string(), status: z.string(), startedAt: z.string() });
31
+ const trackedRunsSchema = z.record(z.string(), childRunInfoSchema.extend({
32
+ checksum: z.string(),
33
+ history: z.array(childRunInfoSchema).default([]),
34
+ abortWithParent: z.boolean().default(false),
35
+ }));
36
+ /** How many times a tracked run that the API reports as missing is looked up again before it counts as gone. */
37
+ const NOT_FOUND_RETRIES = 12;
38
+ const NOT_FOUND_RETRY_INTERVAL_MILLIS = 250;
39
+ /**
40
+ * Fetches a tracked run, retrying a 404 for a few seconds. A run started moments ago (e.g. by a concurrent call or
41
+ * right before a migration) may not be on every API replica yet, and treating it as gone would start a duplicate.
42
+ */
43
+ const getTrackedRun = async (runClient) => {
44
+ let run = await runClient.get();
45
+ for (let retry = 0; !run && retry < NOT_FOUND_RETRIES; retry++) {
46
+ await sleep(NOT_FOUND_RETRY_INTERVAL_MILLIS);
47
+ run = await runClient.get();
48
+ }
49
+ return run;
50
+ };
51
+ /** Statuses that shortly end as `ABORTED` / `TIMED-OUT`. */
52
+ const SETTLING_STATUSES = ['ABORTING', 'TIMING-OUT'];
53
+ const RESURRECTABLE_STATUSES = ['ABORTED', 'TIMED-OUT'];
54
+ const REUSABLE_STATUSES = ['READY', 'RUNNING', 'SUCCEEDED', ...RESURRECTABLE_STATUSES];
55
+ const ABORTED_STATUSES = ['ABORTING', 'ABORTED'];
56
+ /**
57
+ * How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
58
+ * run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
59
+ */
60
+ export const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10_000;
61
+ export class ChildRunTracker {
62
+ trackedRuns = {};
63
+ loading;
64
+ /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
65
+ clients = new Map();
66
+ lastWrite = Promise.resolve();
67
+ locks = new Map();
68
+ /** Set once this run is being gracefully aborted, after which no run with `abortWithParent` is started. */
69
+ isParentAborting = false;
70
+ /**
71
+ * Throws if the run tracked under `runName` was started for a different Actor / task or input,
72
+ * as it would otherwise be silently returned or resurrected in place of the requested one.
73
+ */
74
+ async verifyRequest(runName, request) {
75
+ const tracked = await this.get(runName);
76
+ if (tracked && tracked.checksum !== checksumRequest(request)) {
77
+ throw new Error(`The run name "${runName}" was already used for a different Actor, task or input. Use a unique \`runName\` for each child run.`);
78
+ }
79
+ }
80
+ /**
81
+ * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
82
+ * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
83
+ * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
84
+ * keeping the previous one in the history. `abortWithParent` replaces the value tracked under `runName`.
85
+ */
86
+ async startOrResumeChildRun(client, runName, request, startOptions, abortWithParent, start) {
87
+ return this.getLock(runName).runExclusive(async () => {
88
+ if (abortWithParent && this.isParentAborting) {
89
+ throw new Error(`Child run "${runName}" with \`abortWithParent\` was not started, because this run is being aborted.`);
90
+ }
91
+ const { build, memory, runTimeoutSecs, maxItems, maxTotalChargeUsd, restartOnError, timeoutSecs, signal } = startOptions;
92
+ const tracked = await this.get(runName);
93
+ let trackedRun = tracked ? await getTrackedRun(client.run(tracked.runId)) : undefined;
94
+ if (trackedRun && SETTLING_STATUSES.includes(trackedRun.status)) {
95
+ trackedRun = await client.run(trackedRun.id).waitForFinish({ timeoutSecs, signal });
96
+ }
97
+ if (trackedRun && REUSABLE_STATUSES.includes(trackedRun.status)) {
98
+ await this.verifyRequest(runName, request);
99
+ const run = RESURRECTABLE_STATUSES.includes(trackedRun.status)
100
+ ? await client.run(trackedRun.id).resurrect({
101
+ build,
102
+ memory,
103
+ runTimeoutSecs,
104
+ maxItems,
105
+ maxTotalChargeUsd,
106
+ restartOnError,
107
+ timeoutSecs,
108
+ signal,
109
+ })
110
+ : trackedRun;
111
+ if (tracked.abortWithParent !== abortWithParent) {
112
+ tracked.abortWithParent = abortWithParent;
113
+ await this.persist();
114
+ }
115
+ await this.update(runName, run);
116
+ this.clients.set(runName, client);
117
+ return { run, resumed: true };
118
+ }
119
+ const run = await start();
120
+ await this.track(runName, run, request, trackedRun?.status ?? 'LOST', abortWithParent);
121
+ this.clients.set(runName, client);
122
+ return { run, resumed: false };
123
+ });
124
+ }
125
+ /**
126
+ * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
127
+ * history, with `replacedStatus` as its last known status.
128
+ */
129
+ async track(runName, run, request, replacedStatus, abortWithParent) {
130
+ const trackedRuns = await this.load();
131
+ const previous = trackedRuns[runName];
132
+ trackedRuns[runName] = {
133
+ ...toInfo(run),
134
+ checksum: checksumRequest(request),
135
+ history: previous
136
+ ? [
137
+ ...previous.history,
138
+ { runId: previous.runId, startedAt: previous.startedAt, status: replacedStatus },
139
+ ]
140
+ : [],
141
+ abortWithParent,
142
+ };
143
+ await this.persist();
144
+ }
145
+ /**
146
+ * Records the latest observed state of the run tracked under `runName`.
147
+ */
148
+ async update(runName, run) {
149
+ const trackedRuns = await this.load();
150
+ const tracked = trackedRuns[runName];
151
+ if (tracked?.runId !== run.id || tracked.status === run.status)
152
+ return;
153
+ tracked.status = run.status;
154
+ await this.persist();
155
+ }
156
+ /**
157
+ * Returns the tracked run and its history for `runName`, if there is one.
158
+ */
159
+ async get(runName) {
160
+ const trackedRuns = await this.load();
161
+ return trackedRuns[runName];
162
+ }
163
+ /**
164
+ * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
165
+ * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
166
+ */
167
+ getRunClients(defaultClient) {
168
+ return Object.fromEntries(Object.entries(this.trackedRuns).map(([runName, { runId }]) => [
169
+ runName,
170
+ (this.clients.get(runName) ?? defaultClient).run(runId),
171
+ ]));
172
+ }
173
+ /**
174
+ * Gracefully aborts the current run under each name tracked with `abortWithParent`, and makes any later start with
175
+ * `abortWithParent` throw. A start in flight is waited for, so the run it starts is aborted too. Resolves after
176
+ * {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in progress to go on.
177
+ */
178
+ async abortRunsWithParent(defaultClient) {
179
+ this.isParentAborting = true;
180
+ const trackedRuns = await this.load();
181
+ const runNames = new Set([...Object.keys(trackedRuns), ...this.locks.keys()]);
182
+ const aborts = Promise.all([...runNames].map(async (runName) => this.getLock(runName).runExclusive(async () => {
183
+ const tracked = await this.get(runName);
184
+ if (!tracked?.abortWithParent)
185
+ return;
186
+ try {
187
+ const run = await (this.clients.get(runName) ?? defaultClient)
188
+ .run(tracked.runId)
189
+ .abort({ gracefully: true });
190
+ if (ABORTED_STATUSES.includes(run.status)) {
191
+ log.info(`Aborted child run "${runName}" with the parent`, { runId: run.id });
192
+ }
193
+ }
194
+ catch (error) {
195
+ if (error instanceof NotFoundError)
196
+ return;
197
+ log.exception(error, `Failed to abort child run "${runName}"`, {
198
+ runId: tracked.runId,
199
+ });
200
+ }
201
+ })));
202
+ // `Actor.exit()` waits for this listener without a timeout of its own.
203
+ 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));
204
+ }
205
+ getLock(runName) {
206
+ if (!this.locks.has(runName)) {
207
+ this.locks.set(runName, new ReentrantAsyncLock());
208
+ }
209
+ return this.locks.get(runName);
210
+ }
211
+ async persist() {
212
+ const write = this.lastWrite.then(async () => withDirectStorageAccess(async () => {
213
+ const defaultStore = await KeyValueStore.open();
214
+ await defaultStore.setValue(CHILD_RUNS_KVS_KEY, this.trackedRuns);
215
+ }));
216
+ this.lastWrite = write.catch(() => { });
217
+ await write;
218
+ }
219
+ /**
220
+ * Loads the tracked runs from the default key-value store, once.
221
+ */
222
+ async load() {
223
+ this.loading ??= KeyValueStore.open()
224
+ .then(async (defaultStore) => defaultStore.getValue(CHILD_RUNS_KVS_KEY))
225
+ .then((storedRuns) => {
226
+ const parsed = trackedRunsSchema.safeParse(storedRuns ?? {});
227
+ if (!parsed.success) {
228
+ 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 });
229
+ }
230
+ this.trackedRuns = parsed.data;
231
+ })
232
+ .catch((error) => {
233
+ this.loading = undefined;
234
+ throw error;
235
+ });
236
+ await this.loading;
237
+ return this.trackedRuns;
238
+ }
239
+ }
@@ -2,55 +2,65 @@ import type { ConfigField, FieldsInput, FieldsOutput } from '@crawlee/core';
2
2
  import { Configuration as CoreConfiguration } from '@crawlee/core';
3
3
  import { z } from 'zod';
4
4
  export declare const apifyConfigFields: {
5
+ maxUsedCpuRatio: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
6
+ internalTimeoutMillis: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber, unknown>>>;
7
+ systemInfoIntervalMillis: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
8
+ logLevel: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodEnum<typeof import("@crawlee/core").LogLevel>, unknown>>>;
9
+ persistStorage: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
10
+ storageDir: ConfigField<z.ZodDefault<z.ZodString>>;
11
+ containerized: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
12
+ memoryMbytes: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber, unknown>>>;
13
+ availableMemoryRatio: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
14
+ disableBrowserSandbox: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
15
+ persistStateIntervalMillis: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
16
+ headless: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
17
+ xvfb: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
18
+ chromeExecutablePath: ConfigField<z.ZodOptional<z.ZodString>>;
19
+ defaultBrowserPath: ConfigField<z.ZodOptional<z.ZodString>>;
20
+ purgeOnStart: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
5
21
  defaultDatasetId: ConfigField<z.ZodDefault<z.ZodString>>;
6
22
  defaultKeyValueStoreId: ConfigField<z.ZodDefault<z.ZodString>>;
7
23
  defaultRequestQueueId: ConfigField<z.ZodDefault<z.ZodString>>;
8
24
  inputKey: ConfigField<z.ZodDefault<z.ZodString>>;
9
- memoryMbytes: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
10
- availableMemoryRatio: ConfigField<any>;
11
- disableBrowserSandbox: ConfigField<any>;
12
- persistStateIntervalMillis: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
13
- headless: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
14
- xvfb: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
15
- chromeExecutablePath: ConfigField<z.ZodOptional<z.ZodString>>;
16
- defaultBrowserPath: ConfigField<z.ZodOptional<z.ZodString>>;
17
- purgeOnStart: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
18
- metamorphAfterSleepMillis: ConfigField<any>;
25
+ metamorphAfterSleepMillis: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
19
26
  actorEventsWsUrl: ConfigField<z.ZodOptional<z.ZodString>>;
20
27
  token: ConfigField<z.ZodOptional<z.ZodString>>;
21
28
  actorId: ConfigField<z.ZodOptional<z.ZodString>>;
22
29
  actorRunId: ConfigField<z.ZodOptional<z.ZodString>>;
23
30
  actorTaskId: ConfigField<z.ZodOptional<z.ZodString>>;
31
+ actorBuildId: ConfigField<z.ZodOptional<z.ZodString>>;
32
+ actorBuildNumber: ConfigField<z.ZodOptional<z.ZodString>>;
33
+ actorBuildTags: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodString>, unknown>>>;
34
+ actorFullName: ConfigField<z.ZodOptional<z.ZodString>>;
35
+ workflowKey: ConfigField<z.ZodOptional<z.ZodString>>;
36
+ startedAt: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodDate, unknown>>>;
37
+ timeoutAt: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodDate, unknown>>>;
38
+ maxPaidDatasetItems: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber, unknown>>>;
39
+ dedicatedCpus: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber, unknown>>>;
24
40
  apiBaseUrl: ConfigField<z.ZodDefault<z.ZodString>>;
25
41
  apiPublicBaseUrl: ConfigField<z.ZodDefault<z.ZodString>>;
26
- containerPort: ConfigField<any>;
42
+ containerPort: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
27
43
  containerUrl: ConfigField<z.ZodDefault<z.ZodString>>;
28
44
  proxyHostname: ConfigField<z.ZodDefault<z.ZodString>>;
29
45
  proxyPassword: ConfigField<z.ZodOptional<z.ZodString>>;
30
- proxyPort: ConfigField<any>;
46
+ proxyPort: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
31
47
  proxyStatusUrl: ConfigField<z.ZodDefault<z.ZodString>>;
32
48
  /** @deprecated use `containerPort` instead */
33
- standbyPort: ConfigField<any>;
49
+ standbyPort: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
34
50
  standbyUrl: ConfigField<z.ZodOptional<z.ZodString>>;
35
- isAtHome: ConfigField<any>;
51
+ isAtHome: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
36
52
  userId: ConfigField<z.ZodOptional<z.ZodString>>;
37
- userIsPaying: ConfigField<z.ZodOptional<z.ZodString>>;
53
+ userIsPaying: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
38
54
  actorPermissionLevel: ConfigField<z.ZodOptional<z.ZodString>>;
39
55
  inputSecretsPrivateKeyPassphrase: ConfigField<z.ZodOptional<z.ZodString>>;
40
56
  inputSecretsPrivateKeyFile: ConfigField<z.ZodOptional<z.ZodString>>;
41
- maxTotalChargeUsd: ConfigField<any>;
57
+ maxTotalChargeUsd: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodPreprocess<z.ZodNumber, unknown>, z.ZodTransform<number, number>>>>;
42
58
  metaOrigin: ConfigField<z.ZodOptional<z.ZodString>>;
43
- testPayPerEvent: ConfigField<any>;
44
- useChargingLogDataset: ConfigField<any>;
59
+ testPayPerEvent: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
45
60
  actorPricingInfo: ConfigField<z.ZodOptional<z.ZodString>>;
46
61
  chargedEventCounts: ConfigField<z.ZodOptional<z.ZodString>>;
47
62
  actorStoragesJson: ConfigField<z.ZodOptional<z.ZodString>>;
48
63
  storageClientOptions: ConfigField<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
49
- maxUsedCpuRatio: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
50
- systemInfoIntervalMillis: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
51
- logLevel: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<{} | null | undefined, unknown>, z.ZodEnum<typeof import("@apify/log").LogLevel>>>>;
52
- persistStorage: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
53
- containerized: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
54
64
  };
55
65
  export type ApifyConfigurationInput = FieldsInput<typeof apifyConfigFields>;
56
66
  export type ApifyResolvedConfigValues = FieldsOutput<typeof apifyConfigFields>;
@@ -61,13 +71,13 @@ export interface Configuration extends ApifyResolvedConfigValues {
61
71
  /**
62
72
  * `Configuration` is a value object holding the SDK configuration. We can use it in two ways:
63
73
  *
64
- * 1. When using `Actor` class, we can get the instance configuration via `sdk.config`
74
+ * 1. When using `Actor` class, we can get the instance configuration via `sdk.configuration`
65
75
  *
66
76
  * ```javascript
67
77
  * import { Actor } from 'apify';
68
78
  *
69
79
  * const sdk = new Actor({ token: '123' });
70
- * console.log(sdk.config.token); // '123'
80
+ * console.log(sdk.configuration.token); // '123'
71
81
  * ```
72
82
  *
73
83
  * 2. To get the global configuration (singleton instance). It will respect the environment variables.
@@ -75,7 +85,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
75
85
  * ```javascript
76
86
  * import { Configuration } from 'apify';
77
87
  *
78
- * const config = Configuration.getGlobalConfig();
88
+ * const config = Configuration.getGlobalConfiguration();
79
89
  * console.log(config.headless);
80
90
  * console.log(config.persistStateIntervalMillis);
81
91
  * ```
@@ -108,7 +118,16 @@ export interface Configuration extends ApifyResolvedConfigValues {
108
118
  * `actorId` | `ACTOR_ID` | -
109
119
  * `actorRunId` | `ACTOR_RUN_ID` | -
110
120
  * `actorTaskId` | `ACTOR_TASK_ID` | -
111
- * `apiBaseUrl` | `APIFY_API_BASE_URL` | `'https://api.apify.com'`
121
+ * `actorBuildId` | `ACTOR_BUILD_ID` | -
122
+ * `actorBuildNumber` | `ACTOR_BUILD_NUMBER` | -
123
+ * `actorBuildTags` | `ACTOR_BUILD_TAGS` | -
124
+ * `actorFullName` | `ACTOR_FULL_NAME` | -
125
+ * `workflowKey` | `APIFY_WORKFLOW_KEY` | -
126
+ * `startedAt` | `ACTOR_STARTED_AT` | -
127
+ * `timeoutAt` | `ACTOR_TIMEOUT_AT` | -
128
+ * `maxPaidDatasetItems` | `ACTOR_MAX_PAID_DATASET_ITEMS` | -
129
+ * `dedicatedCpus` | `APIFY_DEDICATED_CPUS` | -
130
+ * `apiBaseUrl` | `APIFY_API_BASE_URL` | `'https://api.apify.com/'`
112
131
  * `containerPort` | `ACTOR_WEB_SERVER_PORT` | `4321`
113
132
  * `containerUrl` | `ACTOR_WEB_SERVER_URL` | `'http://localhost:4321'`
114
133
  * `inputKey` | `ACTOR_INPUT_KEY` | `'INPUT'`
@@ -119,6 +138,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
119
138
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
120
139
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
121
140
  * `userId` | `APIFY_USER_ID` | -
141
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
122
142
  * `xvfb` | `APIFY_XVFB` | -
123
143
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
124
144
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
@@ -139,5 +159,5 @@ export declare class Configuration extends CoreConfiguration {
139
159
  * what crawlee internals resolve against; this singleton is only the
140
160
  * fallback for code reaching for a configuration without an explicit one.
141
161
  */
142
- static getGlobalConfig(): Configuration;
162
+ static getGlobalConfiguration(): Configuration;
143
163
  }