apify 4.0.0-rc.0 → 4.0.0-rc.1
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/dist/actor.d.ts +250 -29
- package/dist/actor.js +377 -126
- package/dist/apify_request_queue_backend.d.ts +1 -1
- package/dist/apify_request_queue_backend.js +1 -1
- package/dist/apify_request_queue_shared_backend.d.ts +2 -2
- package/dist/apify_request_queue_shared_backend.js +4 -4
- package/dist/apify_storage_backend.js +6 -13
- package/dist/charging.d.ts +27 -5
- package/dist/charging.js +155 -29
- package/dist/charging_storage_backend.js +6 -2
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +2 -1
- package/dist/configuration.js +2 -1
- package/dist/errors.d.ts +2 -2
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/platform_event_manager.d.ts +13 -2
- package/dist/platform_event_manager.js +178 -32
- package/dist/proxy_configuration.js +5 -2
- package/dist/utils.d.ts +5 -3
- package/dist/utils.js +14 -13
- package/package.json +31 -33
|
@@ -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
|
+
}
|
package/dist/configuration.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export declare const apifyConfigFields: {
|
|
|
41
41
|
standbyUrl: ConfigField<z.ZodOptional<z.ZodString>>;
|
|
42
42
|
isAtHome: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
|
|
43
43
|
userId: ConfigField<z.ZodOptional<z.ZodString>>;
|
|
44
|
-
userIsPaying: ConfigField<z.
|
|
44
|
+
userIsPaying: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
|
|
45
45
|
actorPermissionLevel: ConfigField<z.ZodOptional<z.ZodString>>;
|
|
46
46
|
inputSecretsPrivateKeyPassphrase: ConfigField<z.ZodOptional<z.ZodString>>;
|
|
47
47
|
inputSecretsPrivateKeyFile: ConfigField<z.ZodOptional<z.ZodString>>;
|
|
@@ -121,6 +121,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
|
|
|
121
121
|
* `proxyPort` | `APIFY_PROXY_PORT` | `8000`
|
|
122
122
|
* `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
|
|
123
123
|
* `userId` | `APIFY_USER_ID` | -
|
|
124
|
+
* `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
|
|
124
125
|
* `xvfb` | `APIFY_XVFB` | -
|
|
125
126
|
* `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
|
|
126
127
|
* `standbyUrl` | `ACTOR_STANDBY_URL` | -
|
package/dist/configuration.js
CHANGED
|
@@ -85,7 +85,7 @@ export const apifyConfigFields = {
|
|
|
85
85
|
standbyUrl: field(z.string().optional(), ACTOR_ENV_VARS.STANDBY_URL),
|
|
86
86
|
isAtHome: field(coerceBoolean.default(false), APIFY_ENV_VARS.IS_AT_HOME),
|
|
87
87
|
userId: field(z.string().optional(), APIFY_ENV_VARS.USER_ID),
|
|
88
|
-
userIsPaying: field(
|
|
88
|
+
userIsPaying: field(coerceBoolean.default(false), APIFY_ENV_VARS.USER_IS_PAYING),
|
|
89
89
|
actorPermissionLevel: field(z.string().optional(), ACTOR_ENV_VARS.PERMISSION_LEVEL),
|
|
90
90
|
inputSecretsPrivateKeyPassphrase: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_PASSPHRASE),
|
|
91
91
|
inputSecretsPrivateKeyFile: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_FILE),
|
|
@@ -164,6 +164,7 @@ export const apifyConfigFields = {
|
|
|
164
164
|
* `proxyPort` | `APIFY_PROXY_PORT` | `8000`
|
|
165
165
|
* `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
|
|
166
166
|
* `userId` | `APIFY_USER_ID` | -
|
|
167
|
+
* `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
|
|
167
168
|
* `xvfb` | `APIFY_XVFB` | -
|
|
168
169
|
* `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
|
|
169
170
|
* `standbyUrl` | `ACTOR_STANDBY_URL` | -
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** Why {@link Actor.getInput} could not produce the input. */
|
|
2
2
|
export type ActorInputErrorCode =
|
|
3
|
-
/** No input record in the default key-value store, and locally no input file
|
|
3
|
+
/** No input record in the default key-value store, and locally no input file either. */
|
|
4
4
|
'NOT_FOUND'
|
|
5
|
-
/**
|
|
5
|
+
/** The input is in more than one place — both `<inputKey>` and `<inputKey>.json` in one directory, or in the store and in the working directory — so none is picked. */
|
|
6
6
|
| 'MULTIPLE_FILES'
|
|
7
7
|
/** The secret fields of the input could not be decrypted; `cause` holds the underlying error. */
|
|
8
8
|
| 'DECRYPTION_FAILED'
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Dictionary } from '@crawlee/types';
|
|
2
|
+
/**
|
|
3
|
+
* Turns a Google Sheets sharing link into the link of its CSV export, other URLs are returned unchanged.
|
|
4
|
+
* @internal
|
|
5
|
+
*/
|
|
6
|
+
export declare function toGoogleSheetsCsvUrl(url: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* Replaces Google Sheets sharing links in the `requestsFromUrl` entries of the input's array fields (as produced by
|
|
9
|
+
* the "Link remote text file" option of the `requestListSources` editor) with the links of their CSV exports.
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
export declare function fixGoogleSheetsUrls<T extends Dictionary>(input: T): T;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Links published to the web (`/spreadsheets/d/e/<id>/pub?output=csv`) and links that already point at an export
|
|
2
|
+
// (`/gviz/...`, `/export...`) are downloadable as they are, so they're left alone.
|
|
3
|
+
const GOOGLE_SHEETS_URL_REGEX = /^(https:\/\/docs\.google\.com\/spreadsheets\/d\/(?!e\/)(?:\w|-)+)(\/(?:gviz|export)\b)?/;
|
|
4
|
+
/**
|
|
5
|
+
* Turns a Google Sheets sharing link into the link of its CSV export, other URLs are returned unchanged.
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export function toGoogleSheetsCsvUrl(url) {
|
|
9
|
+
const match = GOOGLE_SHEETS_URL_REGEX.exec(url);
|
|
10
|
+
return match && !match[2] ? `${match[1]}/gviz/tq?tqx=out:csv` : url;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Replaces Google Sheets sharing links in the `requestsFromUrl` entries of the input's array fields (as produced by
|
|
14
|
+
* the "Link remote text file" option of the `requestListSources` editor) with the links of their CSV exports.
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
export function fixGoogleSheetsUrls(input) {
|
|
18
|
+
return Object.fromEntries(Object.entries(input).map(([key, value]) => [
|
|
19
|
+
key,
|
|
20
|
+
Array.isArray(value)
|
|
21
|
+
? value.map((item) => typeof item?.requestsFromUrl === 'string'
|
|
22
|
+
? { ...item, requestsFromUrl: toGoogleSheetsCsvUrl(item.requestsFromUrl) }
|
|
23
|
+
: item)
|
|
24
|
+
: value,
|
|
25
|
+
]));
|
|
26
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -12,4 +12,4 @@ export * from './proxy_configuration.js';
|
|
|
12
12
|
export * from './platform_event_manager.js';
|
|
13
13
|
export { Dataset, DatasetDataOptions, DatasetIteratorOptions, DatasetConsumer, DatasetMapper, DatasetReducer, DatasetOptions, DatasetContent, RequestQueue, RequestQueueOperationOptions, RequestQueueOptions, KeyValueStore, KeyConsumer, KeyValueStoreOptions, RecordOptions, KeyValueStoreIteratorOptions, log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
|
|
14
14
|
export type { QueueOperationInfo } from '@crawlee/types';
|
|
15
|
-
export { ApifyClient, ApifyClientOptions } from 'apify-client';
|
|
15
|
+
export { ApifyClient, ApifyClientOptions, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
package/dist/index.js
CHANGED
|
@@ -9,4 +9,4 @@ export * from './configuration.js';
|
|
|
9
9
|
export * from './proxy_configuration.js';
|
|
10
10
|
export * from './platform_event_manager.js';
|
|
11
11
|
export { Dataset, RequestQueue, KeyValueStore, log, Log, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
|
|
12
|
-
export { ApifyClient } from 'apify-client';
|
|
12
|
+
export { ApifyClient, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EventTypeName } from '@crawlee/core';
|
|
1
2
|
import { EventManager } from '@crawlee/core';
|
|
2
3
|
import { Configuration } from './configuration.js';
|
|
3
4
|
/**
|
|
@@ -37,17 +38,27 @@ import { Configuration } from './configuration.js';
|
|
|
37
38
|
* in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
|
|
38
39
|
* Note that the `persistState` event is provided merely for user convenience,
|
|
39
40
|
* you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
|
|
41
|
+
*
|
|
42
|
+
* The connection to the platform events websocket is re-established after it drops, unless it was closed
|
|
43
|
+
* with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
|
|
40
44
|
*/
|
|
41
45
|
export declare class PlatformEventManager extends EventManager {
|
|
42
46
|
#private;
|
|
43
47
|
readonly configuration: Configuration;
|
|
44
|
-
|
|
48
|
+
/**
|
|
49
|
+
* @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
|
|
50
|
+
* user code can neither remove them with `off()` nor see them in `listeners()`.
|
|
51
|
+
*/
|
|
52
|
+
constructor(configuration?: Configuration, internalListeners?: Partial<Record<EventTypeName, (...args: any[]) => unknown>>);
|
|
53
|
+
emit(event: EventTypeName, ...args: unknown[]): void;
|
|
54
|
+
waitForAllListenersToComplete(): Promise<boolean>;
|
|
45
55
|
/**
|
|
46
56
|
* Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
|
|
47
57
|
* This is an internal function that is automatically called by `Actor.main()`.
|
|
58
|
+
*
|
|
59
|
+
* Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
|
|
48
60
|
*/
|
|
49
61
|
init(): Promise<void>;
|
|
50
|
-
private createWebSocketConnection;
|
|
51
62
|
/**
|
|
52
63
|
* Closes websocket providing events from Actor infrastructure and also stops sending internal events
|
|
53
64
|
* of Apify package such as `persistState`.
|
|
@@ -1,8 +1,34 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
1
2
|
import { EventManager, EventType } from '@crawlee/core';
|
|
2
3
|
import { WebSocket } from 'ws';
|
|
3
4
|
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES } from '@apify/consts';
|
|
4
5
|
import { betterClearInterval } from '@apify/utilities';
|
|
5
6
|
import { Configuration } from './configuration.js';
|
|
7
|
+
/**
|
|
8
|
+
* WebSocket close codes for a permanent condition, on which the connection is not re-established.
|
|
9
|
+
*
|
|
10
|
+
* The platform sends `1008` (policy violation) for an unknown/missing run ID or an exceeded per-run connection limit.
|
|
11
|
+
* The rest are protocol, data, or mandatory-extension failures that reconnecting cannot resolve.
|
|
12
|
+
*/
|
|
13
|
+
const NON_RETRYABLE_CLOSE_CODES = new Set([1002, 1003, 1007, 1008, 1010]);
|
|
14
|
+
/** Close codes of a clean close, as opposed to a lost connection. */
|
|
15
|
+
const CLEAN_CLOSE_CODES = new Set([1000, 1001]);
|
|
16
|
+
/** How long a connection must stay open to count as healthy, after which a drop reconnects without backoff. */
|
|
17
|
+
const HEALTHY_CONNECTION_MIN_DURATION_MILLIS = 1000;
|
|
18
|
+
/**
|
|
19
|
+
* Delays between reconnection attempts, mirroring the Python `websockets` library
|
|
20
|
+
* (see RFC 6455, section 7.2.3): a random initial delay, then exponential growth up to a cap.
|
|
21
|
+
*/
|
|
22
|
+
function* backoffDelays() {
|
|
23
|
+
yield Math.random() * 5000;
|
|
24
|
+
let delay = 3100;
|
|
25
|
+
while (delay < 90_000) {
|
|
26
|
+
yield delay;
|
|
27
|
+
delay *= 1.618;
|
|
28
|
+
}
|
|
29
|
+
while (true)
|
|
30
|
+
yield 90_000;
|
|
31
|
+
}
|
|
6
32
|
/**
|
|
7
33
|
* Gets an instance of a Node.js'
|
|
8
34
|
* [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
|
@@ -40,20 +66,51 @@ import { Configuration } from './configuration.js';
|
|
|
40
66
|
* in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`.
|
|
41
67
|
* Note that the `persistState` event is provided merely for user convenience,
|
|
42
68
|
* you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
|
|
69
|
+
*
|
|
70
|
+
* The connection to the platform events websocket is re-established after it drops, unless it was closed
|
|
71
|
+
* with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
|
|
43
72
|
*/
|
|
44
73
|
export class PlatformEventManager extends EventManager {
|
|
45
74
|
configuration;
|
|
46
75
|
/** Websocket connection to Actor events. */
|
|
47
76
|
#eventsWs;
|
|
48
|
-
|
|
77
|
+
/** Aborted by `close()`, which stops any pending reconnection and marks the final close as intentional. */
|
|
78
|
+
#abortController = new AbortController();
|
|
79
|
+
/** Backoff for rapid reconnections; reset after a connection that stayed open long enough to count as healthy. */
|
|
80
|
+
#backoff;
|
|
81
|
+
#internalListeners;
|
|
82
|
+
/** Calls of the internal listeners that are still in progress. */
|
|
83
|
+
#internalListenerCalls = new Set();
|
|
84
|
+
/**
|
|
85
|
+
* @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
|
|
86
|
+
* user code can neither remove them with `off()` nor see them in `listeners()`.
|
|
87
|
+
*/
|
|
88
|
+
constructor(configuration = Configuration.getGlobalConfiguration(), internalListeners = {}) {
|
|
49
89
|
super({
|
|
50
90
|
persistStateIntervalMillis: configuration.persistStateIntervalMillis,
|
|
51
91
|
});
|
|
52
92
|
this.configuration = configuration;
|
|
93
|
+
this.#internalListeners = internalListeners;
|
|
94
|
+
}
|
|
95
|
+
emit(event, ...args) {
|
|
96
|
+
super.emit(event, ...args);
|
|
97
|
+
const listener = this.#internalListeners[event];
|
|
98
|
+
if (!listener)
|
|
99
|
+
return;
|
|
100
|
+
const call = (async () => listener(...args))()
|
|
101
|
+
.catch((err) => this.log.exception(err, `Internal listener of the "${event}" event failed`))
|
|
102
|
+
.finally(() => this.#internalListenerCalls.delete(call));
|
|
103
|
+
this.#internalListenerCalls.add(call);
|
|
104
|
+
}
|
|
105
|
+
async waitForAllListenersToComplete() {
|
|
106
|
+
const [completed] = await Promise.all([super.waitForAllListenersToComplete(), ...this.#internalListenerCalls]);
|
|
107
|
+
return completed;
|
|
53
108
|
}
|
|
54
109
|
/**
|
|
55
110
|
* Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
|
|
56
111
|
* This is an internal function that is automatically called by `Actor.main()`.
|
|
112
|
+
*
|
|
113
|
+
* Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
|
|
57
114
|
*/
|
|
58
115
|
async init() {
|
|
59
116
|
if (this.initialized) {
|
|
@@ -66,37 +123,16 @@ export class PlatformEventManager extends EventManager {
|
|
|
66
123
|
this.log.debug(`Environment variable ${ACTOR_ENV_VARS.EVENTS_WEBSOCKET_URL} is not set, no events from Apify platform will be emitted.`);
|
|
67
124
|
return;
|
|
68
125
|
}
|
|
69
|
-
this
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (name === ACTOR_EVENT_NAMES.MIGRATING) {
|
|
80
|
-
betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
|
|
81
|
-
this.events.emit(EventType.PERSIST_STATE, {
|
|
82
|
-
isMigrating: true,
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
catch (err) {
|
|
87
|
-
this.log.exception(err, 'Cannot parse Actor event');
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
this.#eventsWs.on('error', (err) => {
|
|
91
|
-
// Don't print this error as this happens in the case of very short Actor.main().
|
|
92
|
-
if (err.message === 'WebSocket was closed before the connection was established')
|
|
93
|
-
return;
|
|
94
|
-
this.log.exception(err, 'web socket connection failed');
|
|
95
|
-
});
|
|
96
|
-
this.#eventsWs.on('close', () => {
|
|
97
|
-
this.log.debug('web socket has been closed');
|
|
98
|
-
this.#eventsWs = undefined;
|
|
99
|
-
});
|
|
126
|
+
this.#abortController = new AbortController();
|
|
127
|
+
this.#backoff = undefined;
|
|
128
|
+
try {
|
|
129
|
+
await this.#connect(eventsWsUrl);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
// Leave no `persistState` interval behind, so that `init()` can be retried.
|
|
133
|
+
await this.close();
|
|
134
|
+
throw new Error('Error connecting to platform events websocket!', { cause: err });
|
|
135
|
+
}
|
|
100
136
|
}
|
|
101
137
|
/**
|
|
102
138
|
* Closes websocket providing events from Actor infrastructure and also stops sending internal events
|
|
@@ -108,6 +144,116 @@ export class PlatformEventManager extends EventManager {
|
|
|
108
144
|
return;
|
|
109
145
|
}
|
|
110
146
|
await super.close();
|
|
147
|
+
this.#abortController.abort();
|
|
111
148
|
this.#eventsWs?.close();
|
|
112
149
|
}
|
|
150
|
+
/** Opens a new connection; resolves once it is established and rejects if it fails before that. */
|
|
151
|
+
async #connect(eventsWsUrl) {
|
|
152
|
+
await new Promise((resolve, reject) => {
|
|
153
|
+
// `ws` has no default handshake timeout, so without it a silent server would block `init()` forever.
|
|
154
|
+
const ws = new WebSocket(eventsWsUrl, { handshakeTimeout: 10_000 });
|
|
155
|
+
this.#eventsWs = ws;
|
|
156
|
+
let openedAt;
|
|
157
|
+
let lastError;
|
|
158
|
+
ws.on('open', () => {
|
|
159
|
+
openedAt = Date.now();
|
|
160
|
+
resolve();
|
|
161
|
+
});
|
|
162
|
+
ws.on('message', (message) => this.#handleMessage(message));
|
|
163
|
+
ws.on('error', (err) => {
|
|
164
|
+
// Before the connection is open, the error is reported through the `close` event.
|
|
165
|
+
lastError = err;
|
|
166
|
+
if (openedAt !== undefined)
|
|
167
|
+
this.log.exception(err, 'Platform events websocket error');
|
|
168
|
+
});
|
|
169
|
+
ws.on('close', (code, reason) => {
|
|
170
|
+
if (this.#eventsWs === ws)
|
|
171
|
+
this.#eventsWs = undefined;
|
|
172
|
+
if (openedAt === undefined) {
|
|
173
|
+
reject(lastError ??
|
|
174
|
+
new Error(`Web socket closed before the connection was established (code=${code})`));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.#handleClose(eventsWsUrl, { code, reason: reason.toString(), openedAt });
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
#handleMessage(message) {
|
|
182
|
+
if (!message)
|
|
183
|
+
return;
|
|
184
|
+
try {
|
|
185
|
+
const { name, data } = JSON.parse(String(message));
|
|
186
|
+
this.emit(name, data);
|
|
187
|
+
if (name === ACTOR_EVENT_NAMES.MIGRATING) {
|
|
188
|
+
betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
|
|
189
|
+
this.events.emit(EventType.PERSIST_STATE, {
|
|
190
|
+
isMigrating: true,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
this.log.exception(err, 'Cannot parse Actor event');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Logs the close of an established connection and schedules a reconnection, unless the close is final. */
|
|
199
|
+
#handleClose(eventsWsUrl, { code, reason, openedAt }) {
|
|
200
|
+
if (this.#abortController.signal.aborted) {
|
|
201
|
+
this.log.debug('web socket has been closed');
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const details = `code=${code}, reason=${JSON.stringify(reason)}`;
|
|
205
|
+
if (NON_RETRYABLE_CLOSE_CODES.has(code)) {
|
|
206
|
+
this.log.error(`Connection to platform events websocket was closed with a non-retryable code (${details}); not reconnecting. ` +
|
|
207
|
+
'No further platform events will be received for the rest of this run, so migration and abort handling ' +
|
|
208
|
+
'(e.g. persisting state before a migration) is now disabled.');
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (CLEAN_CLOSE_CODES.has(code)) {
|
|
212
|
+
this.log.info(`Connection to platform events websocket was closed (${details}), reconnecting...`);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
this.log.warning(`Connection to platform events websocket was lost (${details}), reconnecting...`);
|
|
216
|
+
}
|
|
217
|
+
// Reconnect a healthy connection immediately; back off only on repeated rapid drops. The first rapid drop
|
|
218
|
+
// retries without delay (it just primes the backoff), each consecutive one waits for the next interval.
|
|
219
|
+
let delay = 0;
|
|
220
|
+
if (Date.now() - openedAt >= HEALTHY_CONNECTION_MIN_DURATION_MILLIS) {
|
|
221
|
+
this.#backoff = undefined;
|
|
222
|
+
}
|
|
223
|
+
else if (this.#backoff) {
|
|
224
|
+
delay = this.#backoff.next().value;
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
this.#backoff = backoffDelays();
|
|
228
|
+
}
|
|
229
|
+
this.#reconnect(eventsWsUrl, delay).catch((err) => {
|
|
230
|
+
this.log.exception(err, 'Reconnecting to platform events websocket failed');
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
/** Keeps trying to connect, with backoff between failed attempts, until it succeeds or `close()` is called. */
|
|
234
|
+
async #reconnect(eventsWsUrl, initialDelayMillis) {
|
|
235
|
+
const { signal } = this.#abortController;
|
|
236
|
+
await this.#sleep(initialDelayMillis, signal);
|
|
237
|
+
while (!signal.aborted) {
|
|
238
|
+
try {
|
|
239
|
+
await this.#connect(eventsWsUrl);
|
|
240
|
+
this.log.info('Reconnected to the platform events websocket.');
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
if (signal.aborted)
|
|
245
|
+
return;
|
|
246
|
+
this.log.warning(`Reconnecting to platform events websocket failed: ${err.message}`);
|
|
247
|
+
}
|
|
248
|
+
this.#backoff ??= backoffDelays();
|
|
249
|
+
await this.#sleep(this.#backoff.next().value, signal);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** Sleeps for the given time, or until the signal is aborted. */
|
|
253
|
+
async #sleep(millis, signal) {
|
|
254
|
+
if (millis <= 0 || signal.aborted)
|
|
255
|
+
return;
|
|
256
|
+
// Rejects with an `AbortError` when aborted, which just means there is nothing left to wait for.
|
|
257
|
+
await sleep(millis, undefined, { signal }).catch(() => { });
|
|
258
|
+
}
|
|
113
259
|
}
|