apify 4.0.0-beta.101 → 4.0.0-beta.102
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 +22 -0
- package/dist/actor.js +69 -3
- package/dist/charging.d.ts +22 -3
- package/dist/charging.js +76 -3
- package/dist/charging_storage_backend.js +6 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/proxy_configuration.js +1 -1
- package/package.json +2 -2
package/dist/actor.d.ts
CHANGED
|
@@ -670,6 +670,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
670
670
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
671
671
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
672
672
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
673
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
673
674
|
* @ignore
|
|
674
675
|
*/
|
|
675
676
|
pushData(item: Data | Data[], eventName?: string | undefined): Promise<ChargeResult>;
|
|
@@ -919,6 +920,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
919
920
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
920
921
|
* and avoids situations where more work is requested than the budget allows.
|
|
921
922
|
*
|
|
923
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
924
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
925
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
926
|
+
*
|
|
922
927
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
923
928
|
* @ignore
|
|
924
929
|
*/
|
|
@@ -928,6 +933,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
928
933
|
* @ignore
|
|
929
934
|
*/
|
|
930
935
|
getChargingManager(): ChargingManager;
|
|
936
|
+
/**
|
|
937
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
938
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
939
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
940
|
+
*/
|
|
941
|
+
getCurrentRun(): Promise<ClientActorRun | undefined>;
|
|
931
942
|
/**
|
|
932
943
|
* Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
|
|
933
944
|
*/
|
|
@@ -1311,6 +1322,7 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
1311
1322
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
1312
1323
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
1313
1324
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
1325
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
1314
1326
|
*/
|
|
1315
1327
|
static pushData<Data extends Dictionary = Dictionary>(item: Data | Data[], eventName: string): Promise<ChargeResult>;
|
|
1316
1328
|
/**
|
|
@@ -1549,6 +1561,10 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
1549
1561
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1550
1562
|
* and avoids situations where more work is requested than the budget allows.
|
|
1551
1563
|
*
|
|
1564
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1565
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1566
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1567
|
+
*
|
|
1552
1568
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1553
1569
|
*/
|
|
1554
1570
|
static charge(options: ChargeOptions): Promise<ChargeResult>;
|
|
@@ -1576,6 +1592,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
|
|
|
1576
1592
|
* Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).
|
|
1577
1593
|
*/
|
|
1578
1594
|
static isAtHome(): boolean;
|
|
1595
|
+
/**
|
|
1596
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1597
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1598
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1599
|
+
*/
|
|
1600
|
+
static getCurrentRun(): Promise<ClientActorRun | undefined>;
|
|
1579
1601
|
/** Default {@link ApifyClient} instance. */
|
|
1580
1602
|
static get apifyClient(): ApifyClient;
|
|
1581
1603
|
/** Default {@link Configuration} instance. */
|
package/dist/actor.js
CHANGED
|
@@ -5,7 +5,7 @@ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend,
|
|
|
5
5
|
import { sleep } from '@crawlee/utils';
|
|
6
6
|
import { ApifyClient } from 'apify-client';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, } from '@apify/consts';
|
|
8
|
+
import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, META_ORIGINS, } from '@apify/consts';
|
|
9
9
|
import { decryptInputSecrets } from '@apify/input_secrets';
|
|
10
10
|
import log from '@apify/log';
|
|
11
11
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
@@ -103,6 +103,8 @@ export class Actor {
|
|
|
103
103
|
*/
|
|
104
104
|
#statusMessageForwarder;
|
|
105
105
|
#chargingManager;
|
|
106
|
+
#runPromise;
|
|
107
|
+
#actorPromise;
|
|
106
108
|
/** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
|
|
107
109
|
#abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
|
|
108
110
|
/** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
|
|
@@ -137,7 +139,7 @@ export class Actor {
|
|
|
137
139
|
this.eventManager = new PlatformEventManager(this.configuration, {
|
|
138
140
|
[ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
|
|
139
141
|
});
|
|
140
|
-
this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
|
|
142
|
+
this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient, async () => this.getCurrentRun(), async () => this.#getCurrentActor());
|
|
141
143
|
this.#childRunTracker = new ChildRunTracker();
|
|
142
144
|
}
|
|
143
145
|
/**
|
|
@@ -295,11 +297,20 @@ export class Actor {
|
|
|
295
297
|
});
|
|
296
298
|
log.debug(`Default storages purged`);
|
|
297
299
|
await this.#childRunTracker.load();
|
|
300
|
+
this.#runPromise = undefined;
|
|
301
|
+
this.#actorPromise = undefined;
|
|
302
|
+
if (this.isAtHome() && this.configuration.metaOrigin === META_ORIGINS.STANDBY) {
|
|
303
|
+
// Server Actor runs live long enough to make the fetches worth it up front; `charge()` needs them anyway.
|
|
304
|
+
void this.getCurrentRun().catch(() => { });
|
|
305
|
+
void this.#getCurrentActor().catch(() => { });
|
|
306
|
+
}
|
|
298
307
|
await this.#chargingManager.init();
|
|
299
308
|
log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
|
|
300
309
|
// Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
|
|
301
310
|
// registered with crawlee directly; the storages the Actor installs itself are wrapped.
|
|
302
|
-
if (this.#chargingManager.isPayPerEvent &&
|
|
311
|
+
if (this.#chargingManager.isPayPerEvent &&
|
|
312
|
+
!this.#chargingManager.isMultiTenant &&
|
|
313
|
+
!this.#chargesDefaultDatasetItems()) {
|
|
303
314
|
log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
|
|
304
315
|
'storage - the platform only counts items it stores itself.');
|
|
305
316
|
}
|
|
@@ -808,6 +819,7 @@ export class Actor {
|
|
|
808
819
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
809
820
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
810
821
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
822
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
811
823
|
* @ignore
|
|
812
824
|
*/
|
|
813
825
|
async pushData(item, eventName) {
|
|
@@ -815,6 +827,9 @@ export class Actor {
|
|
|
815
827
|
if (eventName?.startsWith('apify-')) {
|
|
816
828
|
throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
|
|
817
829
|
}
|
|
830
|
+
if (eventName !== undefined && this.#chargingManager.isMultiTenant) {
|
|
831
|
+
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.');
|
|
832
|
+
}
|
|
818
833
|
if (eventName !== undefined) {
|
|
819
834
|
rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
|
|
820
835
|
'so a rolled-back request would be billed for items that were never stored.');
|
|
@@ -1159,6 +1174,10 @@ export class Actor {
|
|
|
1159
1174
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1160
1175
|
* and avoids situations where more work is requested than the budget allows.
|
|
1161
1176
|
*
|
|
1177
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1178
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1179
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1180
|
+
*
|
|
1162
1181
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1163
1182
|
* @ignore
|
|
1164
1183
|
*/
|
|
@@ -1174,6 +1193,40 @@ export class Actor {
|
|
|
1174
1193
|
this.ensureActorInit('getChargingManager');
|
|
1175
1194
|
return this.#chargingManager;
|
|
1176
1195
|
}
|
|
1196
|
+
/**
|
|
1197
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1198
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1199
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1200
|
+
*/
|
|
1201
|
+
async getCurrentRun() {
|
|
1202
|
+
const runId = this.configuration.actorRunId;
|
|
1203
|
+
if (!runId) {
|
|
1204
|
+
return undefined;
|
|
1205
|
+
}
|
|
1206
|
+
this.#runPromise ??= this.apifyClient
|
|
1207
|
+
.run(runId)
|
|
1208
|
+
.get()
|
|
1209
|
+
.catch((err) => {
|
|
1210
|
+
this.#runPromise = undefined;
|
|
1211
|
+
throw err;
|
|
1212
|
+
});
|
|
1213
|
+
return this.#runPromise;
|
|
1214
|
+
}
|
|
1215
|
+
/** Cached for the lifetime of the Actor; only the charging manager needs it. */
|
|
1216
|
+
async #getCurrentActor() {
|
|
1217
|
+
const { actorId } = this.configuration;
|
|
1218
|
+
if (!actorId) {
|
|
1219
|
+
return undefined;
|
|
1220
|
+
}
|
|
1221
|
+
this.#actorPromise ??= this.apifyClient
|
|
1222
|
+
.actor(actorId)
|
|
1223
|
+
.get()
|
|
1224
|
+
.catch((err) => {
|
|
1225
|
+
this.#actorPromise = undefined;
|
|
1226
|
+
throw err;
|
|
1227
|
+
});
|
|
1228
|
+
return this.#actorPromise;
|
|
1229
|
+
}
|
|
1177
1230
|
/**
|
|
1178
1231
|
* Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
|
|
1179
1232
|
*/
|
|
@@ -1622,6 +1675,7 @@ export class Actor {
|
|
|
1622
1675
|
* @param item Object or array of objects containing data to be stored in the default dataset.
|
|
1623
1676
|
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
|
|
1624
1677
|
* @param eventName If provided, the method will attempt to charge for the event for each pushed item.
|
|
1678
|
+
* Not supported in multi-tenant Server Actor runs, which charge per request with `Actor.charge()`.
|
|
1625
1679
|
*/
|
|
1626
1680
|
static async pushData(item, eventName) {
|
|
1627
1681
|
if (eventName === undefined) {
|
|
@@ -1822,6 +1876,10 @@ export class Actor {
|
|
|
1822
1876
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
1823
1877
|
* and avoids situations where more work is requested than the budget allows.
|
|
1824
1878
|
*
|
|
1879
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
1880
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
1881
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
1882
|
+
*
|
|
1825
1883
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
1826
1884
|
*/
|
|
1827
1885
|
static async charge(options) {
|
|
@@ -1859,6 +1917,14 @@ export class Actor {
|
|
|
1859
1917
|
static isAtHome() {
|
|
1860
1918
|
return Actor.getDefaultInstance().isAtHome();
|
|
1861
1919
|
}
|
|
1920
|
+
/**
|
|
1921
|
+
* Fetches the current Actor run from the Apify API. The result is cached for the lifetime of the Actor,
|
|
1922
|
+
* so use `Actor.apifyClient.run(runId).get()` instead when you need fresh data such as the run status.
|
|
1923
|
+
* Resolves to `undefined` when not running on the Apify platform.
|
|
1924
|
+
*/
|
|
1925
|
+
static async getCurrentRun() {
|
|
1926
|
+
return Actor.getDefaultInstance().getCurrentRun();
|
|
1927
|
+
}
|
|
1862
1928
|
/** Default {@link ApifyClient} instance. */
|
|
1863
1929
|
static get apifyClient() {
|
|
1864
1930
|
return Actor.getDefaultInstance().apifyClient;
|
package/dist/charging.d.ts
CHANGED
|
@@ -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 {
|
|
@@ -16,8 +16,15 @@ export interface ChargeOptions {
|
|
|
16
16
|
* A unique key preventing a retried operation from being charged for twice - e.g. a request handler rerun by a retry.
|
|
17
17
|
* A repeat under the same key within three minutes is not sent to the API and reports the `chargedCount` of
|
|
18
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.
|
|
19
20
|
*/
|
|
20
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;
|
|
21
28
|
}
|
|
22
29
|
export interface ChargeResult {
|
|
23
30
|
/**
|
|
@@ -60,9 +67,11 @@ export interface ActorPricingInfo {
|
|
|
60
67
|
*/
|
|
61
68
|
export declare class ChargingManager {
|
|
62
69
|
#private;
|
|
63
|
-
constructor(configuration: Configuration, apifyClient: ApifyClient);
|
|
70
|
+
constructor(configuration: Configuration, apifyClient: ApifyClient, getCurrentRun: () => Promise<ClientActorRun | undefined>, getCurrentActor: () => Promise<ActorResource | undefined>);
|
|
64
71
|
/** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
|
|
65
72
|
get isPayPerEvent(): boolean;
|
|
73
|
+
/** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
|
|
74
|
+
get isMultiTenant(): boolean;
|
|
66
75
|
private fetchPricingInfo;
|
|
67
76
|
/**
|
|
68
77
|
* Initialize the ChargingManager by loading pricing information and charging state via Apify API.
|
|
@@ -92,9 +101,19 @@ export declare class ChargingManager {
|
|
|
92
101
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
93
102
|
* and avoids situations where more work is requested than the budget allows.
|
|
94
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
|
+
*
|
|
95
108
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
96
109
|
*/
|
|
97
|
-
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;
|
|
98
117
|
private getIdempotentCharge;
|
|
99
118
|
private setIdempotentCharge;
|
|
100
119
|
/**
|
package/dist/charging.js
CHANGED
|
@@ -4,6 +4,19 @@ import { ReentrantAsyncLock } from './utils.js';
|
|
|
4
4
|
/** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
|
|
5
5
|
const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
|
|
6
6
|
export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
|
|
7
|
+
/**
|
|
8
|
+
* The pricing history includes scheduled future changes, so the effective entry is the latest one
|
|
9
|
+
* with `startedAt <= now`, not the last one.
|
|
10
|
+
*
|
|
11
|
+
* Resolved once at init on purpose. A change kicking in mid-run only affects local event titles and
|
|
12
|
+
* "unknown event" warnings; the platform prices each charge from its own current pricing anyway.
|
|
13
|
+
*/
|
|
14
|
+
function getEffectivePricingInfo(pricingInfos, now = new Date()) {
|
|
15
|
+
return pricingInfos
|
|
16
|
+
.filter((info) => new Date(info.startedAt) <= now)
|
|
17
|
+
.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime())
|
|
18
|
+
.at(-1);
|
|
19
|
+
}
|
|
7
20
|
/**
|
|
8
21
|
* Handles pay-per-event charging.
|
|
9
22
|
*/
|
|
@@ -14,6 +27,8 @@ export class ChargingManager {
|
|
|
14
27
|
#isAtHome;
|
|
15
28
|
#actorRunId;
|
|
16
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;
|
|
17
32
|
#purgeChargingLogDataset;
|
|
18
33
|
#useChargingLogDataset;
|
|
19
34
|
#notPpeWarningPrinted = false;
|
|
@@ -25,7 +40,9 @@ export class ChargingManager {
|
|
|
25
40
|
#chargeLock = new ReentrantAsyncLock();
|
|
26
41
|
#apifyClient;
|
|
27
42
|
#configuration;
|
|
28
|
-
|
|
43
|
+
#getCurrentRun;
|
|
44
|
+
#getCurrentActor;
|
|
45
|
+
constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
|
|
29
46
|
this.#configuration = configuration;
|
|
30
47
|
this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
|
|
31
48
|
this.#isAtHome = configuration.isAtHome;
|
|
@@ -33,11 +50,17 @@ export class ChargingManager {
|
|
|
33
50
|
this.#purgeChargingLogDataset = configuration.purgeOnStart;
|
|
34
51
|
this.#useChargingLogDataset = configuration.useChargingLogDataset;
|
|
35
52
|
this.#apifyClient = apifyClient;
|
|
53
|
+
this.#getCurrentRun = getCurrentRun;
|
|
54
|
+
this.#getCurrentActor = getCurrentActor;
|
|
36
55
|
}
|
|
37
56
|
/** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
|
|
38
57
|
get isPayPerEvent() {
|
|
39
58
|
return this.#pricingModel === 'PAY_PER_EVENT';
|
|
40
59
|
}
|
|
60
|
+
/** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
|
|
61
|
+
get isMultiTenant() {
|
|
62
|
+
return this.#isMultiTenant;
|
|
63
|
+
}
|
|
41
64
|
async fetchPricingInfo() {
|
|
42
65
|
if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
|
|
43
66
|
return {
|
|
@@ -50,10 +73,22 @@ export class ChargingManager {
|
|
|
50
73
|
if (this.#actorRunId === undefined) {
|
|
51
74
|
throw new Error('Actor run ID not found even though the Actor is running on Apify');
|
|
52
75
|
}
|
|
53
|
-
const run = await this.#
|
|
76
|
+
const run = await this.#getCurrentRun();
|
|
54
77
|
if (run === undefined) {
|
|
55
78
|
throw new Error('Actor run not found');
|
|
56
79
|
}
|
|
80
|
+
if (run.standby?.deployment.startsWith('MULTI_TENANT')) {
|
|
81
|
+
const actor = await this.#getCurrentActor();
|
|
82
|
+
if (actor === undefined) {
|
|
83
|
+
throw new Error('Actor not found');
|
|
84
|
+
}
|
|
85
|
+
this.#isMultiTenant = true;
|
|
86
|
+
return {
|
|
87
|
+
pricingInfo: getEffectivePricingInfo(actor.pricingInfos ?? []),
|
|
88
|
+
chargedEventCounts: {}, // the run's counts mix all callers
|
|
89
|
+
maxTotalChargeUsd: Infinity, // the platform prices and limits per caller
|
|
90
|
+
};
|
|
91
|
+
}
|
|
57
92
|
return {
|
|
58
93
|
pricingInfo: run.pricingInfo,
|
|
59
94
|
chargedEventCounts: run.chargedEventCounts,
|
|
@@ -165,9 +200,13 @@ export class ChargingManager {
|
|
|
165
200
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
166
201
|
* and avoids situations where more work is requested than the budget allows.
|
|
167
202
|
*
|
|
203
|
+
* **Note:** `idempotencyKey` is scoped to the whole run, not to `requestId`. In a multi-tenant
|
|
204
|
+
* Server Actor run, a key reused across requests charges only the first caller, so it must
|
|
205
|
+
* be globally unique (e.g. derived from `requestId`).
|
|
206
|
+
*
|
|
168
207
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
169
208
|
*/
|
|
170
|
-
async charge({ eventName, count = 1, idempotencyKey }) {
|
|
209
|
+
async charge({ eventName, count = 1, idempotencyKey, requestId }) {
|
|
171
210
|
if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
|
|
172
211
|
throw new Error('idempotencyKey must not be blank');
|
|
173
212
|
}
|
|
@@ -182,6 +221,9 @@ export class ChargingManager {
|
|
|
182
221
|
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
183
222
|
};
|
|
184
223
|
}
|
|
224
|
+
if (this.#isMultiTenant) {
|
|
225
|
+
return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
|
|
226
|
+
}
|
|
185
227
|
// Match the Python SDK: a non-positive count never reaches the platform and never
|
|
186
228
|
// mutates local charge state (a negative count would otherwise decrement the budget).
|
|
187
229
|
if (count <= 0) {
|
|
@@ -249,6 +291,7 @@ export class ChargingManager {
|
|
|
249
291
|
eventName,
|
|
250
292
|
count: chargedCount,
|
|
251
293
|
idempotencyKey,
|
|
294
|
+
requestId,
|
|
252
295
|
});
|
|
253
296
|
}
|
|
254
297
|
else {
|
|
@@ -275,6 +318,7 @@ export class ChargingManager {
|
|
|
275
318
|
eventPriceUsd: pricingInfo.price,
|
|
276
319
|
chargedCount,
|
|
277
320
|
idempotencyKey,
|
|
321
|
+
requestId,
|
|
278
322
|
timestamp: new Date().toISOString(),
|
|
279
323
|
});
|
|
280
324
|
}
|
|
@@ -289,6 +333,35 @@ export class ChargingManager {
|
|
|
289
333
|
};
|
|
290
334
|
});
|
|
291
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
|
|
338
|
+
* locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
|
|
339
|
+
* run, even by another caller.
|
|
340
|
+
*/
|
|
341
|
+
async chargeServerRequest(eventName, count, idempotencyKey, requestId) {
|
|
342
|
+
if (eventName.startsWith('apify-')) {
|
|
343
|
+
throw new Error(`Cannot charge for synthetic event '${eventName}' in a multi-tenant Server Actor run`);
|
|
344
|
+
}
|
|
345
|
+
if (!requestId) {
|
|
346
|
+
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().`);
|
|
347
|
+
}
|
|
348
|
+
let chargedCount = 0;
|
|
349
|
+
if (count <= 0) {
|
|
350
|
+
// Nothing to charge.
|
|
351
|
+
}
|
|
352
|
+
else if (this.#pricingInfo[eventName] === undefined) {
|
|
353
|
+
log.warning(`Attempting to charge for an unknown event '${eventName}'`);
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
await this.#apifyClient.run(this.#actorRunId).charge({ eventName, count, idempotencyKey, requestId });
|
|
357
|
+
chargedCount = count;
|
|
358
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
eventChargeLimitReached: false,
|
|
361
|
+
chargedCount,
|
|
362
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
292
365
|
getIdempotentCharge(idempotencyKey) {
|
|
293
366
|
const charge = this.#idempotentCharges.get(idempotencyKey);
|
|
294
367
|
if (charge !== undefined && charge.expiresAt <= Date.now()) {
|
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -12,4 +12,4 @@ export * from './proxy_configuration.js';
|
|
|
12
12
|
export * from './platform_event_manager.js';
|
|
13
13
|
export { Dataset, DatasetDataOptions, DatasetIteratorOptions, DatasetConsumer, DatasetMapper, DatasetReducer, DatasetOptions, DatasetContent, RequestQueue, RequestQueueOperationOptions, RequestQueueOptions, KeyValueStore, KeyConsumer, KeyValueStoreOptions, RecordOptions, KeyValueStoreIteratorOptions, log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
|
|
14
14
|
export type { QueueOperationInfo } from '@crawlee/types';
|
|
15
|
-
export { ApifyClient, ApifyClientOptions, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
|
15
|
+
export { ApifyClient, ApifyClientOptions, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
package/dist/index.js
CHANGED
|
@@ -9,4 +9,4 @@ export * from './configuration.js';
|
|
|
9
9
|
export * from './proxy_configuration.js';
|
|
10
10
|
export * from './platform_event_manager.js';
|
|
11
11
|
export { Dataset, RequestQueue, KeyValueStore, log, Log, LogLevel, Logger, LoggerJson, LoggerText, } from '@crawlee/core';
|
|
12
|
-
export { ApifyClient, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
|
12
|
+
export { ApifyClient, ApifyClientError, ApifyApiError, InvalidRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, InvalidResponseBodyError, ResponseValidationError, } from 'apify-client';
|
|
@@ -231,7 +231,7 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
|
|
|
231
231
|
return;
|
|
232
232
|
try {
|
|
233
233
|
const user = await Actor.apifyClient.user().get();
|
|
234
|
-
this.#password = user?.proxy?.password;
|
|
234
|
+
this.#password = user?.proxy?.password ?? undefined;
|
|
235
235
|
}
|
|
236
236
|
catch (error) {
|
|
237
237
|
if (Actor.isAtHome()) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apify",
|
|
3
|
-
"version": "4.0.0-beta.
|
|
3
|
+
"version": "4.0.0-beta.102",
|
|
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": ">=22.13.0"
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"@crawlee/fs-storage": "4.0.0-rc.2",
|
|
66
66
|
"@crawlee/types": "4.0.0-rc.2",
|
|
67
67
|
"@crawlee/utils": "4.0.0-rc.2",
|
|
68
|
-
"apify-client": "^3.0.0-rc.
|
|
68
|
+
"apify-client": "^3.0.0-rc.1",
|
|
69
69
|
"minimatch": "^11.0.5",
|
|
70
70
|
"tslib": "^2.9.1",
|
|
71
71
|
"ws": "^8.22.2",
|