apify 4.0.0-rc.0 → 4.0.0-rc.2

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.
@@ -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
+ }
@@ -28,6 +28,15 @@ export declare const apifyConfigFields: {
28
28
  actorId: ConfigField<z.ZodOptional<z.ZodString>>;
29
29
  actorRunId: ConfigField<z.ZodOptional<z.ZodString>>;
30
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>>>;
31
40
  apiBaseUrl: ConfigField<z.ZodDefault<z.ZodString>>;
32
41
  apiPublicBaseUrl: ConfigField<z.ZodDefault<z.ZodString>>;
33
42
  containerPort: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber, unknown>>>;
@@ -41,14 +50,13 @@ export declare const apifyConfigFields: {
41
50
  standbyUrl: ConfigField<z.ZodOptional<z.ZodString>>;
42
51
  isAtHome: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
43
52
  userId: ConfigField<z.ZodOptional<z.ZodString>>;
44
- userIsPaying: ConfigField<z.ZodOptional<z.ZodString>>;
53
+ userIsPaying: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
45
54
  actorPermissionLevel: ConfigField<z.ZodOptional<z.ZodString>>;
46
55
  inputSecretsPrivateKeyPassphrase: ConfigField<z.ZodOptional<z.ZodString>>;
47
56
  inputSecretsPrivateKeyFile: ConfigField<z.ZodOptional<z.ZodString>>;
48
57
  maxTotalChargeUsd: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodPreprocess<z.ZodNumber, unknown>, z.ZodTransform<number, number>>>>;
49
58
  metaOrigin: ConfigField<z.ZodOptional<z.ZodString>>;
50
59
  testPayPerEvent: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
51
- useChargingLogDataset: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
52
60
  actorPricingInfo: ConfigField<z.ZodOptional<z.ZodString>>;
53
61
  chargedEventCounts: ConfigField<z.ZodOptional<z.ZodString>>;
54
62
  actorStoragesJson: ConfigField<z.ZodOptional<z.ZodString>>;
@@ -110,6 +118,15 @@ export interface Configuration extends ApifyResolvedConfigValues {
110
118
  * `actorId` | `ACTOR_ID` | -
111
119
  * `actorRunId` | `ACTOR_RUN_ID` | -
112
120
  * `actorTaskId` | `ACTOR_TASK_ID` | -
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` | -
113
130
  * `apiBaseUrl` | `APIFY_API_BASE_URL` | `'https://api.apify.com/'`
114
131
  * `containerPort` | `ACTOR_WEB_SERVER_PORT` | `4321`
115
132
  * `containerUrl` | `ACTOR_WEB_SERVER_URL` | `'http://localhost:4321'`
@@ -121,6 +138,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
121
138
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
122
139
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
123
140
  * `userId` | `APIFY_USER_ID` | -
141
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
124
142
  * `xvfb` | `APIFY_XVFB` | -
125
143
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
126
144
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
@@ -8,6 +8,22 @@ import { ACTOR_ENV_VARS, APIFY_ENV_VARS, LOCAL_ACTOR_ENV_VARS, LOCAL_APIFY_ENV_V
8
8
  // Reads the env var, not the resolved `isAtHome` field, so an explicit
9
9
  // `new Configuration({ isAtHome: true })` won't flip these — env is the source.
10
10
  const isAtHome = () => !!process.env[APIFY_ENV_VARS.IS_AT_HOME];
11
+ // Zod preprocessors for the Apify-specific field types; crawlee's
12
+ // `coerceBoolean` / `coerceNumber` cover the rest.
13
+ const coerceDate = z.preprocess((val) => {
14
+ if (typeof val === 'string')
15
+ return new Date(Date.parse(val));
16
+ return val;
17
+ }, z.date());
18
+ const coerceStringList = z.preprocess((val) => {
19
+ if (typeof val === 'string') {
20
+ return val
21
+ .split(',')
22
+ .map((item) => item.trim())
23
+ .filter(Boolean);
24
+ }
25
+ return val;
26
+ }, z.array(z.string()));
11
27
  function withApifyEnv(base, apifyEnvVars, schema) {
12
28
  const crawleeVars = base.envVar == null ? [] : [base.envVar].flat();
13
29
  return field((schema ?? base.schema), [...[apifyEnvVars].flat(), ...crawleeVars]);
@@ -66,6 +82,18 @@ export const apifyConfigFields = {
66
82
  actorId: field(z.string().optional(), [ACTOR_ENV_VARS.ID, APIFY_ENV_VARS.ACTOR_ID]),
67
83
  actorRunId: field(z.string().optional(), [ACTOR_ENV_VARS.RUN_ID, APIFY_ENV_VARS.ACTOR_RUN_ID]),
68
84
  actorTaskId: field(z.string().optional(), [ACTOR_ENV_VARS.TASK_ID, APIFY_ENV_VARS.ACTOR_TASK_ID]),
85
+ actorBuildId: field(z.string().optional(), [ACTOR_ENV_VARS.BUILD_ID, APIFY_ENV_VARS.ACTOR_BUILD_ID]),
86
+ actorBuildNumber: field(z.string().optional(), [ACTOR_ENV_VARS.BUILD_NUMBER, APIFY_ENV_VARS.ACTOR_BUILD_NUMBER]),
87
+ actorBuildTags: field(coerceStringList.optional(), ACTOR_ENV_VARS.BUILD_TAGS),
88
+ actorFullName: field(z.string().optional(), ACTOR_ENV_VARS.FULL_NAME),
89
+ workflowKey: field(z.string().optional(), APIFY_ENV_VARS.WORKFLOW_KEY),
90
+ startedAt: field(coerceDate.optional(), [ACTOR_ENV_VARS.STARTED_AT, APIFY_ENV_VARS.STARTED_AT]),
91
+ timeoutAt: field(coerceDate.optional(), [ACTOR_ENV_VARS.TIMEOUT_AT, APIFY_ENV_VARS.TIMEOUT_AT]),
92
+ maxPaidDatasetItems: field(coerceNumber.optional(), [
93
+ ACTOR_ENV_VARS.MAX_PAID_DATASET_ITEMS,
94
+ APIFY_ENV_VARS.ACTOR_MAX_PAID_DATASET_ITEMS,
95
+ ]),
96
+ dedicatedCpus: field(coerceNumber.optional(), APIFY_ENV_VARS.DEDICATED_CPUS),
69
97
  apiBaseUrl: field(z.string().default('https://api.apify.com/'), APIFY_ENV_VARS.API_BASE_URL),
70
98
  apiPublicBaseUrl: field(z.string().default('https://api.apify.com'), APIFY_ENV_VARS.API_PUBLIC_BASE_URL),
71
99
  containerPort: field(coerceNumber.default(+LOCAL_ACTOR_ENV_VARS[ACTOR_ENV_VARS.WEB_SERVER_PORT]), [
@@ -85,7 +113,7 @@ export const apifyConfigFields = {
85
113
  standbyUrl: field(z.string().optional(), ACTOR_ENV_VARS.STANDBY_URL),
86
114
  isAtHome: field(coerceBoolean.default(false), APIFY_ENV_VARS.IS_AT_HOME),
87
115
  userId: field(z.string().optional(), APIFY_ENV_VARS.USER_ID),
88
- userIsPaying: field(z.string().optional(), APIFY_ENV_VARS.USER_IS_PAYING),
116
+ userIsPaying: field(coerceBoolean.default(false), APIFY_ENV_VARS.USER_IS_PAYING),
89
117
  actorPermissionLevel: field(z.string().optional(), ACTOR_ENV_VARS.PERMISSION_LEVEL),
90
118
  inputSecretsPrivateKeyPassphrase: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_PASSPHRASE),
91
119
  inputSecretsPrivateKeyFile: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_FILE),
@@ -93,7 +121,6 @@ export const apifyConfigFields = {
93
121
  maxTotalChargeUsd: field(coerceNumber.transform((val) => (val === 0 ? Infinity : val)).default(Infinity), ACTOR_ENV_VARS.MAX_TOTAL_CHARGE_USD),
94
122
  metaOrigin: field(z.string().optional(), APIFY_ENV_VARS.META_ORIGIN),
95
123
  testPayPerEvent: field(coerceBoolean.default(false), 'ACTOR_TEST_PAY_PER_EVENT'),
96
- useChargingLogDataset: field(coerceBoolean.default(false), 'ACTOR_USE_CHARGING_LOG_DATASET'),
97
124
  // Pay-per-event charging metadata injected by the platform (JSON strings).
98
125
  actorPricingInfo: field(z.string().optional(), 'APIFY_ACTOR_PRICING_INFO'),
99
126
  chargedEventCounts: field(z.string().optional(), 'APIFY_CHARGED_ACTOR_EVENT_COUNTS'),
@@ -153,6 +180,15 @@ export const apifyConfigFields = {
153
180
  * `actorId` | `ACTOR_ID` | -
154
181
  * `actorRunId` | `ACTOR_RUN_ID` | -
155
182
  * `actorTaskId` | `ACTOR_TASK_ID` | -
183
+ * `actorBuildId` | `ACTOR_BUILD_ID` | -
184
+ * `actorBuildNumber` | `ACTOR_BUILD_NUMBER` | -
185
+ * `actorBuildTags` | `ACTOR_BUILD_TAGS` | -
186
+ * `actorFullName` | `ACTOR_FULL_NAME` | -
187
+ * `workflowKey` | `APIFY_WORKFLOW_KEY` | -
188
+ * `startedAt` | `ACTOR_STARTED_AT` | -
189
+ * `timeoutAt` | `ACTOR_TIMEOUT_AT` | -
190
+ * `maxPaidDatasetItems` | `ACTOR_MAX_PAID_DATASET_ITEMS` | -
191
+ * `dedicatedCpus` | `APIFY_DEDICATED_CPUS` | -
156
192
  * `apiBaseUrl` | `APIFY_API_BASE_URL` | `'https://api.apify.com/'`
157
193
  * `containerPort` | `ACTOR_WEB_SERVER_PORT` | `4321`
158
194
  * `containerUrl` | `ACTOR_WEB_SERVER_URL` | `'http://localhost:4321'`
@@ -164,6 +200,7 @@ export const apifyConfigFields = {
164
200
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
165
201
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
166
202
  * `userId` | `APIFY_USER_ID` | -
203
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
167
204
  * `xvfb` | `APIFY_XVFB` | -
168
205
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
169
206
  * `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 in the working directory either. */
3
+ /** No input record in the default key-value store, and locally no input file either. */
4
4
  'NOT_FOUND'
5
- /** Both `<inputKey>` and `<inputKey>.json` exist in the working directory, so neither is picked. */
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,5 @@ 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 { ACTOR_ENV_VARS, APIFY_ENV_VARS } from '@apify/consts';
16
+ 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,5 @@ 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 { ACTOR_ENV_VARS, APIFY_ENV_VARS } from '@apify/consts';
13
+ 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
  /**
@@ -9,16 +10,16 @@ import { Configuration } from './configuration.js';
9
10
  * **Example usage:**
10
11
  *
11
12
  * ```javascript
12
- * Actor.on('cpuInfo', (data) => {
13
+ * Actor.on('systemInfo', (data) => {
13
14
  * if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');
14
15
  * });
15
16
  * ```
16
17
  *
17
18
  * The following events are emitted:
18
19
  *
19
- * - `cpuInfo`: `{ "isCpuOverloaded": Boolean }`
20
- * The event is emitted approximately every second
21
- * and it indicates whether the Actor is using the maximum of available CPU resources.
20
+ * - `systemInfo`: `{ "cpuCurrentUsage": Number, "isCpuOverloaded": Boolean, "memCurrentBytes": Number, ... }`
21
+ * The event is emitted approximately every second and it describes the CPU and memory usage of the Actor.
22
+ * `isCpuOverloaded` indicates whether the Actor is using the maximum of available CPU resources.
22
23
  * If that's the case, the Actor should not add more workload.
23
24
  * For example, this event is used by the {@link AutoscaledPool} class.
24
25
  * - `migrating`: `void`
@@ -37,17 +38,32 @@ 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
+ * Messages with any other name are not emitted. This includes the deprecated `cpuInfo` event, which the platform
43
+ * sends next to `systemInfo` for backward compatibility. Registering a `cpuInfo` listener logs a warning.
44
+ * Unknown names are logged at the debug level.
45
+ *
46
+ * The connection to the platform events websocket is re-established after it drops, unless it was closed
47
+ * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
40
48
  */
41
49
  export declare class PlatformEventManager extends EventManager {
42
50
  #private;
43
51
  readonly configuration: Configuration;
44
- constructor(configuration?: Configuration);
52
+ /**
53
+ * @param internalListeners Listeners of the SDK itself, kept apart from the ones registered with `on()`, so that
54
+ * user code can neither remove them with `off()` nor see them in `listeners()`.
55
+ */
56
+ constructor(configuration?: Configuration, internalListeners?: Partial<Record<EventTypeName, (...args: any[]) => unknown>>);
57
+ on(event: EventTypeName, listener: (...args: any[]) => any): void;
58
+ emit(event: EventTypeName, ...args: unknown[]): void;
59
+ waitForAllListenersToComplete(): Promise<boolean>;
45
60
  /**
46
61
  * Initializes `Actor.events` event emitter by creating a connection to a websocket that provides them.
47
62
  * This is an internal function that is automatically called by `Actor.main()`.
63
+ *
64
+ * Rejects if the first connection cannot be established. Later drops are handled by reconnecting.
48
65
  */
49
66
  init(): Promise<void>;
50
- private createWebSocketConnection;
51
67
  /**
52
68
  * Closes websocket providing events from Actor infrastructure and also stops sending internal events
53
69
  * of Apify package such as `persistState`.