apify 3.7.3-beta.97 → 3.7.3-beta.99

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.
package/dist/actor.d.ts CHANGED
@@ -322,6 +322,8 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
322
322
  */
323
323
  private gracefulShutdownHandlers;
324
324
  private chargingManager;
325
+ private runPromise?;
326
+ private actorPromise?;
325
327
  /**
326
328
  * Tracks which aliased storages have been purged during this session,
327
329
  * so we only purge them once (on first open) when running locally.
@@ -572,6 +574,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
572
574
  * @param item Object or array of objects containing data to be stored in the default dataset.
573
575
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
574
576
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
577
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
575
578
  * @ignore
576
579
  */
577
580
  pushData(item: Data | Data[], eventName?: string | undefined): Promise<ChargeResult>;
@@ -782,6 +785,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
782
785
  * rather than batching via `count` — this gives finer control over budget consumption
783
786
  * and avoids situations where more work is requested than the budget allows.
784
787
  *
788
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
789
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
790
+ * be globally unique (e.g. derived from `requestId`).
791
+ *
785
792
  * @param options The name of the event to charge for and the number of events to be charged.
786
793
  * @ignore
787
794
  */
@@ -791,6 +798,14 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
791
798
  * @ignore
792
799
  */
793
800
  getChargingManager(): ChargingManager;
801
+ /**
802
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
803
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
804
+ * Resolves to `undefined` when not running on the Apify platform.
805
+ */
806
+ getCurrentRun(): Promise<ClientActorRun | undefined>;
807
+ /** Cached for the lifetime of the Actor; only the charging manager needs it. */
808
+ private getCurrentActor;
794
809
  /**
795
810
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
796
811
  */
@@ -1122,6 +1137,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1122
1137
  * @param item Object or array of objects containing data to be stored in the default dataset.
1123
1138
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1124
1139
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1140
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1125
1141
  */
1126
1142
  static pushData<Data extends Dictionary = Dictionary>(item: Data | Data[], eventName: string): Promise<ChargeResult>;
1127
1143
  /**
@@ -1322,6 +1338,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1322
1338
  * rather than batching via `count` — this gives finer control over budget consumption
1323
1339
  * and avoids situations where more work is requested than the budget allows.
1324
1340
  *
1341
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1342
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1343
+ * be globally unique (e.g. derived from `requestId`).
1344
+ *
1325
1345
  * @param options The name of the event to charge for and the number of events to be charged.
1326
1346
  */
1327
1347
  static charge(options: ChargeOptions): Promise<ChargeResult>;
@@ -1349,6 +1369,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1349
1369
  * Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).
1350
1370
  */
1351
1371
  static isAtHome(): boolean;
1372
+ /**
1373
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1374
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1375
+ * Resolves to `undefined` when not running on the Apify platform.
1376
+ */
1377
+ static getCurrentRun(): Promise<ClientActorRun | undefined>;
1352
1378
  /** Default {@link ApifyClient} instance. */
1353
1379
  static get apifyClient(): ApifyClient;
1354
1380
  /** Default {@link Configuration} instance. */
package/dist/actor.js CHANGED
@@ -119,6 +119,18 @@ class Actor {
119
119
  writable: true,
120
120
  value: void 0
121
121
  });
122
+ Object.defineProperty(this, "runPromise", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: void 0
127
+ });
128
+ Object.defineProperty(this, "actorPromise", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: void 0
133
+ });
122
134
  /**
123
135
  * Tracks which aliased storages have been purged during this session,
124
136
  * so we only purge them once (on first open) when running locally.
@@ -134,7 +146,7 @@ class Actor {
134
146
  this.config = Object.keys(options).length === 0 ? configuration_js_1.Configuration.getGlobalConfig() : new configuration_js_1.Configuration(options);
135
147
  this.apifyClient = this.newClient();
136
148
  this.eventManager = new platform_event_manager_js_1.PlatformEventManager(this.config);
137
- this.chargingManager = new charging_js_1.ChargingManager(this.config, this.apifyClient);
149
+ this.chargingManager = new charging_js_1.ChargingManager(this.config, this.apifyClient, async () => this.getCurrentRun(), async () => this.getCurrentActor());
138
150
  }
139
151
  /**
140
152
  * Runs the main user function that performs the job of the Actor
@@ -279,6 +291,13 @@ class Actor {
279
291
  });
280
292
  log_1.default.debug(`Default storages purged`);
281
293
  configuration_js_1.Configuration.storage.enterWith(this.config);
294
+ this.runPromise = undefined;
295
+ this.actorPromise = undefined;
296
+ if (this.isAtHome() && this.config.get('metaOrigin') === consts_1.META_ORIGINS.STANDBY) {
297
+ // Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
298
+ void this.getCurrentRun().catch(() => { });
299
+ void this.getCurrentActor().catch(() => { });
300
+ }
282
301
  await this.chargingManager.init();
283
302
  log_1.default.debug(`ChargingManager initialized`, this.chargingManager.getPricingInfo());
284
303
  }
@@ -660,6 +679,7 @@ class Actor {
660
679
  * @param item Object or array of objects containing data to be stored in the default dataset.
661
680
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
662
681
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
682
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
663
683
  * @ignore
664
684
  */
