apify 4.0.0-beta.12 → 4.0.0-beta.120

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 (69) hide show
  1. package/README.md +29 -43
  2. package/dist/actor.d.ts +511 -167
  3. package/dist/actor.js +895 -322
  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 +82 -18
  19. package/dist/charging.js +388 -128
  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 +86 -136
  25. package/dist/configuration.js +136 -145
  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 -5
  33. package/dist/index.js +8 -5
  34. package/dist/input-schemas.d.ts +7 -0
  35. package/dist/input-schemas.js +58 -0
  36. package/dist/platform_event_manager.d.ts +15 -6
  37. package/dist/platform_event_manager.js +187 -41
  38. package/dist/proxy_configuration.d.ts +66 -59
  39. package/dist/proxy_configuration.js +172 -154
  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 +38 -0
  43. package/dist/storage.js +1 -0
  44. package/dist/utils.d.ts +28 -4
  45. package/dist/utils.js +60 -20
  46. package/package.json +117 -73
  47. package/.turbo/turbo-build.log +0 -26
  48. package/.turbo/turbo-copy.log +0 -4
  49. package/dist/LICENSE.md +0 -201
  50. package/dist/README.md +0 -98
  51. package/dist/actor.d.ts.map +0 -1
  52. package/dist/actor.js.map +0 -1
  53. package/dist/charging.d.ts.map +0 -1
  54. package/dist/charging.js.map +0 -1
  55. package/dist/configuration.d.ts.map +0 -1
  56. package/dist/configuration.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/key_value_store.d.ts +0 -17
  60. package/dist/key_value_store.d.ts.map +0 -1
  61. package/dist/key_value_store.js +0 -33
  62. package/dist/key_value_store.js.map +0 -1
  63. package/dist/package.json +0 -75
  64. package/dist/platform_event_manager.d.ts.map +0 -1
  65. package/dist/platform_event_manager.js.map +0 -1
  66. package/dist/proxy_configuration.d.ts.map +0 -1
  67. package/dist/proxy_configuration.js.map +0 -1
  68. package/dist/utils.d.ts.map +0 -1
  69. package/dist/utils.js.map +0 -1
package/dist/charging.js CHANGED
@@ -1,115 +1,197 @@
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;
7
+ export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
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);
20
+ }
3
21
  /**
4
22
  * Handles pay-per-event charging.
5
23
  */
