apify 4.0.0-beta.13 → 4.0.0-beta.130

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