665
685
  async pushData(item, eventName) {
@@ -667,6 +687,9 @@ class Actor {
667
687
  if (eventName?.startsWith('apify-')) {
668
688
  throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
669
689
  }
690
+ if (eventName !== undefined && this.chargingManager.isMultiTenant) {
691
+ throw new Error('Charging for pushed items is not supported in a multi-tenant Server Actor run - use Actor.charge() with the `requestId` of the incoming request instead.');
692
+ }
670
693
  const dataset = await this.openDataset();
671
694
  // Two code paths for charging:
672
695
  // 1. Intercepted client: PatchedDatasetClient intercepts pushItems() calls, handling charging
@@ -952,6 +975,10 @@ class Actor {
952
975
  * rather than batching via `count` — this gives finer control over budget consumption
953
976
  * and avoids situations where more work is requested than the budget allows.
954
977
  *
978
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
979
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
980
+ * be globally unique (e.g. derived from `requestId`).
981
+ *
955
982
  * @param options The name of the event to charge for and the number of events to be charged.
956
983
  * @ignore
957
984
  */
@@ -967,6 +994,40 @@ class Actor {
967
994
  this._ensureActorInit('getChargingManager');
968
995
  return this.chargingManager;
969
996
  }
997
+ /**
998
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
999
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1000
+ * Resolves to `undefined` when not running on the Apify platform.
1001
+ */
1002
+ async getCurrentRun() {
1003
+ const runId = this.config.get('actorRunId');
1004
+ if (!runId) {
1005
+ return undefined;
1006
+ }
1007
+ this.runPromise ?? (this.runPromise = this.apifyClient
1008
+ .run(runId)
1009
+ .get()
1010
+ .catch((err) => {
1011
+ this.runPromise = undefined;
1012
+ throw err;
1013
+ }));
1014
+ return this.runPromise;
1015
+ }
1016
+ /** Cached for the lifetime of the Actor; only the charging manager needs it. */
1017
+ async getCurrentActor() {
1018
+ const actorId = this.config.get('actorId');
1019
+ if (!actorId) {
1020
+ return undefined;
1021
+ }
1022
+ this.actorPromise ?? (this.actorPromise = this.apifyClient
1023
+ .actor(actorId)
1024
+ .get()
1025
+ .catch((err) => {
1026
+ this.actorPromise = undefined;
1027
+ throw err;
1028
+ }));
1029
+ return this.actorPromise;
1030
+ }
970
1031
  /**
971
1032
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
972
1033
  */
@@ -1361,6 +1422,7 @@ class Actor {
1361
1422
  * @param item Object or array of objects containing data to be stored in the default dataset.
1362
1423
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
1363
1424
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
1425
+ * Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
1364
1426
  */
1365
1427
  static async pushData(item, eventName) {
1366
1428
  if (eventName === undefined) {
@@ -1580,6 +1642,10 @@ class Actor {
1580
1642
  * rather than batching via `count` — this gives finer control over budget consumption
1581
1643
  * and avoids situations where more work is requested than the budget allows.
1582
1644
  *
1645
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
1646
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
1647
+ * be globally unique (e.g. derived from `requestId`).
1648
+ *
1583
1649
  * @param options The name of the event to charge for and the number of events to be charged.
1584
1650
  */
1585
1651
  static async charge(options) {
@@ -1617,6 +1683,14 @@ class Actor {
1617
1683
  static isAtHome() {
1618
1684
  return Actor.getDefaultInstance().isAtHome();
1619
1685
  }
1686
+ /**
1687
+ * Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
1688
+ * so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
1689
+ * Resolves to `undefined` when not running on the Apify platform.
1690
+ */
1691
+ static async getCurrentRun() {
1692
+ return Actor.getDefaultInstance().getCurrentRun();
1693
+ }
1620
1694
  /** Default {@link ApifyClient} instance. */
1621
1695
  static get apifyClient() {
1622
1696
  return Actor.getDefaultInstance().apifyClient;
@@ -1,4 +1,4 @@
1
- import type { ActorRunPricingInfo, ApifyClient } from 'apify-client';
1
+ import type { Actor as ClientActor, ActorRun, ActorRunPricingInfo, ApifyClient } from 'apify-client';
2
2
  import type { Configuration } from './configuration.js';
3
3
  export declare const DEFAULT_DATASET_ITEM_EVENT = "apify-default-dataset-item";
4
4
  export interface ChargeOptions {
@@ -16,6 +16,12 @@ export interface ChargeOptions {
16
16
  * An idempotency key to prevent multiple unintended charges.
17
17
  */
18
18
  idempotencyKey?: string;
19
+ /**
20
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
21
+ * Required for multi-tenant Server Actor runs, where it maps the charge to the caller's account instead of the account that started the run.
22
+ * Ignored elsewhere.
23
+ */
24
+ requestId?: string;
19
25
  }
20
26
  export interface ChargeResult {
21
27
  /**
@@ -59,12 +65,16 @@ export declare function mergeChargeResults(a: ChargeResult, b: ChargeResult): Ch
59
65
  */
60
66
  export declare class ChargingManager {
61
67
  private configuration;
68
+ private getCurrentRun;
69
+ private getCurrentActor;
62
70
  private readonly LOCAL_CHARGING_LOG_DATASET_NAME;
63
71
  private readonly PLATFORM_CHARGING_LOG_DATASET_ID_KEY;
64
72
  private maxTotalChargeUsd;
65
73
  private isAtHome;
66
74
  private actorRunId?;
67
75
  private pricingModel?;
76
+ /** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
77
+ private multiTenant;
68
78
  private purgeChargingLogDataset;
69
79
  private useChargingLogDataset;
70
80
  private notPpeWarningPrinted;
@@ -72,8 +82,10 @@ export declare class ChargingManager {
72
82
  private chargingState?;
73
83
  private chargingLogDataset?;
74
84
  private apifyClient;
75
- constructor(configuration: Configuration, apifyClient: ApifyClient);
85
+ constructor(configuration: Configuration, apifyClient: ApifyClient, getCurrentRun: () => Promise<ActorRun | undefined>, getCurrentActor: () => Promise<ClientActor | undefined>);
76
86
  private get isPayPerEvent();
87
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
88
+ get isMultiTenant(): boolean;
77
89
  private fetchPricingInfo;
78
90
  /**
79
91
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
@@ -103,9 +115,17 @@ export declare class ChargingManager {
103
115
  * rather than batching via `count` — this gives finer control over budget consumption
104
116
  * and avoids situations where more work is requested than the budget allows.
105
117
  *
118
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
119
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
120
+ * be globally unique (e.g. derived from `requestId`).
121
+ *
106
122
  * @param options The name of the event to charge for and the number of events to be charged.
107
123
  */
108
- charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
124
+ charge({ eventName, count, idempotencyKey, requestId }: ChargeOptions): Promise<ChargeResult>;
125
+ /**
126
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced locally.
127
+ */
128
+ private chargeServerRequest;
109
129
  /**
110
130
  * Get the number of events with given name that the Actor has charged for so far.
111
131
  */
package/dist/charging.js CHANGED
@@ -5,8 +5,22 @@ exports.mergeChargeResults = mergeChargeResults;
5
5
  exports.pushDataAndCharge = pushDataAndCharge;
6
6
  const tslib_1 = require("tslib");
7
7
  const core_1 = require("@crawlee/core");
8
+ const consts_1 = require("@apify/consts");
8
9
  const log_1 = tslib_1.__importDefault(require("@apify/log"));
9
10
  exports.DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
11
+ /**
12
+ * The pricing history includes scheduled future changes, so the effective entry is the latest one
13
+ * with `startedAt <= now`, not the last one.
14
+ *
15
+ * Resolved once at init on purpose. A change kicking in mid-run only affects local event titles and
16
+ * "unknown event" warnings; the platform prices each charge from its own current pricing anyway.
17
+ */
18
+ function getEffectivePricingInfo(pricingInfos, now = new Date()) {
19
+ return pricingInfos
20
+ .filter((info) => new Date(info.startedAt) <= now)
21
+ .sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime())
22
+ .at(-1);
23
+ }
10
24
  function mergeChargeResults(a, b) {
11
25
  return {
12
26
  eventChargeLimitReached: a.eventChargeLimitReached || b.eventChargeLimitReached,
@@ -21,13 +35,25 @@ function mergeChargeResults(a, b) {
21
35
  * Handles pay-per-event charging.
22
36
  */
23
37
  class ChargingManager {
24
- constructor(configuration, apifyClient) {
38
+ constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
25
39
  Object.defineProperty(this, "configuration", {
26
40
  enumerable: true,
27
41
  configurable: true,
28
42
  writable: true,
29
43
  value: configuration
30
44
  });
45
+ Object.defineProperty(this, "getCurrentRun", {
46
+ enumerable: true,
47
+ configurable: true,
48
+ writable: true,
49
+ value: getCurrentRun
50
+ });
51
+ Object.defineProperty(this, "getCurrentActor", {
52
+ enumerable: true,
53
+ configurable: true,
54
+ writable: true,
55
+ value: getCurrentActor
56
+ });
31
57
  Object.defineProperty(this, "LOCAL_CHARGING_LOG_DATASET_NAME", {
32
58
  enumerable: true,
33
59
  configurable: true,
@@ -64,6 +90,13 @@ class ChargingManager {
64
90
  writable: true,
65
91
  value: void 0
66
92
  });
93
+ /** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
94
+ Object.defineProperty(this, "multiTenant", {
95
+ enumerable: true,
96
+ configurable: true,
97
+ writable: true,
98
+ value: false
99
+ });
67
100
  Object.defineProperty(this, "purgeChargingLogDataset", {
68
101
  enumerable: true,
69
102
  configurable: true,
@@ -116,22 +149,45 @@ class ChargingManager {
116
149
  get isPayPerEvent() {
117
150
  return this.pricingModel === 'PAY_PER_EVENT';
118
151
  }
152
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
153
+ get isMultiTenant() {
154
+ return this.multiTenant;
155
+ }
119
156
  async fetchPricingInfo() {
120
157
  if (this.configuration.get('actorPricingInfo') && this.configuration.get('chargedEventCounts')) {
121
- return {
122
- pricingInfo: JSON.parse(this.configuration.get('actorPricingInfo')),
123
- chargedEventCounts: JSON.parse(this.configuration.get('chargedEventCounts')),
124
- maxTotalChargeUsd: this.configuration.get('maxTotalChargeUsd') || Infinity,
125
- };
158
+ const pricingInfo = JSON.parse(this.configuration.get('actorPricingInfo'));
159
+ // Multi-tenant runs get an empty snapshot (`{}`); only the run tells them apart from free Server Actor runs.
160
+ const isMultiTenantCandidate = pricingInfo.pricingModel === undefined &&
161
+ this.isAtHome &&
162
+ this.configuration.get('metaOrigin') === consts_1.META_ORIGINS.STANDBY;
163
+ if (!isMultiTenantCandidate) {
164
+ return {
165
+ pricingInfo,
166
+ chargedEventCounts: JSON.parse(this.configuration.get('chargedEventCounts')),
167
+ maxTotalChargeUsd: this.configuration.get('maxTotalChargeUsd') || Infinity,
168
+ };
169
+ }
126
170
  }
127
171
  if (this.isAtHome) {
128
172
  if (this.actorRunId === undefined) {
129
173
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
130
174
  }
131
- const run = await this.apifyClient.run(this.actorRunId).get();
175
+ const run = await this.getCurrentRun();
132
176
  if (run === undefined) {
133
177
  throw new Error('Actor run not found');
134
178
  }
179
+ if (run.standby?.deployment.startsWith('MULTI_TENANT')) {
180
+ const actor = await this.getCurrentActor();
181
+ if (actor === undefined) {
182
+ throw new Error('Actor not found');
183
+ }
184
+ this.multiTenant = true;
185
+ return {
186
+ pricingInfo: getEffectivePricingInfo(actor.pricingInfos ?? []),
187
+ chargedEventCounts: {}, // the run's counts mix all callers
188
+ maxTotalChargeUsd: Infinity, // the platform prices and limits per caller
189
+ };
190
+ }
135
191
  return {
136
192
  pricingInfo: run.pricingInfo,
137
193
  chargedEventCounts: run.chargedEventCounts,
@@ -243,9 +299,13 @@ class ChargingManager {
243
299
  * rather than batching via `count` — this gives finer control over budget consumption
244
300
  * and avoids situations where more work is requested than the budget allows.
245
301
  *
302
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
303
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
304
+ * be globally unique (e.g. derived from `requestId`).
305
+ *
246
306
  * @param options The name of the event to charge for and the number of events to be charged.
247
307
  */
248
- async charge({ eventName, count = 1, idempotencyKey }) {
308
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
249
309
  var _a;
250
310
  const calculateChargeableWithinLimit = () => Object.fromEntries(Object.keys(this.pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)]));
251
311
  if (!this.isPayPerEvent) {
@@ -259,6 +319,12 @@ class ChargingManager {
259
319
  chargeableWithinLimit: calculateChargeableWithinLimit(),
260
320
  };
261
321
  }
322
+ if (this.chargingState === undefined) {
323
+ throw new Error('ChargingManager is not initialized');
324
+ }
325
+ if (this.multiTenant) {
326
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
327
+ }
262
328
  // Match the Python SDK: a non-positive count never reaches the platform and never
263
329
  // mutates local charge state (a negative count would otherwise decrement the budget).
264
330
  if (count <= 0) {
@@ -268,9 +334,6 @@ class ChargingManager {
268
334
  chargeableWithinLimit: calculateChargeableWithinLimit(),
269
335
  };
270
336
  }
271
- if (this.chargingState === undefined) {
272
- throw new Error('ChargingManager is not initialized');
273
- }
274
337
  /* START OF CRITICAL SECTION - no awaits here */
275
338
  const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
276
339
  const chargedCount = (() => {
@@ -309,7 +372,9 @@ class ChargingManager {
309
372
  // the platform handles them automatically based on dataset writes.
310
373
  }
311
374
  else if (this.pricingInfo[eventName] !== undefined) {
312
- await this.apifyClient.run(this.actorRunId).charge({ eventName, count: chargedCount, idempotencyKey });
375
+ await this.apifyClient
376
+ .run(this.actorRunId)
377
+ .charge({ eventName, count: chargedCount, idempotencyKey, requestId });
313
378
  }
314
379
  else {
315
380
  log_1.default.warning(`Attempting to charge for an unknown event '${eventName}'`);
@@ -323,6 +388,7 @@ class ChargingManager {
323
388
  eventPriceUsd: pricingInfo.price,
324
389
  chargedCount,
325
390
  timestamp,
391
+ requestId,
326
392
  });
327
393
  }
328
394
  if (chargedCount < count) {
@@ -335,6 +401,33 @@ class ChargingManager {
335
401
  chargeableWithinLimit: calculateChargeableWithinLimit(),
336
402
  };
337
403
  }
404
+ /**
405
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced locally.
406
+ */
407
+ async chargeServerRequest(eventName, count, idempotencyKey, requestId) {
408
+ if (eventName.startsWith('apify-')) {
409
+ throw new Error(`Cannot charge for synthetic event '${eventName}' in a multi-tenant Server Actor run`);
410
+ }
411
+ if (!requestId) {
412
+ 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().`);
413
+ }
414
+ let chargedCount = 0;
415
+ if (count <= 0) {
416
+ // Nothing to charge.
417
+ }
418
+ else if (this.pricingInfo[eventName] === undefined) {
419
+ log_1.default.warning(`Attempting to charge for an unknown event '${eventName}'`);
420
+ }
421
+ else {
422
+ await this.apifyClient.run(this.actorRunId).charge({ eventName, count, idempotencyKey, requestId });
423
+ chargedCount = count;
424
+ }
425
+ return {
426
+ eventChargeLimitReached: false,
427
+ chargedCount,
428
+ chargeableWithinLimit: Object.fromEntries(Object.keys(this.pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)])),
429
+ };
430
+ }
338
431
  /**
339
432
  * Get the number of events with given name that the Actor has charged for so far.
340
433
  */
@@ -396,7 +489,8 @@ class ChargingManager {
396
489
  throw new Error('ChargingManager is not initialized');
397
490
  }
398
491
  const itemsArray = Array.isArray(items) ? items : [items];
399
- if (!this.isPayPerEvent) {
492
+ // Multi-tenant runs charge per request only, so dataset writes charge nothing there.
493
+ if (!this.isPayPerEvent || this.multiTenant) {
400
494
  return {
401
495
  limitedItems: itemsArray,
402
496
  eventsToCharge: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "3.7.3-beta.97",
3
+ "version": "3.7.3-beta.99",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=16.0.0"
@@ -62,7 +62,7 @@
62
62
  "@crawlee/core": "^3.18.2",
63
63
  "@crawlee/types": "^3.18.2",
64
64
  "@crawlee/utils": "^3.18.2",
65
- "apify-client": "^2.25.0",
65
+ "apify-client": "^2.26.0",
66
66
  "fs-extra": "^11.4.1",
67
67
  "ow": "^0.28.2",
68
68
  "semver": "^7.8.5",