apify 4.0.0-beta.141 → 4.0.0-beta.143

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.js CHANGED
@@ -335,6 +335,8 @@ export class Actor {
335
335
  if (this.#gracefulShutdownHandlers.migrating) {
336
336
  this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
337
337
  }
338
+ // Writes the charged event counts one last time, so that a resurrected run continues from them.
339
+ await this.#chargingManager.teardown();
338
340
  // Close the event manager and emit the final PERSIST_STATE event
339
341
  await events.close();
340
342
  log.debug(`Events closed`);
@@ -1,5 +1,7 @@
1
1
  import type { ActorResource, ActorRunPricingInfo, ApifyClient, Run as ClientActorRun } from 'apify-client';
2
2
  import type { Configuration } from './configuration.js';
3
+ /** Key of the default key-value store record that carries the charged event counts across a container restart. */
4
+ export declare const CHARGING_STATE_KEY = "APIFY_ACTOR_CHARGING_STATE";
3
5
  export declare const DEFAULT_DATASET_ITEM_EVENT = "apify-default-dataset-item";
4
6
  export interface ChargeOptions {
5
7
  /**
@@ -77,6 +79,12 @@ export declare class ChargingManager {
77
79
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
78
80
  */
79
81
  init(): Promise<void>;
82
+ /**
83
+ * Persist the charged event counts one last time and stop listening for the persist state events.
84
+ *
85
+ * @internal
86
+ */
87
+ teardown(): Promise<void>;
80
88
  /**
81
89
  * Whether {@link ChargingManager.init} has run. All charging operations (including
82
90
  * {@link ChargingManager.getPricingInfo}) require an initialized manager.
package/dist/charging.js CHANGED
@@ -1,7 +1,13 @@
1
- import { Dataset, withDirectStorageAccess } from '@crawlee/core';
1
+ import { Dataset, RecoverableState, withDirectStorageAccess } from '@crawlee/core';
2
+ import { z } from 'zod';
2
3
  import { META_ORIGINS } from '@apify/consts';
3
4
  import log from '@apify/log';
4
5
  import { ReentrantAsyncLock } from './utils.js';
6
+ /** Key of the default key-value store record that carries the charged event counts across a container restart. */
7
+ export const CHARGING_STATE_KEY = 'APIFY_ACTOR_CHARGING_STATE';
8
+ const chargingStateSchema = z.object({
9
+ chargedEventCounts: z.record(z.string(), z.number().int().nonnegative()),
10
+ });
5
11
  /** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
6
12
  const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
7
13
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
@@ -32,6 +38,7 @@ export class ChargingManager {
32
38
  #purgeChargingLogDataset;
33
39
  #notPpeWarningPrinted = false;
34
40
  #pricingInfo = {};
41
+ /** The charged event counts, persisted to the default key-value store in a pay-per-event run on the platform. */
35
42
  #chargingState;
36
43
  #chargingLogDataset;
37
44
  /** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
@@ -134,12 +141,20 @@ export class ChargingManager {
134
141
  }
135
142
  this.#maxTotalChargeUsd = maxTotalChargeUsd;
136
143
  }
137
- this.#chargingState = {};
144
+ // The platform fills the env var with the counts recorded when the run started, so after a reboot, migration
145
+ // or restart they miss what an earlier container charged. On the platform the counts are therefore also kept
146
+ // in the default key-value store, and the persisted ones take over where they are higher. A multi-tenant run
147
+ // has no counts of its own to keep.
148
+ this.#chargingState = new RecoverableState({
149
+ defaultState: { chargedEventCounts: {} },
150
+ persistStateKey: CHARGING_STATE_KEY,
151
+ persistenceEnabled: this.#isAtHome && this.isPayPerEvent && !this.#isMultiTenant,
152
+ deserialize: chargingStateSchema,
153
+ configuration: this.#configuration,
154
+ });
155
+ await this.#chargingState.initialize();
138
156
  for (const [eventName, chargeCount] of Object.entries(chargedEventCounts ?? {})) {
139
- this.#chargingState[eventName] = {
140
- chargeCount,
141
- totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
142
- };
157
+ this.#chargedEventCounts[eventName] = Math.max(this.#chargedEventCounts[eventName] ?? 0, chargeCount);
143
158
  }
144
159
  if (this.#isAtHome || !this.isPayPerEvent) {
145
160
  return;
@@ -151,6 +166,14 @@ export class ChargingManager {
151
166
  }
152
167
  this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
153
168
  }
169
+ /**
170
+ * Persist the charged event counts one last time and stop listening for the persist state events.
171
+ *
172
+ * @internal
173
+ */
174
+ async teardown() {
175
+ await this.#chargingState?.teardown();
176
+ }
154
177
  /**
155
178
  * Whether {@link ChargingManager.init} has run. All charging operations (including
156
179
  * {@link ChargingManager.getPricingInfo}) require an initialized manager.
@@ -158,6 +181,12 @@ export class ChargingManager {
158
181
  get isInitialized() {
159
182
  return this.#chargingState !== undefined;
160
183
  }
184
+ get #chargedEventCounts() {
185
+ if (this.#chargingState === undefined) {
186
+ throw new Error('ChargingManager is not initialized');
187
+ }
188
+ return this.#chargingState.currentValue.chargedEventCounts;
189
+ }
161
190
  /**
162
191
  * Get information about the pricing for this Actor.
163
192
  */
@@ -219,8 +248,7 @@ export class ChargingManager {
219
248
  chargeableWithinLimit: this.calculateChargeableWithinLimit(),
220
249
  };
221
250
  }
222
- const chargingState = this.#chargingState;
223
- if (chargingState === undefined) {
251
+ if (this.#chargingState === undefined) {
224
252
  throw new Error('ChargingManager is not initialized');
225
253
  }
226
254
  return await this.withChargeLock(async () => {
@@ -286,12 +314,7 @@ export class ChargingManager {
286
314
  }
287
315
  // Count the charge only after the API call succeeds, so a failed call retried under the same key
288
316
  // is counted once.
289
- chargingState[eventName] ??= {
290
- chargeCount: 0,
291
- totalChargedAmount: 0,
292
- };
293
- chargingState[eventName].chargeCount += chargedCount;
294
- chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
317
+ this.#chargedEventCounts[eventName] = (this.#chargedEventCounts[eventName] ?? 0) + chargedCount;
295
318
  // Remember the key for every charge that was counted, including events the API never receives,
296
319
  // such as synthetic ones - those are counted locally and a repeat would count them twice.
297
320
  if (idempotencyKey !== undefined) {
@@ -376,7 +399,7 @@ export class ChargingManager {
376
399
  if (this.#chargingState === undefined) {
377
400
  throw new Error('ChargingManager is not initialized');
378
401
  }
379
- return this.#chargingState[eventName]?.chargeCount ?? 0;
402
+ return this.#chargedEventCounts[eventName] ?? 0;
380
403
  }
381
404
  /**
382
405
  * Get the maximum amount of money that the Actor is allowed to charge.
@@ -391,8 +414,8 @@ export class ChargingManager {
391
414
  if (this.#chargingState === undefined) {
392
415
  throw new Error('ChargingManager is not initialized');
393
416
  }
394
- const result = Object.values(this.#chargingState)
395
- .map(({ totalChargedAmount }) => totalChargedAmount)
417
+ const result = Object.entries(this.#chargedEventCounts)
418
+ .map(([eventName, count]) => count * (this.calculateEventPrice(eventName) ?? 0))
396
419
  .reduce((sum, inc) => sum + inc, 0);
397
420
  // Keeping float precision issues at bay
398
421
  return Number(result.toFixed(6));
@@ -412,7 +435,8 @@ export class ChargingManager {
412
435
  return this.calculateMaxChargesByPrice(price);
413
436
  }
414
437
  calculateEventPrice(eventName) {
415
- return this.#isAtHome ? this.#pricingInfo[eventName]?.price : 1; // Use a nonzero price for local development so that the maximum budget can be reached
438
+ // Unknown events cost $1 in local development so that the maximum budget can be reached.
439
+ return this.#pricingInfo[eventName]?.price ?? (this.#isAtHome ? undefined : 1);
416
440
  }
417
441
  calculateMaxChargesByPrice(price) {
418
442
  // The raw number of events allowed by the budget
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.141",
3
+ "version": "4.0.0-beta.143",
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"
@@ -61,10 +61,10 @@
61
61
  "@apify/timeout": "^1.1.0",
62
62
  "@apify/utilities": "^3.1.1",
63
63
  "@apify/validations": "^1.1.4",
64
- "@crawlee/core": "4.0.0-rc.3",
65
- "@crawlee/fs-storage": "4.0.0-rc.3",
66
- "@crawlee/types": "4.0.0-rc.3",
67
- "@crawlee/utils": "4.0.0-rc.3",
64
+ "@crawlee/core": "4.0.0-beta.340",
65
+ "@crawlee/fs-storage": "4.0.0-beta.340",
66
+ "@crawlee/types": "4.0.0-beta.340",
67
+ "@crawlee/utils": "4.0.0-beta.340",
68
68
  "apify-client": "^3.0.0-rc.2",
69
69
  "minimatch": "^11.0.9",
70
70
  "tslib": "^2.9.1",
@@ -79,7 +79,7 @@
79
79
  "@types/node": "^26.6.6",
80
80
  "@types/ws": "^8.18.2",
81
81
  "commitlint": "^21.2.4",
82
- "crawlee": "4.0.0-rc.3",
82
+ "crawlee": "4.0.0-beta.340",
83
83
  "husky": "^9.1.7",
84
84
  "lint-staged": "^17.6.1",
85
85
  "oxfmt": "0.80.0",