6
24
  export class ChargingManager {
7
- LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log';
8
- PLATFORM_CHARGING_LOG_DATASET_ID_KEY = 'CHARGING_LOG_DATASET_ID';
9
- maxTotalChargeUsd;
10
- isAtHome;
11
- actorRunId;
12
- pricingModel;
13
- purgeChargingLogDataset;
14
- useChargingLogDataset;
15
- notPpeWarningPrinted = false;
16
- pricingInfo = {};
17
- chargingState;
18
- chargingLogDataset;
19
- apifyClient;
20
- constructor(configuration, apifyClient) {
21
- this.maxTotalChargeUsd =
22
- configuration.get('maxTotalChargeUsd') || Infinity; // convert `0` to `Infinity` in case the value is an empty string
23
- this.isAtHome = configuration.get('isAtHome');
24
- this.actorRunId = configuration.get('actorRunId');
25
- this.purgeChargingLogDataset = configuration.get('purgeOnStart');
26
- this.useChargingLogDataset = configuration.get('useChargingLogDataset');
27
- if (this.useChargingLogDataset && this.isAtHome) {
28
- throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
29
- }
30
- if (configuration.get('testPayPerEvent')) {
31
- if (this.isAtHome) {
32
- throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
33
- }
34
- this.pricingModel = 'PAY_PER_EVENT';
35
- }
36
- 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;
37
56
  }
57
+ /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
38
58
  get isPayPerEvent() {
39
- return this.pricingModel === 'PAY_PER_EVENT';
59
+ return this.#pricingModel === 'PAY_PER_EVENT';
40
60
  }
41
- /**
42
- * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
43
- */
44
- async init() {
45
- this.chargingState = {};
46
- // Retrieve pricing information
47
- if (this.isAtHome) {
48
- if (this.actorRunId === undefined) {
61
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
62
+ get isMultiTenant() {
63
+ return this.#isMultiTenant;
64
+ }
65
+ async fetchPricingInfo() {
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
+ }
79
+ }
80
+ if (this.#isAtHome) {
81
+ if (this.#actorRunId === undefined) {
49
82
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
50
83
  }
51
- const run = await this.apifyClient.run(this.actorRunId).get();
84
+ const run = await this.#getCurrentRun();
52
85
  if (run === undefined) {
53
86
  throw new Error('Actor run not found');
54
87
  }
55
- this.pricingModel = run.pricingInfo?.pricingModel;
56
- // Load per-event pricing information
57
- if (run.pricingInfo?.pricingModel === 'PAY_PER_EVENT') {
58
- for (const [eventName, eventPricing] of Object.entries(run.pricingInfo.pricingPerEvent.actorChargeEvents)) {
59
- this.pricingInfo[eventName] = {
60
- price: eventPricing.eventPriceUsd,
61
- title: eventPricing.eventTitle,
62
- };
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');
63
92
  }
64
- this.maxTotalChargeUsd =
65
- run.options.maxTotalChargeUsd ?? this.maxTotalChargeUsd;
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
+ }
100
+ return {
101
+ pricingInfo: run.pricingInfo,
102
+ chargedEventCounts: run.chargedEventCounts,
103
+ maxTotalChargeUsd: run.options.maxTotalChargeUsd || Infinity,
104
+ };
105
+ }
106
+ return {
107
+ pricingInfo: undefined,
108
+ chargedEventCounts: {},
109
+ maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
110
+ };
111
+ }
112
+ /**
113
+ * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
114
+ */
115
+ async init() {
116
+ // Validate config - it may have changed since the instantiation
117
+ if (this.#useChargingLogDataset && this.#isAtHome) {
118
+ throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
119
+ }
120
+ if (this.#configuration.testPayPerEvent) {
121
+ if (this.#isAtHome) {
122
+ throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
66
123
  }
67
- // Load charged event counts
68
- for (const [eventName, chargeCount] of Object.entries(run.chargedEventCounts ?? {})) {
69
- this.chargingState[eventName] = {
70
- chargeCount,
71
- totalChargedAmount: chargeCount * (this.pricingInfo[eventName]?.price ?? 0),
124
+ }
125
+ // Retrieve pricing information
126
+ const { pricingInfo, chargedEventCounts, maxTotalChargeUsd } = await this.fetchPricingInfo();
127
+ if (this.#configuration.testPayPerEvent) {
128
+ this.#pricingModel = 'PAY_PER_EVENT';
129
+ }
130
+ else {
131
+ this.#pricingModel ??= pricingInfo?.pricingModel;
132
+ }
133
+ // Load per-event pricing information
134
+ if (pricingInfo?.pricingModel === 'PAY_PER_EVENT') {
135
+ for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents ?? {})) {
136
+ this.#pricingInfo[eventName] = {
137
+ price: eventPricing.eventPriceUsd ?? 0,
138
+ title: eventPricing.eventTitle,
72
139
  };
73
140
  }
141
+ this.#maxTotalChargeUsd = maxTotalChargeUsd;
142
+ }
143
+ this.#chargingState = {};
144
+ for (const [eventName, chargeCount] of Object.entries(chargedEventCounts ?? {})) {
145
+ this.#chargingState[eventName] = {
146
+ chargeCount,
147
+ totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
148
+ };
74
149
  }
75
- if (!this.isPayPerEvent || !this.useChargingLogDataset) {
150
+ if (!this.isPayPerEvent || !this.#useChargingLogDataset) {
76
151
  return;
77
152
  }
78
153
  // Set up charging log dataset
79
- if (this.isAtHome) {
154
+ if (this.#isAtHome) {
80
155
  const datasetId = await this.ensureChargingLogDatasetOnPlatform();
81
- this.chargingLogDataset = await Dataset.open(datasetId);
156
+ this.#chargingLogDataset = await Dataset.open(datasetId);
82
157
  }
83
158
  else {
84
- if (this.purgeChargingLogDataset) {
85
- 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);
86
161
  await dataset.drop();
87
162
  }
88
- this.chargingLogDataset = await Dataset.open(this.LOCAL_CHARGING_LOG_DATASET_NAME);
163
+ this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
89
164
  }
90
165
  }
91
166
  async ensureChargingLogDatasetOnPlatform() {
92
167
  const defaultStore = await KeyValueStore.open();
93
- 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);
94
169
  if (storedDatasetId !== null) {
95
170
  return storedDatasetId;
96
171
  }
97
- const dataset = await this.apifyClient.datasets().getOrCreate();
98
- 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);
99
174
  return dataset.id;
