apify 4.0.0-beta.131 → 4.0.0-beta.133

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 CHANGED
@@ -456,7 +456,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
456
456
  *
457
457
  * A run started with a custom `token` uses that token, except for a run started before a migration or
458
458
  * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
459
- * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
459
+ * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
460
460
  */
461
461
  get childRuns(): Record<string, RunClient>;
462
462
  /**
@@ -841,7 +841,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
841
841
  *
842
842
  * Values can be modified by simply using the assignment operator.
843
843
  *
844
- * @param name The name of the store to use.
844
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
845
845
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
846
846
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
847
847
  */
@@ -851,7 +851,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
851
851
  *
852
852
  * Values can be modified by simply using the assignment operator.
853
853
  *
854
- * @param name The name of the store to use.
854
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
855
855
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
856
856
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
857
857
  */
@@ -1062,7 +1062,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1062
1062
  *
1063
1063
  * A run started with a custom `token` uses that token, except for a run started before a migration or
1064
1064
  * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1065
- * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1065
+ * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
1066
1066
  */
1067
1067
  static get childRuns(): Record<string, RunClient>;
1068
1068
  /**
package/dist/actor.js CHANGED
@@ -596,7 +596,7 @@ export class Actor {
596
596
  *
597
597
  * A run started with a custom `token` uses that token, except for a run started before a migration or
598
598
  * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
599
- * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
599
+ * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
600
600
  */
