apify 3.7.3-beta.97 → 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 +237 -293
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +105 -0
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +85 -144
- package/dist/configuration.js +138 -174
- package/dist/enqueue_links_filters.d.ts +29 -0
- package/dist/enqueue_links_filters.js +52 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +22 -0
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +12 -22
- package/dist/input-schemas.d.ts +1 -1
- package/dist/input-schemas.js +12 -18
- package/dist/platform_event_manager.d.ts +15 -10
- package/dist/platform_event_manager.js +193 -63
- package/dist/proxy_configuration.d.ts +52 -72
- package/dist/proxy_configuration.js +176 -221
- package/dist/smart_apify_storage_backend.d.ts +52 -0
- package/dist/smart_apify_storage_backend.js +73 -0
- package/dist/storage.d.ts +6 -24
- package/dist/storage.js +1 -79
- package/dist/utils.d.ts +30 -0
- package/dist/utils.js +81 -23
- package/package.json +38 -43
- package/dist/index.mjs +0 -19
- package/dist/key_value_store.d.ts +0 -16
- package/dist/key_value_store.js +0 -40
- package/dist/patched_apify_client.d.ts +0 -25
- package/dist/patched_apify_client.js +0 -75
|
@@ -0,0 +1,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,105 @@
|
|
|
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.
|
|
34
|
+
if (items.length === 0 || !chargingManager.isInitialized || !chargingManager.isPayPerEvent) {
|
|
35
|
+
await this.#inner.pushData(items);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
await chargingManager.withChargeLock(async () => {
|
|
39
|
+
const limit = chargingManager.calculatePushDataLimit(items.length, { isDefaultDataset: true });
|
|
40
|
+
if (limit === 0) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
await this.#inner.pushData(limit < items.length ? items.slice(0, limit) : items);
|
|
44
|
+
await chargingManager.charge({ eventName: DEFAULT_DATASET_ITEM_EVENT, count: limit });
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Wraps another storage backend so that items pushed to the run's default dataset are charged for
|
|
50
|
+
* under the pay-per-event pricing model.
|
|
51
|
+
*
|
|
52
|
+
* Charging belongs here rather than in `Actor.pushData()` because `Dataset.pushData()` is also
|
|
53
|
+
* called directly - by user code and by crawlee itself (`context.pushData()`) - and every item that
|
|
54
|
+
* reaches the default dataset is billed by the platform regardless of who pushed it.
|
|
55
|
+
*
|
|
56
|
+
* @internal
|
|
57
|
+
*/
|
|
58
|
+
export class ChargingStorageBackend {
|
|
59
|
+
storageExists;
|
|
60
|
+
purge;
|
|
61
|
+
teardown;
|
|
62
|
+
#inner;
|
|
63
|
+
#options;
|
|
64
|
+
constructor(inner, options) {
|
|
65
|
+
this.#inner = inner;
|
|
66
|
+
this.#options = options;
|
|
67
|
+
// Crawlee branches on the presence of these, so they have to stay absent when `inner` lacks them.
|
|
68
|
+
const { storageExists, purge, teardown } = inner;
|
|
69
|
+
if (storageExists)
|
|
70
|
+
this.storageExists = async (id, type) => storageExists.call(inner, id, type);
|
|
71
|
+
if (purge)
|
|
72
|
+
this.purge = async () => purge.call(inner);
|
|
73
|
+
if (teardown)
|
|
74
|
+
this.teardown = async () => teardown.call(inner);
|
|
75
|
+
}
|
|
76
|
+
get stats() {
|
|
77
|
+
return this.#inner.stats;
|
|
78
|
+
}
|
|
79
|
+
/** Repeats crawlee's own fallback, so that wrapping a backend does not change how storages are cached. */
|
|
80
|
+
getStorageBackendCacheKey() {
|
|
81
|
+
return this.#inner.getStorageBackendCacheKey?.() ?? this.#inner.constructor.name;
|
|
82
|
+
}
|
|
83
|
+
async createDatasetBackend(options) {
|
|
84
|
+
const backend = await this.#inner.createDatasetBackend(options);
|
|
85
|
+
if (!this.isDefaultDataset(options)) {
|
|
86
|
+
return backend;
|
|
87
|
+
}
|
|
88
|
+
return new ChargingDatasetBackend(backend, this.#options.getChargingManager);
|
|
89
|
+
}
|
|
90
|
+
async createKeyValueStoreBackend(options) {
|
|
91
|
+
return await this.#inner.createKeyValueStoreBackend(options);
|
|
92
|
+
}
|
|
93
|
+
async createRequestQueueBackend(options) {
|
|
94
|
+
return await this.#inner.createRequestQueueBackend(options);
|
|
95
|
+
}
|
|
96
|
+
isDefaultDataset(options) {
|
|
97
|
+
if (!options)
|
|
98
|
+
return true;
|
|
99
|
+
if (options.alias !== undefined)
|
|
100
|
+
return options.alias === DEFAULT_STORAGE_ALIAS;
|
|
101
|
+
if (options.id !== undefined)
|
|
102
|
+
return options.id === this.#options.configuration.defaultDatasetId;
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -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 = '__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
|
+
}
|