100
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
+ }
101
183
  /**
102
184
  * Get information about the pricing for this Actor.
103
185
  */
104
186
  getPricingInfo() {
105
- if (this.chargingState === undefined) {
187
+ if (this.#chargingState === undefined) {
106
188
  throw new Error('ChargingManager is not initialized');
107
189
  }
108
190
  return {
109
- pricingModel: this.pricingModel,
191
+ pricingModel: this.#pricingModel,
110
192
  isPayPerEvent: this.isPayPerEvent,
111
- maxTotalChargeUsd: this.maxTotalChargeUsd,
112
- 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])),
113
195
  };
114
196
  }
115
197
  /**
@@ -118,101 +200,218 @@ export class ChargingManager {
118
200
  * This method attempts to charge for the specified number of events, but may charge fewer
119
201
  * if doing so would exceed the total budget limit (`maxTotalChargeUsd`).
120
202
  *
203
+ * **Important:** When using the `count` parameter to charge for multiple events at once,
204
+ * be aware that the charge may be partially fulfilled, i.e. `chargedCount` can be less
205
+ * than the requested `count`. Always check the returned `chargedCount` to know how many
206
+ * events were actually charged, and only perform that much work. If your work is
207
+ * meaningfully divisible into individual units, prefer calling `charge()` once per unit
208
+ * rather than batching via `count` — this gives finer control over budget consumption
209
+ * and avoids situations where more work is requested than the budget allows.
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
+ *
121
215
  * @param options The name of the event to charge for and the number of events to be charged.
122
216
  */
123
- async charge({ eventName, count = 1, }) {
124
- const calculateChargeableWithinLimit = () => Object.fromEntries(Object.keys(this.pricingInfo).map((name) => [
125
- name,
126
- this.calculateMaxEventChargeCountWithinLimit(name),
127
- ]));
217
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
218
+ if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
219
+ throw new Error('idempotencyKey must not be blank');
220
+ }
128
221
  if (!this.isPayPerEvent) {
129
- if (!this.notPpeWarningPrinted) {
222
+ if (!this.#notPpeWarningPrinted) {
130
223
  log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
131
- this.notPpeWarningPrinted = true;
224
+ this.#notPpeWarningPrinted = true;
132
225
  }
133
226
  return {
134
227
  eventChargeLimitReached: false,
135
228
  chargedCount: 0,
136
- chargeableWithinLimit: calculateChargeableWithinLimit(),
229
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
137
230
  };
138
231
  }
139
- if (this.chargingState === undefined) {
140
- throw new Error('ChargingManager is not initialized');
232
+ if (this.#isMultiTenant) {
233
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
141
234
  }
142
- /* START OF CRITICAL SECTION - no awaits here */
143
- const chargedCount = Math.min(count, this.calculateMaxEventChargeCountWithinLimit(eventName));
144
- 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) {
145
238
  return {
146
- eventChargeLimitReached: count > 0, // Only true if user wanted to charge but couldn't
239
+ eventChargeLimitReached: false,
147
240
  chargedCount: 0,
148
- chargeableWithinLimit: calculateChargeableWithinLimit(),
241
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
149
242
  };
150
243
  }
151
- const pricingInfo = this.pricingInfo[eventName] ?? {
152
- price: this.isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
153
- title: `Unknown event '${eventName}'`,
154
- };
155
- this.chargingState[eventName] ??= {
156
- chargeCount: 0,
157
- totalChargedAmount: 0,
158
- };
159
- this.chargingState[eventName].chargeCount += chargedCount;
160
- this.chargingState[eventName].totalChargedAmount +=
161
- chargedCount * pricingInfo.price;
162
- /* END OF CRITICAL SECTION */
163
- if (this.isAtHome) {
164
- if (this.pricingInfo[eventName] !== undefined) {
165
- await this.apifyClient
166
- .run(this.actorRunId)
167
- .charge({ eventName, count: chargedCount });
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
+ };
168
267
  }
169
- else {
170
- log.warning(`Attempting to charge for an unknown event '${eventName}'`);
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
+ };
171
287
  }
172
- }
173
- const timestamp = new Date().toISOString();
174
- if (this.chargingLogDataset !== undefined) {
175
- await this.chargingLogDataset.pushData({
176
- eventName,
177
- eventTitle: pricingInfo.title,
178
- eventPriceUsd: pricingInfo.price,
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
+ }
308
+ }
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),
179
339
  chargedCount,
