apify 4.0.0-beta.14 → 4.0.0-beta.140

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