apify 4.0.0-beta.15 → 4.0.0-beta.150

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.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +416 -281
  3. package/dist/actor.js +743 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +88 -0
  11. package/dist/apify_request_queue_backend.js +123 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +201 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +265 -0
  16. package/dist/apify_storage_backend.d.ts +95 -0
  17. package/dist/apify_storage_backend.js +219 -0
  18. package/dist/charging.d.ts +77 -47
  19. package/dist/charging.js +348 -226
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +110 -0
  23. package/dist/child_run_tracker.js +333 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +66 -12
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +32 -21
  38. package/dist/proxy_configuration.js +137 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
package/dist/charging.js CHANGED
@@ -1,62 +1,106 @@
1
- import { Dataset, KeyValueStore } from '@crawlee/core';
1
+ import { Dataset, RecoverableState, withDirectStorageAccess } from '@crawlee/core';
2
+ import { z } from 'zod';
3
+ import { META_ORIGINS } from '@apify/consts';
2
4
  import log from '@apify/log';
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
+ });
11
+ /** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
12
+ const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
3
13
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
4
- export function mergeChargeResults(a, b) {
5
- return {
6
- eventChargeLimitReached: a.eventChargeLimitReached || b.eventChargeLimitReached,
7
- chargedCount: a.chargedCount + b.chargedCount,
8
- chargeableWithinLimit: Object.fromEntries(Object.entries(a.chargeableWithinLimit).map(([key, oldValue]) => [
9
- key,
10
- Math.min(oldValue, b.chargeableWithinLimit[key]),
11
- ])),
12
- };
14
+ /**
15
+ * The pricing history includes scheduled future changes, so the effective entry is the latest one
16
+ * with `startedAt <= now`, not the last one.
17
+ *
18
+ * Resolved once at init on purpose. A change kicking in mid-run only affects local event titles and
19
+ * "unknown event" warnings; the platform prices each charge from its own current pricing anyway.
20
+ */
21
+ function getEffectivePricingInfo(pricingInfos, now = new Date()) {
22
+ return pricingInfos
23
+ .filter((info) => new Date(info.startedAt) <= now)
24
+ .sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime())
25
+ .at(-1);
13
26
  }
14
27
  /**
15
28
  * Handles pay-per-event charging.
16
29
  */