180
- timestamp,
181
- });
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`);
182
352
  }
183
- if (chargedCount < count) {
184
- const subject = count === 1 ? 'instance' : 'instances';
185
- 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;
186
366
  }
187
367
  return {
188
- eventChargeLimitReached: this.calculateMaxEventChargeCountWithinLimit(eventName) <= 0,
368
+ eventChargeLimitReached: false,
189
369
  chargedCount,
190
- chargeableWithinLimit: calculateChargeableWithinLimit(),
370
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
191
371
  };
192
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
+ }
193
392
  /**
194
393
  * Get the number of events with given name that the Actor has charged for so far.
195
394
  */
196
395
  getChargedEventCount(eventName) {
197
- if (this.chargingState === undefined) {
396
+ if (this.#chargingState === undefined) {
198
397
  throw new Error('ChargingManager is not initialized');
199
398
  }
200
- return this.chargingState[eventName]?.chargeCount ?? 0;
399
+ return this.#chargingState[eventName]?.chargeCount ?? 0;
201
400
  }
202
401
  /**
203
402
  * Get the maximum amount of money that the Actor is allowed to charge.
204
403
  */
205
404
  getMaxTotalChargeUsd() {
206
- if (this.chargingState === undefined) {
405
+ if (this.#chargingState === undefined) {
207
406
  throw new Error('ChargingManager is not initialized');
208
407
  }
209
- return this.maxTotalChargeUsd;
408
+ return this.#maxTotalChargeUsd;
210
409
  }
211
410
  calculateTotalChargedAmount() {
212
- if (this.chargingState === undefined) {
411
+ if (this.#chargingState === undefined) {
213
412
  throw new Error('ChargingManager is not initialized');
214
413
  }
215
- const result = Object.values(this.chargingState)
414
+ const result = Object.values(this.#chargingState)
216
415
  .map(({ totalChargedAmount }) => totalChargedAmount)
217
416
  .reduce((sum, inc) => sum + inc, 0);
218
417
  // Keeping float precision issues at bay
@@ -223,17 +422,78 @@ export class ChargingManager {
223
422
  * If the event is not registered, returns Infinity (free of charge)
224
423
  */
225
424
  calculateMaxEventChargeCountWithinLimit(eventName) {
226
- if (this.chargingState === undefined) {
425
+ if (this.#chargingState === undefined) {
227
426
  throw new Error('ChargingManager is not initialized');
228
427
  }
229
- const price = this.isAtHome ? this.pricingInfo[eventName].price : 1; // Use a nonzero price for local development so that the maximum budget can be reached
428
+ const price = this.calculateEventPrice(eventName);
230
429
  if (!price) {
231
430
  return Infinity;
232
431
  }
432
+ return this.calculateMaxChargesByPrice(price);
433
+ }
434
+ calculateEventPrice(eventName) {
435
+ return this.#isAtHome ? this.#pricingInfo[eventName]?.price : 1; // Use a nonzero price for local development so that the maximum budget can be reached
436
+ }
437
+ calculateMaxChargesByPrice(price) {
438
+ // The raw number of events allowed by the budget
439
+ const unroundedResult = (this.#maxTotalChargeUsd - this.calculateTotalChargedAmount()) / price;
233
440
  // First round as Math.floor(4.9999999999999999) will incorrectly return 5
234
- return Math.floor(Number(((this.maxTotalChargeUsd -
235
- this.calculateTotalChargedAmount()) /
236
- price).toFixed(4)));
441
+ const roundedResult = Math.floor(Number(unroundedResult.toFixed(4)));
442
+ return Math.max(0, roundedResult);
443
+ }
444
+ /**
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.
447
+ */
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) {
470
+ throw new Error('ChargingManager is not initialized');
471
+ }
472
+ if (!this.isPayPerEvent || itemsCount === 0) {
473
+ return itemsCount;
474
+ }
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;
479
+ }
480
+ const maxChargedCount = this.calculateMaxChargesByPrice(itemPrice);
481
+ if (maxChargedCount >= itemsCount) {
482
+ return itemsCount;
483
+ }
484
+ if (maxChargedCount > 0) {
485
+ return maxChargedCount;
486
+ }
487
+ return this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd ? 1 : 0;
488
+ }
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();
237
498
  }
238
499
  }
239
- //# sourceMappingURL=charging.js.map