apify 3.7.3-beta.97 → 4.0.0-beta.101

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