apify 4.0.0-rc.0 → 4.0.0-rc.2

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.
@@ -28,6 +28,7 @@ export class ApifyKeyValueStoreBackend {
28
28
  async getValue(key) {
29
29
  // Storage backends are byte transports — the KeyValueStore frontend parses values
30
30
  // according to their content type, so the record must be returned unparsed.
31
+ // The client may type the bytes as a `Uint8Array`; in Node.js they are always a `Buffer`.
31
32
  return this.#client.getRecord(key, { buffer: true });
32
33
  }
33
34
  async setValue(record) {
@@ -45,7 +45,7 @@ export declare abstract class ApifyRequestQueueBackend implements RequestQueueBa
45
45
  abstract reclaimRequest(request: UpdateRequestSchema, options?: RequestQueueOperationOptions): Promise<QueueOperationInfo | undefined>;
46
46
  abstract isEmpty(): Promise<boolean>;
47
47
  abstract isFinished(): Promise<boolean>;
48
- setExpectedRequestProcessingTimeSecs(_secs: number): Promise<void>;
48
+ setExpectedRequestProcessingTime(_processingTimeSecs: number): Promise<void>;
49
49
  getMetadata(): Promise<RequestQueueInfo>;
50
50
  drop(): Promise<void>;
51
51
  purge(): Promise<void>;
@@ -32,7 +32,7 @@ export class ApifyRequestQueueBackend {
32
32
  constructor(client) {
33
33
  this.client = client;
34
34
  }
35
- async setExpectedRequestProcessingTimeSecs(_secs) {
35
+ async setExpectedRequestProcessingTime(_processingTimeSecs) {
36
36
  // Only relevant for backends that reserve requests via locking; see the shared backend.
37
37
  }
38
38
  async getMetadata() {
@@ -7,14 +7,14 @@ import { ApifyRequestQueueBackend } from './apify_request_queue_backend.js';
7
7
  * number of clients — including other Actor runs — can process the same queue concurrently without
8
8
  * handing out a request twice. The lock is held until the request is marked as handled or
9
9
  * reclaimed, and its duration follows the consumer's expected processing time
10
- * (see {@link setExpectedRequestProcessingTimeSecs}). This consistency costs roughly one extra API
10
+ * (see {@link setExpectedRequestProcessingTime}). This consistency costs roughly one extra API
11
11
  * call per processed request compared to the single-consumer backend.
12
12
  *
13
13
  * @internal
14
14
  */
15
15
  export declare class ApifyRequestQueueSharedBackend extends ApifyRequestQueueBackend {
16
16
  #private;
17
- setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
17
+ setExpectedRequestProcessingTime(processingTimeSecs: number): Promise<void>;
18
18
  addBatchOfRequests(requests: RequestSchema[], options?: RequestQueueOperationOptions): Promise<BatchAddRequestsResult>;
19
19
  getRequest(uniqueKey: string): Promise<UpdateRequestSchema | undefined>;
20
20
  fetchNextRequest(): Promise<UpdateRequestSchema | undefined>;
@@ -14,7 +14,7 @@ const HEAD_LOCK_LIMIT = 25;
14
14
  * number of clients — including other Actor runs — can process the same queue concurrently without
15
15
  * handing out a request twice. The lock is held until the request is marked as handled or
16
16
  * reclaimed, and its duration follows the consumer's expected processing time
17
- * (see {@link setExpectedRequestProcessingTimeSecs}). This consistency costs roughly one extra API
17
+ * (see {@link setExpectedRequestProcessingTime}). This consistency costs roughly one extra API
18
18
  * call per processed request compared to the single-consumer backend.
19
19
  *
20
20
  * @internal
@@ -28,14 +28,14 @@ export class ApifyRequestQueueSharedBackend extends ApifyRequestQueueBackend {
28
28
  #inProgressIds = new Set();
29
29
  /** Whether the last head read reported any locked requests left in the queue (any client's). */
30
30
  #queueHasLockedRequests;
31
- /** Lock duration applied to fetched requests; raised via `setExpectedRequestProcessingTimeSecs`. */
31
+ /** Lock duration applied to fetched requests; raised via `setExpectedRequestProcessingTime`. */
32
32
  #lockSecs = DEFAULT_REQUEST_LOCK_SECS;
33
33
  /** Serializes head reads and reclaims — both reorder the shared head state. */
34
34
  #headLock = new AsyncLock();
35
- async setExpectedRequestProcessingTimeSecs(secs) {
35
+ async setExpectedRequestProcessingTime(processingTimeSecs) {
36
36
  // Only ever raise the lock duration — several consumers may share this client, and a
37
37
  // short-lived one must not cut the reservation of a long-running one short.
38
- this.#lockSecs = Math.max(this.#lockSecs, secs);
38
+ this.#lockSecs = Math.max(this.#lockSecs, processingTimeSecs);
39
39
  }
40
40
  async addBatchOfRequests(requests, options = {}) {
41
41
  const { forefront = false } = options;
@@ -9,7 +9,7 @@ import { ApifyRequestQueueSingleBackend } from './apify_request_queue_single_bac
9
9
  /** The reserved alias crawlee uses for the default (unnamed) storage. */
10
10
  export const DEFAULT_STORAGE_ALIAS = '__default__';
11
11
  /** The key of the default key-value store record holding this run's alias -> storage id mapping. */
12
- const ALIAS_MAPPING_RECORD_KEY = '__STORAGE_ALIASES_MAPPING';
12
+ const ALIAS_MAPPING_RECORD_KEY = 'APIFY_STORAGE_ALIASES_MAPPING';
13
13
  async function readAliasMapping(store) {
14
14
  const record = await store.getRecord(ALIAS_MAPPING_RECORD_KEY);
15
15
  return record?.value ?? {};
@@ -130,11 +130,6 @@ export class ApifyStorageBackend {
130
130
  if (defaultId)
131
131
  return defaultId;
132
132
  }
133
- else {
134
- const declaredId = this.aliasFromActorStorages(alias, type);
135
- if (declaredId)
136
- return declaredId;
137
- }
138
133
  return this.resolveAliasId(alias, type);
139
134
  }
140
135
  /**
@@ -149,16 +144,14 @@ export class ApifyStorageBackend {
149
144
  // differently-authenticated backends maps to two storages.
150
145
  const key = [type, alias, this.credentialsHash()].join(',');
151
146
  return this.#aliasLock.runExclusive(async () => {
152
- const knownId = this.#aliasIdCache.get(key);
153
- if (knownId)
154
- return knownId;
155
147
  const store = this.aliasMappingStore();
156
148
  this.#persistedAliasIds ??= store ? await readAliasMapping(store) : {};
157
- // A persisted id can point at a storage the user has since deleted.
158
- const persistedId = this.#persistedAliasIds[key];
159
- if (persistedId && (await this.resourceClient(persistedId, type).get())) {
160
- this.#aliasIdCache.set(key, persistedId);
161
- return persistedId;
149
+ // A known id can point at a storage deleted since it was resolved. The persisted id wins
150
+ // over the declared one, as it only exists if the declared storage was gone.
151
+ const knownId = this.#aliasIdCache.get(key) ?? this.#persistedAliasIds[key] ?? this.aliasFromActorStorages(alias, type);
152
+ if (knownId && (await this.resourceClient(knownId, type).get())) {
153
+ this.#aliasIdCache.set(key, knownId);
154
+ return knownId;
162
155
  }
163
156
  const { id } = await this.collectionClient(type).getOrCreate();
164
157
  this.#aliasIdCache.set(key, id);
@@ -1,4 +1,4 @@
1
- import type { ActorRunPricingInfo, ApifyClient } from 'apify-client';
1
+ import type { ActorResource, ActorRunPricingInfo, ApifyClient, Run as ClientActorRun } 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 {
@@ -13,10 +13,18 @@ export interface ChargeOptions {
13
13
  */
14
14
  count?: number;
15
15
  /**
16
- * Repeated charges sharing a key are billed once - e.g. a request handler rerun by a retry.
17
- * Local accounting still counts every call, so the remaining budget comes out underestimated.
16
+ * A unique key preventing a retried operation from being charged for twice - e.g. a request handler rerun by a retry.
17
+ * A repeat under the same key within three minutes is not sent to the API and reports the `chargedCount` of
18
+ * the original call, or zero if it names a different event. Like the platform, the key is forgotten afterwards.
19
+ * In a multi-tenant Server Actor run, every call is sent and the platform deduplicates it.
18
20
  */
19
21
  idempotencyKey?: string;
22
+ /**
23
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
24
+ * 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.
25
+ * Ignored elsewhere.
26
+ */
27
+ requestId?: string;
20
28
  }
21
29
  export interface ChargeResult {
22
30
  /**
@@ -59,15 +67,16 @@ export interface ActorPricingInfo {
59
67
  */
60
68
  export declare class ChargingManager {
61
69
  #private;
62
- constructor(configuration: Configuration, apifyClient: ApifyClient);
70
+ constructor(configuration: Configuration, apifyClient: ApifyClient, getCurrentRun: () => Promise<ClientActorRun | undefined>, getCurrentActor: () => Promise<ActorResource | undefined>);
63
71
  /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
64
72
  get isPayPerEvent(): boolean;
73
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
74
+ get isMultiTenant(): boolean;
65
75
  private fetchPricingInfo;
66
76
  /**
67
77
  * Initialize the ChargingManager by loading pricing information and charging state via Apify API.
68
78
  */
69
79
  init(): Promise<void>;
70
- private ensureChargingLogDatasetOnPlatform;
71
80
  /**
72
81
  * Whether {@link ChargingManager.init} has run. All charging operations (including
73
82
  * {@link ChargingManager.getPricingInfo}) require an initialized manager.
@@ -91,9 +100,21 @@ export declare class ChargingManager {
91
100
  * rather than batching via `count` — this gives finer control over budget consumption
92
101
  * and avoids situations where more work is requested than the budget allows.
93
102
  *
103
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
104
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
105
+ * be globally unique (e.g. derived from `requestId`).
106
+ *
94
107
  * @param options The name of the event to charge for and the number of events to be charged.
95
108
  */
96
- charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
109
+ charge({ eventName, count, idempotencyKey, requestId }: ChargeOptions): Promise<ChargeResult>;
110
+ /**
111
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
112
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
113
+ * run, even by another caller.
114
+ */
115
+ private chargeServerRequest;
116
+ private getIdempotentCharge;
117
+ private setIdempotentCharge;
97
118
  /**
98
119
  * Get the number of events with given name that the Actor has charged for so far.
99
120
  */
package/dist/charging.js CHANGED
@@ -1,72 +1,99 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { Dataset, KeyValueStore } from '@crawlee/core';
1
+ import { Dataset, withDirectStorageAccess } from '@crawlee/core';
2
+ import { META_ORIGINS } from '@apify/consts';
3
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;
4
7
  export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
5
8
  /**
6
- * A FIFO mutex that a critical section may re-enter from a nested call — the charge lock is taken by
7
- * `Actor.pushData()` and again, one level down, by the dataset backend it pushes through.
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.
8
14
  */
9
- class ReentrantAsyncLock {
10
- #tail = Promise.resolve();
11
- #held = new AsyncLocalStorage();
12
- async runExclusive(fn) {
13
- if (this.#held.getStore()) {
14
- return await fn();
15
- }
16
- const run = this.#tail.then(async () => this.#held.run(true, fn));
17
- // Keep the chain alive even when the critical section throws.
18
- this.#tail = run.catch(() => { });
19
- return await run;
20
- }
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);
21
20
  }
22
21
  /**
23
22
  * Handles pay-per-event charging.
24
23
  */
25
24
  export class ChargingManager {
26
- #LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log';
27
- #PLATFORM_CHARGING_LOG_DATASET_ID_KEY = 'CHARGING_LOG_DATASET_ID';
25
+ #LOCAL_CHARGING_LOG_DATASET_NAME = 'charging-log';
28
26
  #maxTotalChargeUsd;
29
27
  #isAtHome;
30
28
  #actorRunId;
31
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
32
  #purgeChargingLogDataset;
33
- #useChargingLogDataset;
34
33
  #notPpeWarningPrinted = false;
35
34
  #pricingInfo = {};
36
35
  #chargingState;
37
36
  #chargingLogDataset;
37
+ /** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
38
+ #idempotentCharges = new Map();
38
39
  #chargeLock = new ReentrantAsyncLock();
39
40
  #apifyClient;
40
41
  #configuration;
41
- constructor(configuration, apifyClient) {
42
+ #getCurrentRun;
43
+ #getCurrentActor;
44
+ constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
42
45
  this.#configuration = configuration;
43
46
  this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
44
47
  this.#isAtHome = configuration.isAtHome;
45
48
  this.#actorRunId = configuration.actorRunId;
46
49
  this.#purgeChargingLogDataset = configuration.purgeOnStart;
47
- this.#useChargingLogDataset = configuration.useChargingLogDataset;
48
50
  this.#apifyClient = apifyClient;
51
+ this.#getCurrentRun = getCurrentRun;
52
+ this.#getCurrentActor = getCurrentActor;
49
53
  }
50
54
  /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
51
55
  get isPayPerEvent() {
52
56
  return this.#pricingModel === 'PAY_PER_EVENT';
53
57
  }
58
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
59
+ get isMultiTenant() {
60
+ return this.#isMultiTenant;
61
+ }
54
62
  async fetchPricingInfo() {
55
63
  if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
56
- return {
57
- pricingInfo: JSON.parse(this.#configuration.actorPricingInfo),
58
- chargedEventCounts: JSON.parse(this.#configuration.chargedEventCounts),
59
- maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
60
- };
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
+ }
61
76
  }
62
77
  if (this.#isAtHome) {
63
78
  if (this.#actorRunId === undefined) {
64
79
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
65
80
  }
66
- const run = await this.#apifyClient.run(this.#actorRunId).get();
81
+ const run = await this.#getCurrentRun();
67
82
  if (run === undefined) {
68
83
  throw new Error('Actor run not found');
69
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
+ }
70
97
  return {
71
98
  pricingInfo: run.pricingInfo,
72
99
  chargedEventCounts: run.chargedEventCounts,
@@ -84,9 +111,6 @@ export class ChargingManager {
84
111
  */
85
112
  async init() {
86
113
  // Validate config - it may have changed since the instantiation
87
- if (this.#useChargingLogDataset && this.#isAtHome) {
88
- throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
89
- }
90
114
  if (this.#configuration.testPayPerEvent) {
91
115
  if (this.#isAtHome) {
92
116
  throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
@@ -117,31 +141,15 @@ export class ChargingManager {
117
141
  totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
118
142
  };
119
143
  }
120
- if (!this.isPayPerEvent || !this.#useChargingLogDataset) {
144
+ if (this.#isAtHome || !this.isPayPerEvent) {
121
145
  return;
122
146
  }
123
- // Set up charging log dataset
124
- if (this.#isAtHome) {
125
- const datasetId = await this.ensureChargingLogDatasetOnPlatform();
126
- this.#chargingLogDataset = await Dataset.open(datasetId);
127
- }
128
- else {
129
- if (this.#purgeChargingLogDataset) {
130
- const dataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
131
- await dataset.drop();
132
- }
133
- 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();
134
151
  }
135
- }
136
- async ensureChargingLogDatasetOnPlatform() {
137
- const defaultStore = await KeyValueStore.open();
138
- const storedDatasetId = await defaultStore.getValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY);
139
- if (storedDatasetId !== null) {
140
- return storedDatasetId;
141
- }
142
- const dataset = await this.#apifyClient.datasets().getOrCreate();
143
- await defaultStore.setValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY, dataset.id);
144
- return dataset.id;
152
+ this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
145
153
  }
146
154
  /**
147
155
  * Whether {@link ChargingManager.init} has run. All charging operations (including
@@ -178,9 +186,16 @@ export class ChargingManager {
178
186
  * rather than batching via `count` — this gives finer control over budget consumption
179
187
  * and avoids situations where more work is requested than the budget allows.
180
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
+ *
181
193
  * @param options The name of the event to charge for and the number of events to be charged.
182
194
  */
183
- async charge({ eventName, count = 1, idempotencyKey }) {
195
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
196
+ if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
197
+ throw new Error('idempotencyKey must not be blank');
198
+ }
184
199
  if (!this.isPayPerEvent) {
185
200
  if (!this.#notPpeWarningPrinted) {
186
201
  log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
@@ -192,11 +207,42 @@ export class ChargingManager {
192
207
  chargeableWithinLimit: this.calculateChargeableWithinLimit(),
193
208
  };
194
209
  }
210
+ if (this.#isMultiTenant) {
211
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
212
+ }
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) {
216
+ return {
217
+ eventChargeLimitReached: false,
218
+ chargedCount: 0,
219
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
220
+ };
221
+ }
195
222
  const chargingState = this.#chargingState;
196
223
  if (chargingState === undefined) {
197
224
  throw new Error('ChargingManager is not initialized');
198
225
  }
199
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
+ };
245
+ }
200
246
  const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
201
247
  const chargedCount = (() => {
202
248
  if (count <= maxEventChargeCount) {
@@ -221,12 +267,6 @@ export class ChargingManager {
221
267
  price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
222
268
  title: `Unknown event '${eventName}'`,
223
269
  };
224
- chargingState[eventName] ??= {
225
- chargeCount: 0,
226
- totalChargedAmount: 0,
227
- };
228
- chargingState[eventName].chargeCount += chargedCount;
229
- chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
230
270
  if (this.#isAtHome) {
231
271
  if (eventName.startsWith('apify-')) {
232
272
  // Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
@@ -237,20 +277,38 @@ export class ChargingManager {
237
277
  eventName,
238
278
  count: chargedCount,
239
279
  idempotencyKey,
280
+ requestId,
240
281
  });
241
282
  }
242
283
  else {
243
284
  log.warning(`Attempting to charge for an unknown event '${eventName}'`);
244
285
  }
245
286
  }
246
- if (this.#chargingLogDataset !== undefined) {
247
- await this.#chargingLogDataset.pushData({
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({
248
304
  eventName,
249
305
  eventTitle: pricingInfo.title,
250
306
  eventPriceUsd: pricingInfo.price,
251
307
  chargedCount,
308
+ idempotencyKey,
309
+ requestId,
252
310
  timestamp: new Date().toISOString(),
253
- });
311
+ }));
254
312
  }
255
313
  if (chargedCount < count) {
256
314
  const subject = count === 1 ? 'instance' : 'instances';
@@ -263,6 +321,54 @@ export class ChargingManager {
263
321
  };
264
322
  });
265
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.
339
+ }
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;
346
+ }
347
+ return {
348
+ eventChargeLimitReached: false,
349
+ chargedCount,
350
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
351
+ };
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
+ }
266
372
  /**
267
373
  * Get the number of events with given name that the Actor has charged for so far.
268
374
  */
@@ -30,8 +30,12 @@ export class ChargingDatasetBackend {
30
30
  }
31
31
  async pushData(items) {
32
32
  const chargingManager = this.#getChargingManager();
33
- // `Dataset.pushData()` also works without `Actor.init()`, where there is no charging state yet.
34
- if (items.length === 0 || !chargingManager.isInitialized || !chargingManager.isPayPerEvent) {
33
+ // `Dataset.pushData()` also works without `Actor.init()`, where there is no charging state yet. Multi-tenant
34
+ // runs charge per request only, so dataset writes charge nothing there.
35
+ if (items.length === 0 ||
36
+ !chargingManager.isInitialized ||
37
+ !chargingManager.isPayPerEvent ||
38
+ chargingManager.isMultiTenant) {
35
39
  await this.#inner.pushData(items);
36
40
  return;
37
41
  }
@@ -0,0 +1,88 @@
1
+ import type { Run as ActorRun, RunClient, RunResurrectOptions } from 'apify-client';
2
+ import type { ApifyClient } from './index.js';
3
+ /**
4
+ * Status of a tracked child run. This copies the `ActorRun['status']` type,
5
+ * but adds `LOST` to mark a locally tracked run that the platform no longer returns.
6
+ *
7
+ * `LOST` runs can happen as a result of a manual removal or expiration.
8
+ */
9
+ export type ChildRunStatus = ActorRun['status'] | 'LOST';
10
+ export interface ChildRunInfo {
11
+ runId: string;
12
+ status: ChildRunStatus;
13
+ /** ISO 8601 timestamp. */
14
+ startedAt: string;
15
+ }
16
+ export interface TrackedChildRun extends ChildRunInfo {
17
+ /** Identifies the Actor / task and input the run was started with. */
18
+ checksum: string;
19
+ /** Earlier runs that were replaced under the same name, oldest first. */
20
+ history: ChildRunInfo[];
21
+ /** Whether the run is aborted when this run is gracefully aborted. */
22
+ abortWithParent: boolean;
23
+ }
24
+ export interface ChildRunRequest {
25
+ type: 'actor' | 'task';
26
+ id: string;
27
+ input?: unknown;
28
+ }
29
+ /**
30
+ * How long `abortRunsWithParent()` waits for the child runs to be aborted. The platform force-stops a gracefully aborted
31
+ * run 30 seconds after the `aborting` event, which has to leave `Actor.exit()` time for the rest of its work.
32
+ */
33
+ export declare const ABORT_WITH_PARENT_TIMEOUT_MILLIS = 10000;
34
+ export declare class ChildRunTracker {
35
+ private trackedRuns;
36
+ private loading?;
37
+ /** Client each name was last started or resumed with in this process, so a custom `token` is kept. */
38
+ private clients;
39
+ private lastWrite;
40
+ private locks;
41
+ /** Set once this run is being gracefully aborted, after which no run with `abortWithParent` is started. */
42
+ private isParentAborting;
43
+ /**
44
+ * Throws if the run tracked under `runName` was started for a different Actor / task or input,
45
+ * as it would otherwise be silently returned or resurrected in place of the requested one.
46
+ */
47
+ verifyRequest(runName: string, request: ChildRunRequest): Promise<void>;
48
+ /**
49
+ * Returns the child run tracked under `runName` if it is still in progress or has succeeded, and resurrects it
50
+ * with `startOptions` if it was aborted or timed out (waiting for it to finish aborting or timing out first).
51
+ * Otherwise (the run failed or is gone), starts a new one using `start` and tracks it under `runName`,
52
+ * keeping the previous one in the history. `abortWithParent` replaces the value tracked under `runName`.
53
+ */
54
+ startOrResumeChildRun(client: ApifyClient, runName: string, request: ChildRunRequest, startOptions: RunResurrectOptions, abortWithParent: boolean, start: () => Promise<ActorRun>): Promise<{
55
+ run: ActorRun;
56
+ resumed: boolean;
57
+ }>;
58
+ /**
59
+ * Tracks `run` as the current run under `runName`. A run tracked earlier under the same name is moved to the
60
+ * history, with `replacedStatus` as its last known status.
61
+ */
62
+ track(runName: string, run: ActorRun, request: ChildRunRequest, replacedStatus: ChildRunStatus, abortWithParent: boolean): Promise<void>;
63
+ /**
64
+ * Records the latest observed state of the run tracked under `runName`.
65
+ */
66
+ update(runName: string, run: ActorRun): Promise<void>;
67
+ /**
68
+ * Returns the tracked run and its history for `runName`, if there is one.
69
+ */
70
+ get(runName: string): Promise<TrackedChildRun>;
71
+ /**
72
+ * Returns a `RunClient` for the current run under each name loaded so far. The client is the one the name was
73
+ * last started or resumed with in this process, or `defaultClient` (e.g. for a run tracked before a migration).
74
+ */
75
+ getRunClients(defaultClient: ApifyClient): Record<string, RunClient>;
76
+ /**
77
+ * Gracefully aborts the current run under each name tracked with `abortWithParent`, and makes any later start with
78
+ * `abortWithParent` throw. A start in flight is waited for, so the run it starts is aborted too. Resolves after
79
+ * {@link ABORT_WITH_PARENT_TIMEOUT_MILLIS} at the latest, leaving the aborts still in progress to go on.
80
+ */
81
+ abortRunsWithParent(defaultClient: ApifyClient): Promise<void>;
82
+ private getLock;
83
+ private persist;
84
+ /**
85
+ * Loads the tracked runs from the default key-value store, once.
86
+ */
87
+ load(): Promise<Record<string, TrackedChildRun>>;
88
+ }