17
30
  export class ChargingManager {
18
- configuration;
19
- LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log';
20
- PLATFORM_CHARGING_LOG_DATASET_ID_KEY = 'CHARGING_LOG_DATASET_ID';
21
- maxTotalChargeUsd;
22
- isAtHome;
23
- actorRunId;
24
- pricingModel;
25
- purgeChargingLogDataset;
26
- useChargingLogDataset;
27
- notPpeWarningPrinted = false;
28
- pricingInfo = {};
29
- chargingState;
30
- chargingLogDataset;
31
- apifyClient;
32
- constructor(configuration, apifyClient) {
33
- this.configuration = configuration;
34
- this.maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
35
- this.isAtHome = configuration.isAtHome;
36
- this.actorRunId = configuration.actorRunId;
37
- this.purgeChargingLogDataset = configuration.purgeOnStart;
38
- this.useChargingLogDataset = configuration.useChargingLogDataset;
39
- this.apifyClient = apifyClient;
31
+ #LOCAL_CHARGING_LOG_DATASET_NAME = 'charging-log';
32
+ #maxTotalChargeUsd;
33
+ #isAtHome;
34
+ #actorRunId;
35
+ #pricingModel;
36
+ /** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
37
+ #isMultiTenant = false;
38
+ #purgeChargingLogDataset;
39
+ #notPpeWarningPrinted = false;
40
+ #pricingInfo = {};
41
+ /** The charged event counts, persisted to the default key-value store in a pay-per-event run on the platform. */
42
+ #chargingState;
43
+ #chargingLogDataset;
44
+ /** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
45
+ #idempotentCharges = new Map();
46
+ #chargeLock = new ReentrantAsyncLock();
47
+ #apifyClient;
48
+ #configuration;
49
+ #getCurrentRun;
50
+ #getCurrentActor;
51
+ constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
52
+ this.#configuration = configuration;
53
+ this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
54
+ this.#isAtHome = configuration.isAtHome;
55
+ this.#actorRunId = configuration.actorRunId;
56
+ this.#purgeChargingLogDataset = configuration.purgeOnStart;
57
+ this.#apifyClient = apifyClient;
58
+ this.#getCurrentRun = getCurrentRun;
59
+ this.#getCurrentActor = getCurrentActor;
40
60
  }
61
+ /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
41
62
  get isPayPerEvent() {
42
- return this.pricingModel === 'PAY_PER_EVENT';
63
+ return this.#pricingModel === 'PAY_PER_EVENT';
64
+ }
65
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
66
+ get isMultiTenant() {
67
+ return this.#isMultiTenant;
43
68
  }
44
69
  async fetchPricingInfo() {
45
- if (this.configuration.actorPricingInfo && this.configuration.chargedEventCounts) {
46
- return {
47
- pricingInfo: JSON.parse(this.configuration.actorPricingInfo),
48
- chargedEventCounts: JSON.parse(this.configuration.chargedEventCounts),
49
- maxTotalChargeUsd: this.configuration.maxTotalChargeUsd || Infinity,
50
- };
70
+ if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
71
+ const pricingInfo = JSON.parse(this.#configuration.actorPricingInfo);
72
+ // Multi-tenant runs get an empty snapshot (`{}`); only the run tells them apart from free Server Actor runs.
73
+ const isMultiTenantCandidate = pricingInfo.pricingModel === undefined &&
74
+ this.#isAtHome &&
75
+ this.#configuration.metaOrigin === META_ORIGINS.STANDBY;
76
+ if (!isMultiTenantCandidate) {
77
+ return {
78
+ pricingInfo,
79
+ chargedEventCounts: JSON.parse(this.#configuration.chargedEventCounts),
80
+ maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
81
+ };
82
+ }
51
83
  }
52
- if (this.isAtHome) {
53
- if (this.actorRunId === undefined) {
84
+ if (this.#isAtHome) {
85
+ if (this.#actorRunId === undefined) {
54
86
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
55
87
  }
56
- const run = await this.apifyClient.run(this.actorRunId).get();
88
+ const run = await this.#getCurrentRun();
57
89
  if (run === undefined) {
58
90
  throw new Error('Actor run not found');
59
91
  }
92
+ if (run.standby?.deployment.startsWith('MULTI_TENANT')) {
93
+ const actor = await this.#getCurrentActor();
94
+ if (actor === undefined) {
95
+ throw new Error('Actor not found');
96
+ }
97
+ this.#isMultiTenant = true;
98
+ return {
99
+ pricingInfo: getEffectivePricingInfo(actor.pricingInfos ?? []),
100
+ chargedEventCounts: {}, // the run's counts mix all callers
101
+ maxTotalChargeUsd: Infinity, // the platform prices and limits per caller
102
+ };
103
+ }
60
104
  return {
61
105
  pricingInfo: run.pricingInfo,
62
106
  chargedEventCounts: run.chargedEventCounts,
@@ -66,7 +110,7 @@ export class ChargingManager {
66
110
  return {
67
111
  pricingInfo: undefined,
68
112
  chargedEventCounts: {},
69
- maxTotalChargeUsd: this.configuration.maxTotalChargeUsd || Infinity,
113
+ maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
70
114
  };
71
115
  }
72
116
  /**
@@ -74,77 +118,87 @@ export class ChargingManager {
74
118
  */
75
119
  async init() {
76
120
  // Validate config - it may have changed since the instantiation
77
- if (this.useChargingLogDataset && this.isAtHome) {
78
- throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
79
- }
80
- if (this.configuration.testPayPerEvent) {
81
- if (this.isAtHome) {
121
+ if (this.#configuration.testPayPerEvent) {
122
+ if (this.#isAtHome) {
82
123
  throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
83
124
  }
84
125
  }
85
126
  // Retrieve pricing information
86
127
  const { pricingInfo, chargedEventCounts, maxTotalChargeUsd } = await this.fetchPricingInfo();
87
- if (this.configuration.testPayPerEvent) {
88
- this.pricingModel = 'PAY_PER_EVENT';
128
+ if (this.#configuration.testPayPerEvent) {
129
+ this.#pricingModel = 'PAY_PER_EVENT';
89
130
  }
90
131
  else {
91
- this.pricingModel ??= pricingInfo?.pricingModel;
132
+ this.#pricingModel ??= pricingInfo?.pricingModel;
92
133
  }
93
134
  // Load per-event pricing information
94
135
  if (pricingInfo?.pricingModel === 'PAY_PER_EVENT') {
95
- for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents)) {
96
- this.pricingInfo[eventName] = {
97
- price: eventPricing.eventPriceUsd,
136
+ for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents ?? {})) {
137
+ this.#pricingInfo[eventName] = {
138
+ price: eventPricing.eventPriceUsd ?? 0,
98
139
  title: eventPricing.eventTitle,
99
140
  };
100
141
  }
101
- this.maxTotalChargeUsd = maxTotalChargeUsd;
142
+ this.#maxTotalChargeUsd = maxTotalChargeUsd;
102
143
  }
103
- 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();
104
156
  for (const [eventName, chargeCount] of Object.entries(chargedEventCounts ?? {})) {
105
- this.chargingState[eventName] = {
106
- chargeCount,
107
- totalChargedAmount: chargeCount * (this.pricingInfo[eventName]?.price ?? 0),
108
- };
157
+ this.#chargedEventCounts[eventName] = Math.max(this.#chargedEventCounts[eventName] ?? 0, chargeCount);
109
158
  }
110
- if (!this.isPayPerEvent || !this.useChargingLogDataset) {
159
+ if (this.#isAtHome || !this.isPayPerEvent) {
111
160
  return;
112
161
  }
113
- // Set up charging log dataset
114
- if (this.isAtHome) {
115
- const datasetId = await this.ensureChargingLogDatasetOnPlatform();
116
- this.chargingLogDataset = await Dataset.open(datasetId);
117
- }
118
- else {
119
- if (this.purgeChargingLogDataset) {
120
- const dataset = await Dataset.open(this.LOCAL_CHARGING_LOG_DATASET_NAME);
121
- await dataset.drop();
122
- }
123
- this.chargingLogDataset = await Dataset.open(this.LOCAL_CHARGING_LOG_DATASET_NAME);
162
+ // Local pay-per-event runs log every charge into a dataset for debugging.
163
+ if (this.#purgeChargingLogDataset) {
164
+ const dataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
165
+ await dataset.drop();
124
166
  }
167
+ this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
125
168
  }
126
- async ensureChargingLogDatasetOnPlatform() {
127
- const defaultStore = await KeyValueStore.open();
128
- const storedDatasetId = await defaultStore.getValue(this.PLATFORM_CHARGING_LOG_DATASET_ID_KEY);
129
- if (storedDatasetId !== null) {
130
- return storedDatasetId;
131
- }
132
- const dataset = await this.apifyClient.datasets().getOrCreate();
133
- await defaultStore.setValue(this.PLATFORM_CHARGING_LOG_DATASET_ID_KEY, dataset.id);
134
- return dataset.id;
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
+ }
177
+ /**
178
+ * Whether {@link ChargingManager.init} has run. All charging operations (including
179
+ * {@link ChargingManager.getPricingInfo}) require an initialized manager.
180
+ */
181
+ get isInitialized() {
182
+ return this.#chargingState !== undefined;
183
+ }
184
+ get #chargedEventCounts() {
185
+ if (this.#chargingState === undefined) {
186
+ throw new Error('ChargingManager is not initialized');
187
+ }
188
+ return this.#chargingState.currentValue.chargedEventCounts;
135
189
  }
136
190
  /**
137
191
  * Get information about the pricing for this Actor.
138
192
  */
139
193
  getPricingInfo() {
140
- if (this.chargingState === undefined) {
194
+ if (this.#chargingState === undefined) {
141
195
  throw new Error('ChargingManager is not initialized');
142
196
  }
143
197
  return {
144
- pricingModel: this.pricingModel,
198
+ pricingModel: this.#pricingModel,
145
199
  isPayPerEvent: this.isPayPerEvent,
146
- maxTotalChargeUsd: this.maxTotalChargeUsd,
147
- perEventPrices: Object.fromEntries(Object.entries(this.pricingInfo).map(([eventName, { price }]) => [eventName, price])),
200
+ maxTotalChargeUsd: this.#maxTotalChargeUsd,
201
+ perEventPrices: Object.fromEntries(Object.entries(this.#pricingInfo).map(([eventName, { price }]) => [eventName, price])),
148
202
  };
149
203
  }
150
204
  /**
@@ -161,112 +215,207 @@ export class ChargingManager {
161
215
  * rather than batching via `count` — this gives finer control over budget consumption
162
216
  * and avoids situations where more work is requested than the budget allows.
163
217
  *
218
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
219
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
220
+ * be globally unique (e.g. derived from `requestId`).
221
+ *
164
222
  * @param options The name of the event to charge for and the number of events to be charged.
165
223
  */
166
- async charge({ eventName, count = 1 }) {
167
- const calculateChargeableWithinLimit = () => Object.fromEntries(Object.keys(this.pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)]));
224
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
225
+ if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
226
+ throw new Error('idempotencyKey must not be blank');
227
+ }
168
228
  if (!this.isPayPerEvent) {
169
- if (!this.notPpeWarningPrinted) {
229
+ if (!this.#notPpeWarningPrinted) {
170
230
  log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
171
- this.notPpeWarningPrinted = true;
231
+ this.#notPpeWarningPrinted = true;
172
232
  }
173
233
  return {
174
234
  eventChargeLimitReached: false,
175
235
  chargedCount: 0,
176
- chargeableWithinLimit: calculateChargeableWithinLimit(),
236
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
177
237
  };
178
238
  }
179
- if (this.chargingState === undefined) {
180
- throw new Error('ChargingManager is not initialized');
239
+ if (this.#isMultiTenant) {
240
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
181
241
  }
182
- /* START OF CRITICAL SECTION - no awaits here */
183
- const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
184
- const chargedCount = (() => {
185
- if (count <= maxEventChargeCount) {
186
- return count;
187
- }
188
- // If the caller tries to charge more than the budget allows, overcharge by one event
189
- // so that the Actor is detected by the platform and terminated.
190
- // But don't do this if already strictly over the budget - no point piling on charges.
191
- if (this.calculateTotalChargedAmount() <= this.maxTotalChargeUsd) {
192
- return maxEventChargeCount + 1;
193
- }
194
- return 0;
195
- })();
196
- if (chargedCount === 0) {
242
+ // Match the Python SDK: a non-positive count never reaches the platform and never
243
+ // mutates local charge state (a negative count would otherwise decrement the budget).
244
+ if (count <= 0) {
197
245
  return {
198
- eventChargeLimitReached: count > 0, // Only true if user wanted to charge but couldn't
246
+ eventChargeLimitReached: false,
199
247
  chargedCount: 0,
200
- chargeableWithinLimit: calculateChargeableWithinLimit(),
248
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
201
249
  };
202
250
  }
203
- const pricingInfo = this.pricingInfo[eventName] ?? {
204
- price: this.isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
205
- title: `Unknown event '${eventName}'`,
206
- };
207
- this.chargingState[eventName] ??= {
208
- chargeCount: 0,
209
- totalChargedAmount: 0,
210
- };
211
- this.chargingState[eventName].chargeCount += chargedCount;
212
- this.chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
213
- /* END OF CRITICAL SECTION */
214
- if (this.isAtHome) {
215
- if (eventName.startsWith('apify-')) {
216
- // Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
217
- // the platform handles them automatically based on dataset writes.
251
+ if (this.#chargingState === undefined) {
252
+ throw new Error('ChargingManager is not initialized');
253
+ }
254
+ return await this.withChargeLock(async () => {
255
+ // A repeat the platform would discard is resolved here too - counting it would inflate the charging state
256
+ // and make the run hit `maxTotalChargeUsd` early. The key alone decides, as on the platform.
257
+ const previous = idempotencyKey === undefined ? undefined : this.getIdempotentCharge(idempotencyKey);
258
+ if (previous !== undefined) {
259
+ let repeatedCount;
260
+ if (previous.eventName === eventName) {
261
+ log.debug(`Skipped a repeated charge of event '${eventName}' under key '${idempotencyKey}'.`);
262
+ repeatedCount = previous.chargedCount;
263
+ }
264
+ else {
265
+ log.warning(`Idempotency key '${idempotencyKey}' was already used to charge for event '${previous.eventName}', so the charge of event '${eventName}' is skipped.`);
266
+ repeatedCount = 0;
267
+ }
268
+ return {
269
+ eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
270
+ chargedCount: repeatedCount,
271
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
272
+ };
273
+ }
274
+ const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
275
+ const chargedCount = (() => {
276
+ if (count <= maxEventChargeCount) {
277
+ return count;
278
+ }
279
+ // If the caller tries to charge more than the budget allows, overcharge by one event
280
+ // so that the Actor is detected by the platform and terminated.
281
+ // But don't do this if already strictly over the budget - no point piling on charges.
282
+ if (this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd) {
283
+ return maxEventChargeCount + 1;
284
+ }
285
+ return 0;
286
+ })();
287
+ if (chargedCount === 0) {
288
+ return {
289
+ eventChargeLimitReached: count > 0, // Only true if user wanted to charge but couldn't
290
+ chargedCount: 0,
291
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
292
+ };
218
293
  }
219
- else if (this.pricingInfo[eventName] !== undefined) {
220
- await this.apifyClient.run(this.actorRunId).charge({ eventName, count: chargedCount });
294
+ const pricingInfo = this.#pricingInfo[eventName] ?? {
295
+ price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
296
+ title: `Unknown event '${eventName}'`,
297
+ };
298
+ if (this.#isAtHome) {
299
+ if (eventName.startsWith('apify-')) {
300
+ // Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
301
+ // the platform handles them automatically based on dataset writes.
302
+ }
303
+ else if (this.#pricingInfo[eventName] !== undefined) {
304
+ await this.#apifyClient.run(this.#actorRunId).charge({
305
+ eventName,
306
+ count: chargedCount,
307
+ idempotencyKey,
308
+ requestId,
309
+ });
310
+ }
311
+ else {
312
+ log.warning(`Attempting to charge for an unknown event '${eventName}'`);
313
+ }
221
314
  }
222
- else {
223
- log.warning(`Attempting to charge for an unknown event '${eventName}'`);
315
+ // Count the charge only after the API call succeeds, so a failed call retried under the same key
316
+ // is counted once.
317
+ this.#chargedEventCounts[eventName] = (this.#chargedEventCounts[eventName] ?? 0) + chargedCount;
318
+ // Remember the key for every charge that was counted, including events the API never receives,
319
+ // such as synthetic ones - those are counted locally and a repeat would count them twice.
320
+ if (idempotencyKey !== undefined) {
321
+ this.setIdempotentCharge(idempotencyKey, { eventName, chargedCount });
224
322
  }
225
- }
226
- const timestamp = new Date().toISOString();
227
- if (this.chargingLogDataset !== undefined) {
228
- await this.chargingLogDataset.pushData({
229
- eventName,
230
- eventTitle: pricingInfo.title,
231
- eventPriceUsd: pricingInfo.price,
323
+ // The charge is not rolled back with a storage transaction, so neither is its log entry.
324
+ const chargingLogDataset = this.#chargingLogDataset;
325
+ if (chargingLogDataset !== undefined) {
326
+ await withDirectStorageAccess(async () => chargingLogDataset.pushData({
327
+ eventName,
328
+ eventTitle: pricingInfo.title,
329
+ eventPriceUsd: pricingInfo.price,
330
+ chargedCount,
331
+ idempotencyKey,
332
+ requestId,
333
+ timestamp: new Date().toISOString(),
334
+ }));
335
+ }
336
+ if (chargedCount < count) {
337
+ const subject = count === 1 ? 'instance' : 'instances';
338
+ log.info(`Charging ${count} ${subject} of '${eventName}' event would exceed maxTotalChargeUsd - only ${chargedCount} events were charged`);
339
+ }
340
+ return {
341
+ eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
232
342
  chargedCount,
233
- timestamp,
234
- });
343
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
344
+ };
345
+ });
346
+ }
347
+ /**
348
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
349
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
350
+ * run, even by another caller.
351
+ */
352
+ async chargeServerRequest(eventName, count, idempotencyKey, requestId) {
353
+ if (eventName.startsWith('apify-')) {
354
+ throw new Error(`Cannot charge for synthetic event '${eventName}' in a multi-tenant Server Actor run`);
355
+ }
356
+ if (!requestId) {
357
+ throw new Error(`Charging for '${eventName}' in a multi-tenant Server Actor run requires \`requestId\` - pass the value of the incoming request's X-Actor-Request-ID header to Actor.charge().`);
235
358
  }
236
- if (chargedCount < count) {
237
- const subject = count === 1 ? 'instance' : 'instances';
238
- log.info(`Charging ${count} ${subject} of '${eventName}' event would exceed maxTotalChargeUsd - only ${chargedCount} events were charged`);
359
+ let chargedCount = 0;
360
+ if (count <= 0) {
361
+ // Nothing to charge.
362
+ }
363
+ else if (this.#pricingInfo[eventName] === undefined) {
364
+ log.warning(`Attempting to charge for an unknown event '${eventName}'`);
365
+ }
366
+ else {
367
+ await this.#apifyClient.run(this.#actorRunId).charge({ eventName, count, idempotencyKey, requestId });
368
+ chargedCount = count;
239
369
  }
240
370
  return {
241
- eventChargeLimitReached: this.calculateMaxEventChargeCountWithinLimit(eventName) <= 0,
371
+ eventChargeLimitReached: false,
242
372
  chargedCount,
243
- chargeableWithinLimit: calculateChargeableWithinLimit(),
373
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
244
374
  };
245
375
  }
376
+ getIdempotentCharge(idempotencyKey) {
377
+ const charge = this.#idempotentCharges.get(idempotencyKey);
378
+ if (charge !== undefined && charge.expiresAt <= Date.now()) {
379
+ this.#idempotentCharges.delete(idempotencyKey);
380
+ return undefined;
381
+ }
382
+ return charge;
383
+ }
384
+ setIdempotentCharge(idempotencyKey, charge) {
385
+ const now = Date.now();
386
+ // Entries expire in insertion order, so pruning can stop at the first live one.
387
+ for (const [key, { expiresAt }] of this.#idempotentCharges) {
388
+ if (expiresAt > now) {
389
+ break;
390
+ }
391
+ this.#idempotentCharges.delete(key);
392
+ }
393
+ this.#idempotentCharges.set(idempotencyKey, { ...charge, expiresAt: now + IDEMPOTENCY_KEY_TTL_MILLIS });
394
+ }
246
395
  /**
247
396
  * Get the number of events with given name that the Actor has charged for so far.
248
397
  */
249
398
  getChargedEventCount(eventName) {
250
- if (this.chargingState === undefined) {
399
+ if (this.#chargingState === undefined) {
251
400
  throw new Error('ChargingManager is not initialized');
252
401
  }
253
- return this.chargingState[eventName]?.chargeCount ?? 0;
402
+ return this.#chargedEventCounts[eventName] ?? 0;
254
403
  }
255
404
  /**
256
405
  * Get the maximum amount of money that the Actor is allowed to charge.
257
406
  */
258
407
  getMaxTotalChargeUsd() {
259
- if (this.chargingState === undefined) {
408
+ if (this.#chargingState === undefined) {
260
409
  throw new Error('ChargingManager is not initialized');
261
410
  }
262
- return this.maxTotalChargeUsd;
411
+ return this.#maxTotalChargeUsd;
263
412
  }
264
413
  calculateTotalChargedAmount() {
265
- if (this.chargingState === undefined) {
414
+ if (this.#chargingState === undefined) {
266
415
  throw new Error('ChargingManager is not initialized');
267
416
  }
268
- const result = Object.values(this.chargingState)
269
- .map(({ totalChargedAmount }) => totalChargedAmount)
417
+ const result = Object.entries(this.#chargedEventCounts)
418
+ .map(([eventName, count]) => count * (this.calculateEventPrice(eventName) ?? 0))
270
419
  .reduce((sum, inc) => sum + inc, 0);
271
420
  // Keeping float precision issues at bay
272
421
  return Number(result.toFixed(6));
@@ -276,7 +425,7 @@ export class ChargingManager {
276
425
  * If the event is not registered, returns Infinity (free of charge)
277
426
  */
278
427
  calculateMaxEventChargeCountWithinLimit(eventName) {
279
- if (this.chargingState === undefined) {
428
+ if (this.#chargingState === undefined) {
280
429
  throw new Error('ChargingManager is not initialized');
281
430
  }
282
431
  const price = this.calculateEventPrice(eventName);
@@ -286,96 +435,69 @@ export class ChargingManager {
286
435
  return this.calculateMaxChargesByPrice(price);
287
436
  }
288
437
  calculateEventPrice(eventName) {
289
- 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);
290
440
  }
291
441
  calculateMaxChargesByPrice(price) {
292
442
  // The raw number of events allowed by the budget
293
- const unroundedResult = (this.maxTotalChargeUsd - this.calculateTotalChargedAmount()) / price;
443
+ const unroundedResult = (this.#maxTotalChargeUsd - this.calculateTotalChargedAmount()) / price;
294
444
  // First round as Math.floor(4.9999999999999999) will incorrectly return 5
295
445
  const roundedResult = Math.floor(Number(unroundedResult.toFixed(4)));
296
446
  return Math.max(0, roundedResult);
297
447
  }
298
448
  /**
299
- * Helper to calculate how many items can be pushed within charging limits.
300
- * Returns the limited items and count to charge.
449
+ * Whether the remaining budget is insufficient to charge even a single event of the given type.
450
+ * Always false when nothing is charged in the first place.
451
+ */
452
+ isEventChargeLimitReached(eventName) {
453
+ return this.isPayPerEvent && this.calculateMaxEventChargeCountWithinLimit(eventName) <= 0;
454
+ }
455
+ /**
456
+ * How many events of each known type can still be charged within the limit.
301
457
  */
302
- calculatePushDataLimits({ items, eventName, isDefaultDataset, }) {
303
- if (this.chargingState === undefined) {
458
+ calculateChargeableWithinLimit() {
459
+ return Object.fromEntries(Object.keys(this.#pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)]));
460
+ }
461
+ /**
462
+ * How many of `itemsCount` items may be pushed to a dataset within the remaining budget.
463
+ *
464
+ * The budget is measured against the combined per-item price of the explicit `eventName` and - on
465
+ * the default dataset - the synthetic {@link DEFAULT_DATASET_ITEM_EVENT}, since pushing one item
466
+ * charges both.
467
+ *
468
+ * When the budget cannot cover a single item, one item is still allowed through so that the
469
+ * resulting overcharge makes the platform terminate the run - unless the run is already strictly
470
+ * over budget, in which case nothing is allowed through.
471
+ */
472
+ calculatePushDataLimit(itemsCount, { eventName, isDefaultDataset = false } = {}) {
473
+ if (this.#chargingState === undefined) {
304
474
  throw new Error('ChargingManager is not initialized');
305
475
  }
306
- const itemsArray = Array.isArray(items) ? items : [items];
307
- if (!this.isPayPerEvent) {
308
- return {
309
- limitedItems: itemsArray,
310
- eventsToCharge: {},
311
- };
476
+ if (!this.isPayPerEvent || itemsCount === 0) {
477
+ return itemsCount;
312
478
  }
313
- const itemPrice = ((eventName !== undefined ? this.calculateEventPrice(eventName) : undefined) ?? 0) +
314
- ((isDefaultDataset ? this.calculateEventPrice(DEFAULT_DATASET_ITEM_EVENT) : undefined) ?? 0);
315
- const maxChargedCount = itemPrice > 0 ? this.calculateMaxChargesByPrice(itemPrice) : Infinity;
316
- const itemsToKeep = (() => {
317
- if (maxChargedCount >= itemsArray.length) {
318
- return itemsArray.length;
319
- }
320
- // If the caller tries to push items even though the limit is depleted, overcharge by one
321
- // so that the Platform terminates the run.
322
- // But don't do this if already strictly over the budget - no point piling on charges.
323
- if (itemsArray.length > 0 &&
324
- maxChargedCount === 0 &&
325
- this.calculateTotalChargedAmount() <= this.maxTotalChargeUsd) {
326
- return 1;
327
- }
328
- return maxChargedCount;
329
- })();
330
- const eventsToCharge = {};
331
- if (eventName !== undefined && itemsToKeep > 0) {
332
- eventsToCharge[eventName] = itemsToKeep;
479
+ const itemPrice = (eventName === undefined ? 0 : (this.calculateEventPrice(eventName) ?? 0)) +
480
+ (isDefaultDataset ? (this.calculateEventPrice(DEFAULT_DATASET_ITEM_EVENT) ?? 0) : 0);
481
+ if (itemPrice === 0) {
482
+ return itemsCount;
333
483
  }
334
- if (isDefaultDataset && itemsToKeep > 0) {
335
- eventsToCharge[DEFAULT_DATASET_ITEM_EVENT] = itemsToKeep;
484
+ const maxChargedCount = this.calculateMaxChargesByPrice(itemPrice);
485
+ if (maxChargedCount >= itemsCount) {
486
+ return itemsCount;
336
487
  }
337
- return {
338
- limitedItems: itemsToKeep >= itemsArray.length ? itemsArray : itemsArray.slice(0, itemsToKeep),
339
- eventsToCharge,
340
- };
341
- }
342
- }
343
- /**
344
- * Helper for PPE-aware pushing of data to the dataset.
345
- *
346
- * 1. Calculate limits based on budget
347
- * 2. Push limited items via the provided callback
348
- * 3. Charge for the events
349
- *
350
- * @internal
351
- */
352
- export async function pushDataAndCharge({ chargingManager, items, eventName, isDefaultDataset, pushFn, }) {
353
- const { limitedItems, eventsToCharge } = chargingManager.calculatePushDataLimits({
354
- items,
355
- eventName,
356
- isDefaultDataset,
357
- });
358
- if (limitedItems.length > 0) {
359
- // Preserve original call shape for single items
360
- await pushFn(Array.isArray(items) ? limitedItems : limitedItems[0]);
488
+ if (maxChargedCount > 0) {
489
+ return maxChargedCount;
490
+ }
491
+ return this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd ? 1 : 0;
361
492
  }
362
- if (Object.keys(eventsToCharge).length > 0) {
363
- const results = {};
364
- await Promise.all(Object.entries(eventsToCharge).map(async ([name, count]) => {
365
- results[name] = await chargingManager.charge({
366
- eventName: name,
367
- count,
368
- });
369
- }));
370
- // Merge all charge results so that eventChargeLimitReached reflects
371
- // whether ANY of the charged events hit their limit.
372
- return Object.values(results).reduce(mergeChargeResults);
493
+ /**
494
+ * Runs `fn` under the charge lock, which keeps a limit reservation and the charge that acts on it
495
+ * atomic against concurrent pushes. Only pay-per-event runs charge anything, so for every other
496
+ * run there is nothing to serialize and the lock is skipped.
497
+ *
498
+ * @internal
499
+ */
500
+ async withChargeLock(fn) {
501
+ return this.isPayPerEvent ? await this.#chargeLock.runExclusive(fn) : await fn();
373
502
  }
374
- const itemsArray = Array.isArray(items) ? items : [items];
375
- const allItemsTrimmed = itemsArray.length > 0 && limitedItems.length === 0;
376
- return {
377
- eventChargeLimitReached: allItemsTrimmed,
378
- chargedCount: 0,
379
- chargeableWithinLimit: {},
380
- };
381
503
  }