601
601
  get childRuns() {
602
602
  this.ensureActorInit('childRuns');
@@ -1266,7 +1266,7 @@ export class Actor {
1266
1266
  *
1267
1267
  * Values can be modified by simply using the assignment operator.
1268
1268
  *
1269
- * @param name The name of the store to use.
1269
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
1270
1270
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
1271
1271
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
1272
1272
  */
@@ -1282,7 +1282,7 @@ export class Actor {
1282
1282
  *
1283
1283
  * Values can be modified by simply using the assignment operator.
1284
1284
  *
1285
- * @param name The name of the store to use.
1285
+ * @param name The key of the record that holds the state. Defaults to `APIFY_GLOBAL_STATE`.
1286
1286
  * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
1287
1287
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
1288
1288
  */
@@ -1515,7 +1515,7 @@ export class Actor {
1515
1515
  *
1516
1516
  * A run started with a custom `token` uses that token, except for a run started before a migration or
1517
1517
  * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1518
- * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1518
+ * under the same name, are stored in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key.
1519
1519
  */
1520
1520
  static get childRuns() {
1521
1521
  return Actor.getDefaultInstance().childRuns;
@@ -9,7 +9,7 @@ import { ApifyRequestQueueSingleBackend } from './apify_request_queue_single_bac
9
9
  /** The reserved alias crawlee uses for the default (unnamed) storage. */
10
10
  export const DEFAULT_STORAGE_ALIAS = '__default__';
11
11
  /** The key of the default key-value store record holding this run's alias -> storage id mapping. */
12
- const ALIAS_MAPPING_RECORD_KEY = '__STORAGE_ALIASES_MAPPING';
12
+ const ALIAS_MAPPING_RECORD_KEY = 'APIFY_STORAGE_ALIASES_MAPPING';
13
13
  async function readAliasMapping(store) {
14
14
  const record = await store.getRecord(ALIAS_MAPPING_RECORD_KEY);
15
15
  return record?.value ?? {};
@@ -77,7 +77,6 @@ export declare class ChargingManager {
77
77
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
78
78
  */
79
79
  init(): Promise<void>;
80
- private ensureChargingLogDatasetOnPlatform;
81
80
  /**
82
81
  * Whether {@link ChargingManager.init} has run. All charging operations (including
83
82
  * {@link ChargingManager.getPricingInfo}) require an initialized manager.
package/dist/charging.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Dataset, KeyValueStore } from '@crawlee/core';
1
+ import { Dataset, withDirectStorageAccess } from '@crawlee/core';
2
2
  import { META_ORIGINS } from '@apify/consts';
3
3
  import log from '@apify/log';
4
4
  import { ReentrantAsyncLock } from './utils.js';
@@ -22,8 +22,7 @@ function getEffectivePricingInfo(pricingInfos, now = new Date()) {
22
22
  * Handles pay-per-event charging.
23
23
  */
24
24
  export class ChargingManager {
25
- #LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log';
26
- #PLATFORM_CHARGING_LOG_DATASET_ID_KEY = 'CHARGING_LOG_DATASET_ID';
25
+ #LOCAL_CHARGING_LOG_DATASET_NAME = 'charging-log';
27
26
  #maxTotalChargeUsd;
28
27
  #isAtHome;
29
28
  #actorRunId;
@@ -31,7 +30,6 @@ export class ChargingManager {
31
30
  /** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
32
31
  #isMultiTenant = false;
33
32
  #purgeChargingLogDataset;
34
- #useChargingLogDataset;
35
33
  #notPpeWarningPrinted = false;
36
34
  #pricingInfo = {};
37
35
  #chargingState;
@@ -49,7 +47,6 @@ export class ChargingManager {
49
47
  this.#isAtHome = configuration.isAtHome;
50
48
  this.#actorRunId = configuration.actorRunId;
51
49
  this.#purgeChargingLogDataset = configuration.purgeOnStart;
52
- this.#useChargingLogDataset = configuration.useChargingLogDataset;
53
50
  this.#apifyClient = apifyClient;
54
51
  this.#getCurrentRun = getCurrentRun;
55
52
  this.#getCurrentActor = getCurrentActor;
@@ -114,9 +111,6 @@ export class ChargingManager {
114
111
  */
115
112
  async init() {
116
113
  // Validate config - it may have changed since the instantiation
117
- if (this.#useChargingLogDataset && this.#isAtHome) {
118
- throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
119
- }
120
114
  if (this.#configuration.testPayPerEvent) {
121
115
  if (this.#isAtHome) {
122
116
  throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
@@ -147,31 +141,15 @@ export class ChargingManager {
147
141
  totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
148
142
  };
149
143
  }
150
- if (!this.isPayPerEvent || !this.#useChargingLogDataset) {
144
+ if (this.#isAtHome || !this.isPayPerEvent) {
151
145
  return;
152
146
  }
153
- // Set up charging log dataset
154
- if (this.#isAtHome) {
155
- const datasetId = await this.ensureChargingLogDatasetOnPlatform();
156
- this.#chargingLogDataset = await Dataset.open(datasetId);
157
- }
158
- else {
159
- if (this.#purgeChargingLogDataset) {
160
- const dataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
161
- await dataset.drop();
162
- }
163
- this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
147
+ // Local pay-per-event runs log every charge into a dataset for debugging.
148
+ if (this.#purgeChargingLogDataset) {
149
+ const dataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
150
+ await dataset.drop();
164
151
  }
165
- }
166
- async ensureChargingLogDatasetOnPlatform() {
167
- const defaultStore = await KeyValueStore.open();
168
- const storedDatasetId = await defaultStore.getValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY);
169
- if (storedDatasetId !== null) {
170
- return storedDatasetId;
171
- }
172
- const dataset = await this.#apifyClient.datasets().getOrCreate();
173
- await defaultStore.setValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY, dataset.id);
174
- return dataset.id;
152
+ this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
175
153
  }
176
154
  /**
177
155
  * Whether {@link ChargingManager.init} has run. All charging operations (including
@@ -319,8 +297,10 @@ export class ChargingManager {
319
297
  if (idempotencyKey !== undefined) {
320
298
  this.setIdempotentCharge(idempotencyKey, { eventName, chargedCount });
321
299
  }
322
- if (this.#chargingLogDataset !== undefined) {
323
- await this.#chargingLogDataset.pushData({
300
+ // The charge is not rolled back with a storage transaction, so neither is its log entry.
301
+ const chargingLogDataset = this.#chargingLogDataset;
302
+ if (chargingLogDataset !== undefined) {
303
+ await withDirectStorageAccess(async () => chargingLogDataset.pushData({
324
304
  eventName,
325
305
  eventTitle: pricingInfo.title,
326
306
  eventPriceUsd: pricingInfo.price,
@@ -328,7 +308,7 @@ export class ChargingManager {
328
308
  idempotencyKey,
329
309
  requestId,
330
310
  timestamp: new Date().toISOString(),
331
- });
311
+ }));
332
312
  }
333
313
  if (chargedCount < count) {
334
314
  const subject = count === 1 ? 'instance' : 'instances';
@@ -26,7 +26,7 @@ const toInfo = (run) => ({
26
26
  status: run.status,
27
27
  startedAt: run.startedAt.toISOString(),
28
28
  });
29
- const CHILD_RUNS_KVS_KEY = '__ACTOR_CHILD_RUNS';
29
+ const CHILD_RUNS_KVS_KEY = 'APIFY_ACTOR_CHILD_RUNS';
30
30
  const childRunInfoSchema = z.object({ runId: z.string(), status: z.string(), startedAt: z.string() });
31
31
  const trackedRunsSchema = z.record(z.string(), childRunInfoSchema.extend({
32
32
  checksum: z.string(),
@@ -57,7 +57,6 @@ export declare const apifyConfigFields: {
57
57
  maxTotalChargeUsd: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodPreprocess<z.ZodNumber, unknown>, z.ZodTransform<number, number>>>>;
58
58
  metaOrigin: ConfigField<z.ZodOptional<z.ZodString>>;
59
59
  testPayPerEvent: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
60
- useChargingLogDataset: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
61
60
  actorPricingInfo: ConfigField<z.ZodOptional<z.ZodString>>;
62
61
  chargedEventCounts: ConfigField<z.ZodOptional<z.ZodString>>;
63
62
  actorStoragesJson: ConfigField<z.ZodOptional<z.ZodString>>;
@@ -121,7 +121,6 @@ export const apifyConfigFields = {
121
121
  maxTotalChargeUsd: field(coerceNumber.transform((val) => (val === 0 ? Infinity : val)).default(Infinity), ACTOR_ENV_VARS.MAX_TOTAL_CHARGE_USD),
122
122
  metaOrigin: field(z.string().optional(), APIFY_ENV_VARS.META_ORIGIN),
123
123
  testPayPerEvent: field(coerceBoolean.default(false), 'ACTOR_TEST_PAY_PER_EVENT'),
124
- useChargingLogDataset: field(coerceBoolean.default(false), 'ACTOR_USE_CHARGING_LOG_DATASET'),
125
124
  // Pay-per-event charging metadata injected by the platform (JSON strings).
126
125
  actorPricingInfo: field(z.string().optional(), 'APIFY_ACTOR_PRICING_INFO'),
127
126
  chargedEventCounts: field(z.string().optional(), 'APIFY_CHARGED_ACTOR_EVENT_COUNTS'),
@@ -10,16 +10,16 @@ import { Configuration } from './configuration.js';
10
10
  * **Example usage:**
11
11
  *
12
12
  * ```javascript
13
- * Actor.on('cpuInfo', (data) => {
13
+ * Actor.on('systemInfo', (data) => {
14
14
  * if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');
15
15
  * });
16
16
  * ```
17
17
  *
18
18
  * The following events are emitted:
19
19
  *
20
- * - `cpuInfo`: `{ "isCpuOverloaded": Boolean }`
21
- * The event is emitted approximately every second
22
- * 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.
23
23
  * If that's the case, the Actor should not add more workload.
24
24
  * For example, this event is used by the {@link AutoscaledPool} class.
25
25
  * - `migrating`: `void`
@@ -39,6 +39,10 @@ import { Configuration } from './configuration.js';
39
39
  * Note that the `persistState` event is provided merely for user convenience,
40
40
  * you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
41
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
+ *
42
46
  * The connection to the platform events websocket is re-established after it drops, unless it was closed
43
47
  * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
44
48
  */
@@ -50,6 +54,7 @@ export declare class PlatformEventManager extends EventManager {
50
54
  * user code can neither remove them with `off()` nor see them in `listeners()`.
51
55
  */
52
56
  constructor(configuration?: Configuration, internalListeners?: Partial<Record<EventTypeName, (...args: any[]) => unknown>>);
57
+ on(event: EventTypeName, listener: (...args: any[]) => any): void;
53
58
  emit(event: EventTypeName, ...args: unknown[]): void;
54
59
  waitForAllListenersToComplete(): Promise<boolean>;
55
60
  /**
@@ -15,6 +15,13 @@ const NON_RETRYABLE_CLOSE_CODES = new Set([1002, 1003, 1007, 1008, 1010]);
15
15
  const CLEAN_CLOSE_CODES = new Set([1000, 1001]);
16
16
  /** How long a connection must stay open to count as healthy, after which a drop reconnects without backoff. */
17
17
  const HEALTHY_CONNECTION_MIN_DURATION_MILLIS = 1000;
18
+ /** Names of the platform events that are emitted to listeners. Messages with any other name are dropped. */
19
+ const PLATFORM_EVENT_NAMES = new Set([
20
+ ACTOR_EVENT_NAMES.SYSTEM_INFO,
21
+ ACTOR_EVENT_NAMES.MIGRATING,
22
+ ACTOR_EVENT_NAMES.ABORTING,
23
+ ACTOR_EVENT_NAMES.PERSIST_STATE,
24
+ ]);
18
25
  /**
19
26
  * Delays between reconnection attempts, mirroring the Python `websockets` library
20
27
  * (see RFC 6455, section 7.2.3): a random initial delay, then exponential growth up to a cap.
@@ -38,16 +45,16 @@ function* backoffDelays() {
38
45
  * **Example usage:**
39
46
  *
40
47
  * ```javascript
41
- * Actor.on('cpuInfo', (data) => {
48
+ * Actor.on('systemInfo', (data) => {
42
49
  * if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');
43
50
  * });
44
51
  * ```
45
52
  *
46
53
  * The following events are emitted:
47
54
  *
48
- * - `cpuInfo`: `{ "isCpuOverloaded": Boolean }`
49
- * The event is emitted approximately every second
50
- * and it indicates whether the Actor is using the maximum of available CPU resources.
55
+ * - `systemInfo`: `{ "cpuCurrentUsage": Number, "isCpuOverloaded": Boolean, "memCurrentBytes": Number, ... }`
56
+ * The event is emitted approximately every second and it describes the CPU and memory usage of the Actor.
57
+ * `isCpuOverloaded` indicates whether the Actor is using the maximum of available CPU resources.
51
58
  * If that's the case, the Actor should not add more workload.
52
59
  * For example, this event is used by the {@link AutoscaledPool} class.
53
60
  * - `migrating`: `void`
@@ -67,6 +74,10 @@ function* backoffDelays() {
67
74
  * Note that the `persistState` event is provided merely for user convenience,
68
75
  * you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
69
76
  *
77
+ * Messages with any other name are not emitted. This includes the deprecated `cpuInfo` event, which the platform
78
+ * sends next to `systemInfo` for backward compatibility. Registering a `cpuInfo` listener logs a warning.
79
+ * Unknown names are logged at the debug level.
80
+ *
70
81
  * The connection to the platform events websocket is re-established after it drops, unless it was closed
71
82
  * with a code signalling a permanent condition (e.g. `1008` for an unknown run ID).
72
83
  */
@@ -92,6 +103,13 @@ export class PlatformEventManager extends EventManager {
92
103
  this.configuration = configuration;
93
104
  this.#internalListeners = internalListeners;
94
105
  }
106
+ on(event, listener) {
107
+ if (event === ACTOR_EVENT_NAMES.CPU_INFO) {
108
+ this.log.warning('The "cpuInfo" event is deprecated and never emitted. ' +
109
+ 'Listen to "systemInfo" instead, which has the same "isCpuOverloaded" field.');
110
+ }
111
+ super.on(event, listener);
112
+ }
95
113
  emit(event, ...args) {
96
114
  super.emit(event, ...args);
97
115
  const listener = this.#internalListeners[event];
@@ -183,6 +201,12 @@ export class PlatformEventManager extends EventManager {
183
201
  return;
184
202
  try {
185
203
  const { name, data } = JSON.parse(String(message));
204
+ if (name === ACTOR_EVENT_NAMES.CPU_INFO)
205
+ return;
206
+ if (!PLATFORM_EVENT_NAMES.has(name)) {
207
+ this.log.debug('Unknown platform event received', { name, data });
208
+ return;
209
+ }
186
210
  this.emit(name, data);
187
211
  if (name === ACTOR_EVENT_NAMES.MIGRATING) {
188
212
  betterClearInterval(this.intervals.persistState); // Don't send any other persist state event.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.131",
3
+ "version": "4.0.0-beta.133",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"
@@ -83,7 +83,7 @@
83
83
  "husky": "^9.1.7",
84
84
  "lint-staged": "^17.6.1",
85
85
  "oxfmt": "0.80.0",
86
- "oxlint": "1.94.0",
86
+ "oxlint": "1.95.0",
87
87
  "oxlint-tsgolint": "7.0.2008",
88
88
  "playwright": "^1.65.1",
89
89
  "puppeteer": "^25.18.1",