apify 4.0.0-rc.0 → 4.0.0-rc.1

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.
@@ -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;
@@ -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,9 +67,11 @@ 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.
@@ -91,9 +101,21 @@ export declare class ChargingManager {
91
101
  * rather than batching via `count` — this gives finer control over budget consumption
92
102
  * and avoids situations where more work is requested than the budget allows.
93
103
  *
104
+ * **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
105
+ * Server Actor run, a key reused across requests charges only the first caller, so it must
106
+ * be globally unique (e.g. derived from `requestId`).
107
+ *
94
108
  * @param options The name of the event to charge for and the number of events to be charged.
95
109
  */
96
- charge({ eventName, count, idempotencyKey }: ChargeOptions): Promise<ChargeResult>;
110
+ charge({ eventName, count, idempotencyKey, requestId }: ChargeOptions): Promise<ChargeResult>;
111
+ /**
112
+ * The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
113
+ * locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
114
+ * run, even by another caller.
115
+ */
116
+ private chargeServerRequest;
117
+ private getIdempotentCharge;
118
+ private setIdempotentCharge;
97
119
  /**
98
120
  * Get the number of events with given name that the Actor has charged for so far.
99
121
  */
package/dist/charging.js CHANGED
@@ -1,23 +1,22 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
1
  import { Dataset, KeyValueStore } 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.
@@ -29,16 +28,22 @@ export class ChargingManager {
29
28
  #isAtHome;
30
29
  #actorRunId;
31
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;
32
33
  #purgeChargingLogDataset;
33
34
  #useChargingLogDataset;
34
35
  #notPpeWarningPrinted = false;
35
36
  #pricingInfo = {};
36
37
  #chargingState;
37
38
  #chargingLogDataset;
39
+ /** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
40
+ #idempotentCharges = new Map();
38
41
  #chargeLock = new ReentrantAsyncLock();
39
42
  #apifyClient;
40
43
  #configuration;
41
- constructor(configuration, apifyClient) {
44
+ #getCurrentRun;
45
+ #getCurrentActor;
46
+ constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
42
47
  this.#configuration = configuration;
43
48
  this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
44
49
  this.#isAtHome = configuration.isAtHome;
@@ -46,27 +51,52 @@ export class ChargingManager {
46
51
  this.#purgeChargingLogDataset = configuration.purgeOnStart;
47
52
  this.#useChargingLogDataset = configuration.useChargingLogDataset;
48
53
  this.#apifyClient = apifyClient;
54
+ this.#getCurrentRun = getCurrentRun;
55
+ this.#getCurrentActor = getCurrentActor;
49
56
  }
50
57
  /** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
51
58
  get isPayPerEvent() {
52
59
  return this.#pricingModel === 'PAY_PER_EVENT';
53
60
  }
61
+ /** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
62
+ get isMultiTenant() {
63
+ return this.#isMultiTenant;
64
+ }
54
65
  async fetchPricingInfo() {
55
66
  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
- };
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
+ }
61
79
  }
62
80
  if (this.#isAtHome) {
63
81
  if (this.#actorRunId === undefined) {
64
82
  throw new Error('Actor run ID not found even though the Actor is running on Apify');
65
83
  }
66
- const run = await this.#apifyClient.run(this.#actorRunId).get();
84
+ const run = await this.#getCurrentRun();
67
85
  if (run === undefined) {
68
86
  throw new Error('Actor run not found');
69
87
  }
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');
92
+ }
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
+ }
70
100
  return {
71
101
  pricingInfo: run.pricingInfo,
72
102
  chargedEventCounts: run.chargedEventCounts,
@@ -178,9 +208,16 @@ export class ChargingManager {
178
208
  * rather than batching via `count` — this gives finer control over budget consumption
179
209
  * and avoids situations where more work is requested than the budget allows.
180
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
+ *
181
215
  * @param options The name of the event to charge for and the number of events to be charged.
182
216
  */
183
- async charge({ eventName, count = 1, idempotencyKey }) {
217
+ async charge({ eventName, count = 1, idempotencyKey, requestId }) {
218
+ if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
219
+ throw new Error('idempotencyKey must not be blank');
220
+ }
184
221
  if (!this.isPayPerEvent) {
185
222
  if (!this.#notPpeWarningPrinted) {
186
223
  log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
@@ -192,11 +229,42 @@ export class ChargingManager {
192
229
  chargeableWithinLimit: this.calculateChargeableWithinLimit(),
193
230
  };
194
231
  }
232
+ if (this.#isMultiTenant) {
233
+ return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
234
+ }
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) {
238
+ return {
239
+ eventChargeLimitReached: false,
240
+ chargedCount: 0,
241
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
242
+ };
243
+ }
195
244
  const chargingState = this.#chargingState;
196
245
  if (chargingState === undefined) {
197
246
  throw new Error('ChargingManager is not initialized');
198
247
  }
199
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
+ };
267
+ }
200
268
  const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
201
269
  const chargedCount = (() => {
202
270
  if (count <= maxEventChargeCount) {
@@ -221,12 +289,6 @@ export class ChargingManager {
221
289
  price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
222
290
  title: `Unknown event '${eventName}'`,
223
291
  };
224
- chargingState[eventName] ??= {
225
- chargeCount: 0,
226
- totalChargedAmount: 0,
227
- };
228
- chargingState[eventName].chargeCount += chargedCount;
229
- chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
230
292
  if (this.#isAtHome) {
231
293
  if (eventName.startsWith('apify-')) {
232
294
  // Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
@@ -237,18 +299,34 @@ export class ChargingManager {
237
299
  eventName,
238
300
  count: chargedCount,
239
301
  idempotencyKey,
302
+ requestId,
240
303
  });
241
304
  }
242
305
  else {
243
306
  log.warning(`Attempting to charge for an unknown event '${eventName}'`);
244
307
  }
245
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
+ }
246
322
  if (this.#chargingLogDataset !== undefined) {
247
323
  await this.#chargingLogDataset.pushData({
248
324
  eventName,
249
325
  eventTitle: pricingInfo.title,
250
326
  eventPriceUsd: pricingInfo.price,
251
327
  chargedCount,
328
+ idempotencyKey,
329
+ requestId,
252
330
  timestamp: new Date().toISOString(),
253
331
  });
254
332
  }
@@ -263,6 +341,54 @@ export class ChargingManager {
263
341
  };
264
342
  });
265
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`);
352
+ }
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;
366
+ }
367
+ return {
368
+ eventChargeLimitReached: false,
369
+ chargedCount,
370
+ chargeableWithinLimit: this.calculateChargeableWithinLimit(),
371
+ };
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
+ }
266
392
  /**
267
393
  * Get the number of events with given name that the Actor has charged for so far.
268
394
  */
@@ -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
+ }