apify 4.0.0-beta.13 → 4.0.0-beta.131
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/README.md +24 -2
- package/dist/actor.d.ts +391 -279
- package/dist/actor.js +732 -415
- package/dist/apify_dataset_backend.d.ts +19 -0
- package/dist/apify_dataset_backend.js +77 -0
- package/dist/apify_file_system_storage_backend.d.ts +34 -0
- package/dist/apify_file_system_storage_backend.js +41 -0
- package/dist/apify_key_value_store_backend.d.ts +23 -0
- package/dist/apify_key_value_store_backend.js +56 -0
- package/dist/apify_request_queue_backend.d.ts +78 -0
- package/dist/apify_request_queue_backend.js +114 -0
- package/dist/apify_request_queue_shared_backend.d.ts +31 -0
- package/dist/apify_request_queue_shared_backend.js +193 -0
- package/dist/apify_request_queue_single_backend.d.ts +43 -0
- package/dist/apify_request_queue_single_backend.js +256 -0
- package/dist/apify_storage_backend.d.ts +90 -0
- package/dist/apify_storage_backend.js +210 -0
- package/dist/charging.d.ts +69 -46
- package/dist/charging.js +326 -208
- package/dist/charging_storage_backend.d.ts +53 -0
- package/dist/charging_storage_backend.js +109 -0
- package/dist/child_run_tracker.d.ts +88 -0
- package/dist/child_run_tracker.js +239 -0
- package/dist/configuration.d.ts +49 -28
- package/dist/configuration.js +67 -12
- package/dist/enqueue_links_filters.d.ts +29 -0
- package/dist/enqueue_links_filters.js +52 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +22 -0
- package/dist/google_sheets.d.ts +12 -0
- package/dist/google_sheets.js +26 -0
- package/dist/index.d.ts +11 -4
- package/dist/index.js +8 -3
- package/dist/input-schemas.d.ts +1 -1
- package/dist/platform_event_manager.d.ts +15 -5
- package/dist/platform_event_manager.js +185 -39
- package/dist/proxy_configuration.d.ts +31 -21
- package/dist/proxy_configuration.js +136 -79
- package/dist/smart_apify_storage_backend.d.ts +52 -0
- package/dist/smart_apify_storage_backend.js +73 -0
- package/dist/storage.d.ts +6 -26
- package/dist/storage.js +1 -79
- package/dist/utils.d.ts +28 -3
- package/dist/utils.js +59 -17
- package/package.json +38 -44
- package/dist/apify_storage_client.d.ts +0 -54
- package/dist/apify_storage_client.js +0 -152
- package/dist/key_value_store.d.ts +0 -21
- package/dist/key_value_store.js +0 -41
package/dist/charging.js
CHANGED
|
@@ -1,62 +1,102 @@
|
|
|
1
1
|
import { Dataset, KeyValueStore } from '@crawlee/core';
|
|
2
|
+
import { META_ORIGINS } from '@apify/consts';
|
|
2
3
|
import log from '@apify/log';
|
|
4
|
+
import { ReentrantAsyncLock } from './utils.js';
|
|
5
|
+
/** How long a charge is remembered by its idempotency key - the same as the platform's own records. */
|
|
6
|
+
const IDEMPOTENCY_KEY_TTL_MILLIS = 3 * 60 * 1000;
|
|
3
7
|
export const DEFAULT_DATASET_ITEM_EVENT = 'apify-default-dataset-item';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
/**
|
|
9
|
+
* The pricing history includes scheduled future changes, so the effective entry is the latest one
|
|
10
|
+
* with `startedAt <= now`, not the last one.
|
|
11
|
+
*
|
|
12
|
+
* Resolved once at init on purpose. A change kicking in mid-run only affects local event titles and
|
|
13
|
+
* "unknown event" warnings; the platform prices each charge from its own current pricing anyway.
|
|
14
|
+
*/
|
|
15
|
+
function getEffectivePricingInfo(pricingInfos, now = new Date()) {
|
|
16
|
+
return pricingInfos
|
|
17
|
+
.filter((info) => new Date(info.startedAt) <= now)
|
|
18
|
+
.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime())
|
|
19
|
+
.at(-1);
|
|
13
20
|
}
|
|
14
21
|
/**
|
|
15
22
|
* Handles pay-per-event charging.
|
|
16
23
|
*/
|
|
17
24
|
export class ChargingManager {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
25
|
+
#LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log';
|
|
26
|
+
#PLATFORM_CHARGING_LOG_DATASET_ID_KEY = 'CHARGING_LOG_DATASET_ID';
|
|
27
|
+
#maxTotalChargeUsd;
|
|
28
|
+
#isAtHome;
|
|
29
|
+
#actorRunId;
|
|
30
|
+
#pricingModel;
|
|
31
|
+
/** Multi-tenant Server Actor runs carry no pricing snapshot; pricing comes from the Actor and the platform prices per caller. */
|
|
32
|
+
#isMultiTenant = false;
|
|
33
|
+
#purgeChargingLogDataset;
|
|
34
|
+
#useChargingLogDataset;
|
|
35
|
+
#notPpeWarningPrinted = false;
|
|
36
|
+
#pricingInfo = {};
|
|
37
|
+
#chargingState;
|
|
38
|
+
#chargingLogDataset;
|
|
39
|
+
/** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
|
|
40
|
+
#idempotentCharges = new Map();
|
|
41
|
+
#chargeLock = new ReentrantAsyncLock();
|
|
42
|
+
#apifyClient;
|
|
43
|
+
#configuration;
|
|
44
|
+
#getCurrentRun;
|
|
45
|
+
#getCurrentActor;
|
|
46
|
+
constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
|
|
47
|
+
this.#configuration = configuration;
|
|
48
|
+
this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
|
|
49
|
+
this.#isAtHome = configuration.isAtHome;
|
|
50
|
+
this.#actorRunId = configuration.actorRunId;
|
|
51
|
+
this.#purgeChargingLogDataset = configuration.purgeOnStart;
|
|
52
|
+
this.#useChargingLogDataset = configuration.useChargingLogDataset;
|
|
53
|
+
this.#apifyClient = apifyClient;
|
|
54
|
+
this.#getCurrentRun = getCurrentRun;
|
|
55
|
+
this.#getCurrentActor = getCurrentActor;
|
|
40
56
|
}
|
|
57
|
+
/** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
|
|
41
58
|
get isPayPerEvent() {
|
|
42
|
-
return this
|
|
59
|
+
return this.#pricingModel === 'PAY_PER_EVENT';
|
|
60
|
+
}
|
|
61
|
+
/** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
|
|
62
|
+
get isMultiTenant() {
|
|
63
|
+
return this.#isMultiTenant;
|
|
43
64
|
}
|
|
44
65
|
async fetchPricingInfo() {
|
|
45
|
-
if (this
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
66
|
+
if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
|
|
67
|
+
const pricingInfo = JSON.parse(this.#configuration.actorPricingInfo);
|
|
68
|
+
// Multi-tenant runs get an empty snapshot (`{}`); only the run tells them apart from free Server Actor runs.
|
|
69
|
+
const isMultiTenantCandidate = pricingInfo.pricingModel === undefined &&
|
|
70
|
+
this.#isAtHome &&
|
|
71
|
+
this.#configuration.metaOrigin === META_ORIGINS.STANDBY;
|
|
72
|
+
if (!isMultiTenantCandidate) {
|
|
73
|
+
return {
|
|
74
|
+
pricingInfo,
|
|
75
|
+
chargedEventCounts: JSON.parse(this.#configuration.chargedEventCounts),
|
|
76
|
+
maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
51
79
|
}
|
|
52
|
-
if (this
|
|
53
|
-
if (this
|
|
80
|
+
if (this.#isAtHome) {
|
|
81
|
+
if (this.#actorRunId === undefined) {
|
|
54
82
|
throw new Error('Actor run ID not found even though the Actor is running on Apify');
|
|
55
83
|
}
|
|
56
|
-
const run = await this
|
|
84
|
+
const run = await this.#getCurrentRun();
|
|
57
85
|
if (run === undefined) {
|
|
58
86
|
throw new Error('Actor run not found');
|
|
59
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
|
+
}
|
|
60
100
|
return {
|
|
61
101
|
pricingInfo: run.pricingInfo,
|
|
62
102
|
chargedEventCounts: run.chargedEventCounts,
|
|
@@ -66,7 +106,7 @@ export class ChargingManager {
|
|
|
66
106
|
return {
|
|
67
107
|
pricingInfo: undefined,
|
|
68
108
|
chargedEventCounts: {},
|
|
69
|
-
maxTotalChargeUsd: this
|
|
109
|
+
maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
|
|
70
110
|
};
|
|
71
111
|
}
|
|
72
112
|
/**
|
|
@@ -74,77 +114,84 @@ export class ChargingManager {
|
|
|
74
114
|
*/
|
|
75
115
|
async init() {
|
|
76
116
|
// Validate config - it may have changed since the instantiation
|
|
77
|
-
if (this
|
|
117
|
+
if (this.#useChargingLogDataset && this.#isAtHome) {
|
|
78
118
|
throw new Error('Using the ACTOR_USE_CHARGING_LOG_DATASET environment variable is only supported in a local development environment');
|
|
79
119
|
}
|
|
80
|
-
if (this
|
|
81
|
-
if (this
|
|
120
|
+
if (this.#configuration.testPayPerEvent) {
|
|
121
|
+
if (this.#isAtHome) {
|
|
82
122
|
throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
|
|
83
123
|
}
|
|
84
124
|
}
|
|
85
125
|
// Retrieve pricing information
|
|
86
126
|
const { pricingInfo, chargedEventCounts, maxTotalChargeUsd } = await this.fetchPricingInfo();
|
|
87
|
-
if (this
|
|
88
|
-
this
|
|
127
|
+
if (this.#configuration.testPayPerEvent) {
|
|
128
|
+
this.#pricingModel = 'PAY_PER_EVENT';
|
|
89
129
|
}
|
|
90
130
|
else {
|
|
91
|
-
this
|
|
131
|
+
this.#pricingModel ??= pricingInfo?.pricingModel;
|
|
92
132
|
}
|
|
93
133
|
// Load per-event pricing information
|
|
94
134
|
if (pricingInfo?.pricingModel === 'PAY_PER_EVENT') {
|
|
95
|
-
for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents)) {
|
|
96
|
-
this
|
|
97
|
-
price: eventPricing.eventPriceUsd,
|
|
135
|
+
for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents ?? {})) {
|
|
136
|
+
this.#pricingInfo[eventName] = {
|
|
137
|
+
price: eventPricing.eventPriceUsd ?? 0,
|
|
98
138
|
title: eventPricing.eventTitle,
|
|
99
139
|
};
|
|
100
140
|
}
|
|
101
|
-
this
|
|
141
|
+
this.#maxTotalChargeUsd = maxTotalChargeUsd;
|
|
102
142
|
}
|
|
103
|
-
this
|
|
143
|
+
this.#chargingState = {};
|
|
104
144
|
for (const [eventName, chargeCount] of Object.entries(chargedEventCounts ?? {})) {
|
|
105
|
-
this
|
|
145
|
+
this.#chargingState[eventName] = {
|
|
106
146
|
chargeCount,
|
|
107
|
-
totalChargedAmount: chargeCount * (this
|
|
147
|
+
totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
|
|
108
148
|
};
|
|
109
149
|
}
|
|
110
|
-
if (!this.isPayPerEvent || !this
|
|
150
|
+
if (!this.isPayPerEvent || !this.#useChargingLogDataset) {
|
|
111
151
|
return;
|
|
112
152
|
}
|
|
113
153
|
// Set up charging log dataset
|
|
114
|
-
if (this
|
|
154
|
+
if (this.#isAtHome) {
|
|
115
155
|
const datasetId = await this.ensureChargingLogDatasetOnPlatform();
|
|
116
|
-
this
|
|
156
|
+
this.#chargingLogDataset = await Dataset.open(datasetId);
|
|
117
157
|
}
|
|
118
158
|
else {
|
|
119
|
-
if (this
|
|
120
|
-
const dataset = await Dataset.open(this
|
|
159
|
+
if (this.#purgeChargingLogDataset) {
|
|
160
|
+
const dataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
|
|
121
161
|
await dataset.drop();
|
|
122
162
|
}
|
|
123
|
-
this
|
|
163
|
+
this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
|
|
124
164
|
}
|
|
125
165
|
}
|
|
126
166
|
async ensureChargingLogDatasetOnPlatform() {
|
|
127
167
|
const defaultStore = await KeyValueStore.open();
|
|
128
|
-
const storedDatasetId = await defaultStore.getValue(this
|
|
168
|
+
const storedDatasetId = await defaultStore.getValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY);
|
|
129
169
|
if (storedDatasetId !== null) {
|
|
130
170
|
return storedDatasetId;
|
|
131
171
|
}
|
|
132
|
-
const dataset = await this
|
|
133
|
-
await defaultStore.setValue(this
|
|
172
|
+
const dataset = await this.#apifyClient.datasets().getOrCreate();
|
|
173
|
+
await defaultStore.setValue(this.#PLATFORM_CHARGING_LOG_DATASET_ID_KEY, dataset.id);
|
|
134
174
|
return dataset.id;
|
|
135
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Whether {@link ChargingManager.init} has run. All charging operations (including
|
|
178
|
+
* {@link ChargingManager.getPricingInfo}) require an initialized manager.
|
|
179
|
+
*/
|
|
180
|
+
get isInitialized() {
|
|
181
|
+
return this.#chargingState !== undefined;
|
|
182
|
+
}
|
|
136
183
|
/**
|
|
137
184
|
* Get information about the pricing for this Actor.
|
|
138
185
|
*/
|
|
139
186
|
getPricingInfo() {
|
|
140
|
-
if (this
|
|
187
|
+
if (this.#chargingState === undefined) {
|
|
141
188
|
throw new Error('ChargingManager is not initialized');
|
|
142
189
|
}
|
|
143
190
|
return {
|
|
144
|
-
pricingModel: this
|
|
191
|
+
pricingModel: this.#pricingModel,
|
|
145
192
|
isPayPerEvent: this.isPayPerEvent,
|
|
146
|
-
maxTotalChargeUsd: this
|
|
147
|
-
perEventPrices: Object.fromEntries(Object.entries(this
|
|
193
|
+
maxTotalChargeUsd: this.#maxTotalChargeUsd,
|
|
194
|
+
perEventPrices: Object.fromEntries(Object.entries(this.#pricingInfo).map(([eventName, { price }]) => [eventName, price])),
|
|
148
195
|
};
|
|
149
196
|
}
|
|
150
197
|
/**
|
|
@@ -161,111 +208,210 @@ export class ChargingManager {
|
|
|
161
208
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
162
209
|
* and avoids situations where more work is requested than the budget allows.
|
|
163
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
|
+
*
|
|
164
215
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
165
216
|
*/
|
|
166
|
-
async charge({ eventName, count = 1 }) {
|
|
167
|
-
|
|
217
|
+
async charge({ eventName, count = 1, idempotencyKey, requestId }) {
|
|
218
|
+
if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
|
|
219
|
+
throw new Error('idempotencyKey must not be blank');
|
|
220
|
+
}
|
|
168
221
|
if (!this.isPayPerEvent) {
|
|
169
|
-
if (!this
|
|
222
|
+
if (!this.#notPpeWarningPrinted) {
|
|
170
223
|
log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
|
|
171
|
-
this
|
|
224
|
+
this.#notPpeWarningPrinted = true;
|
|
172
225
|
}
|
|
173
226
|
return {
|
|
174
227
|
eventChargeLimitReached: false,
|
|
175
228
|
chargedCount: 0,
|
|
176
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
229
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
177
230
|
};
|
|
178
231
|
}
|
|
179
|
-
if (this
|
|
180
|
-
|
|
232
|
+
if (this.#isMultiTenant) {
|
|
233
|
+
return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
|
|
181
234
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (count <= maxEventChargeCount) {
|
|
186
|
-
return count;
|
|
187
|
-
}
|
|
188
|
-
// If the caller tries to charge more than the budget allows, overcharge by one event
|
|
189
|
-
// so that the Actor is detected by the platform and terminated.
|
|
190
|
-
// But don't do this if already strictly over the budget - no point piling on charges.
|
|
191
|
-
if (this.calculateTotalChargedAmount() <= this.maxTotalChargeUsd) {
|
|
192
|
-
return maxEventChargeCount + 1;
|
|
193
|
-
}
|
|
194
|
-
return 0;
|
|
195
|
-
})();
|
|
196
|
-
if (chargedCount === 0) {
|
|
235
|
+
// Match the Python SDK: a non-positive count never reaches the platform and never
|
|
236
|
+
// mutates local charge state (a negative count would otherwise decrement the budget).
|
|
237
|
+
if (count <= 0) {
|
|
197
238
|
return {
|
|
198
|
-
eventChargeLimitReached:
|
|
239
|
+
eventChargeLimitReached: false,
|
|
199
240
|
chargedCount: 0,
|
|
200
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
241
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
201
242
|
};
|
|
202
243
|
}
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
207
|
-
this.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
244
|
+
const chargingState = this.#chargingState;
|
|
245
|
+
if (chargingState === undefined) {
|
|
246
|
+
throw new Error('ChargingManager is not initialized');
|
|
247
|
+
}
|
|
248
|
+
return await this.withChargeLock(async () => {
|
|
249
|
+
// A repeat the platform would discard is resolved here too - counting it would inflate the charging state
|
|
250
|
+
// and make the run hit `maxTotalChargeUsd` early. The key alone decides, as on the platform.
|
|
251
|
+
const previous = idempotencyKey === undefined ? undefined : this.getIdempotentCharge(idempotencyKey);
|
|
252
|
+
if (previous !== undefined) {
|
|
253
|
+
let repeatedCount;
|
|
254
|
+
if (previous.eventName === eventName) {
|
|
255
|
+
log.debug(`Skipped a repeated charge of event '${eventName}' under key '${idempotencyKey}'.`);
|
|
256
|
+
repeatedCount = previous.chargedCount;
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
log.warning(`Idempotency key '${idempotencyKey}' was already used to charge for event '${previous.eventName}', so the charge of event '${eventName}' is skipped.`);
|
|
260
|
+
repeatedCount = 0;
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
|
|
264
|
+
chargedCount: repeatedCount,
|
|
265
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
266
|
+
};
|
|
218
267
|
}
|
|
219
|
-
|
|
220
|
-
|
|
268
|
+
const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
|
|
269
|
+
const chargedCount = (() => {
|
|
270
|
+
if (count <= maxEventChargeCount) {
|
|
271
|
+
return count;
|
|
272
|
+
}
|
|
273
|
+
// If the caller tries to charge more than the budget allows, overcharge by one event
|
|
274
|
+
// so that the Actor is detected by the platform and terminated.
|
|
275
|
+
// But don't do this if already strictly over the budget - no point piling on charges.
|
|
276
|
+
if (this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd) {
|
|
277
|
+
return maxEventChargeCount + 1;
|
|
278
|
+
}
|
|
279
|
+
return 0;
|
|
280
|
+
})();
|
|
281
|
+
if (chargedCount === 0) {
|
|
282
|
+
return {
|
|
283
|
+
eventChargeLimitReached: count > 0, // Only true if user wanted to charge but couldn't
|
|
284
|
+
chargedCount: 0,
|
|
285
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
286
|
+
};
|
|
221
287
|
}
|
|
222
|
-
|
|
223
|
-
|
|
288
|
+
const pricingInfo = this.#pricingInfo[eventName] ?? {
|
|
289
|
+
price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
|
|
290
|
+
title: `Unknown event '${eventName}'`,
|
|
291
|
+
};
|
|
292
|
+
if (this.#isAtHome) {
|
|
293
|
+
if (eventName.startsWith('apify-')) {
|
|
294
|
+
// Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
|
|
295
|
+
// the platform handles them automatically based on dataset writes.
|
|
296
|
+
}
|
|
297
|
+
else if (this.#pricingInfo[eventName] !== undefined) {
|
|
298
|
+
await this.#apifyClient.run(this.#actorRunId).charge({
|
|
299
|
+
eventName,
|
|
300
|
+
count: chargedCount,
|
|
301
|
+
idempotencyKey,
|
|
302
|
+
requestId,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
log.warning(`Attempting to charge for an unknown event '${eventName}'`);
|
|
307
|
+
}
|
|
224
308
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
309
|
+
// Count the charge only after the API call succeeds, so a failed call retried under the same key
|
|
310
|
+
// is counted once.
|
|
311
|
+
chargingState[eventName] ??= {
|
|
312
|
+
chargeCount: 0,
|
|
313
|
+
totalChargedAmount: 0,
|
|
314
|
+
};
|
|
315
|
+
chargingState[eventName].chargeCount += chargedCount;
|
|
316
|
+
chargingState[eventName].totalChargedAmount += chargedCount * pricingInfo.price;
|
|
317
|
+
// Remember the key for every charge that was counted, including events the API never receives,
|
|
318
|
+
// such as synthetic ones - those are counted locally and a repeat would count them twice.
|
|
319
|
+
if (idempotencyKey !== undefined) {
|
|
320
|
+
this.setIdempotentCharge(idempotencyKey, { eventName, chargedCount });
|
|
321
|
+
}
|
|
322
|
+
if (this.#chargingLogDataset !== undefined) {
|
|
323
|
+
await this.#chargingLogDataset.pushData({
|
|
324
|
+
eventName,
|
|
325
|
+
eventTitle: pricingInfo.title,
|
|
326
|
+
eventPriceUsd: pricingInfo.price,
|
|
327
|
+
chargedCount,
|
|
328
|
+
idempotencyKey,
|
|
329
|
+
requestId,
|
|
330
|
+
timestamp: new Date().toISOString(),
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
if (chargedCount < count) {
|
|
334
|
+
const subject = count === 1 ? 'instance' : 'instances';
|
|
335
|
+
log.info(`Charging ${count} ${subject} of '${eventName}' event would exceed maxTotalChargeUsd - only ${chargedCount} events were charged`);
|
|
336
|
+
}
|
|
337
|
+
return {
|
|
338
|
+
eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
|
|
232
339
|
chargedCount,
|
|
233
|
-
|
|
234
|
-
}
|
|
340
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
341
|
+
};
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* The platform prices, limits and deduplicates each caller's charges itself, so nothing is counted or enforced
|
|
346
|
+
* locally, and every call is sent - the platform discards a repeat under an idempotency key used earlier in the
|
|
347
|
+
* run, even by another caller.
|
|
348
|
+
*/
|
|
349
|
+
async chargeServerRequest(eventName, count, idempotencyKey, requestId) {
|
|
350
|
+
if (eventName.startsWith('apify-')) {
|
|
351
|
+
throw new Error(`Cannot charge for synthetic event '${eventName}' in a multi-tenant Server Actor run`);
|
|
235
352
|
}
|
|
236
|
-
if (
|
|
237
|
-
|
|
238
|
-
|
|
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;
|
|
239
366
|
}
|
|
240
367
|
return {
|
|
241
|
-
eventChargeLimitReached:
|
|
368
|
+
eventChargeLimitReached: false,
|
|
242
369
|
chargedCount,
|
|
243
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
370
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
244
371
|
};
|
|
245
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
|
+
}
|
|
246
392
|
/**
|
|
247
393
|
* Get the number of events with given name that the Actor has charged for so far.
|
|
248
394
|
*/
|
|
249
395
|
getChargedEventCount(eventName) {
|
|
250
|
-
if (this
|
|
396
|
+
if (this.#chargingState === undefined) {
|
|
251
397
|
throw new Error('ChargingManager is not initialized');
|
|
252
398
|
}
|
|
253
|
-
return this
|
|
399
|
+
return this.#chargingState[eventName]?.chargeCount ?? 0;
|
|
254
400
|
}
|
|
255
401
|
/**
|
|
256
402
|
* Get the maximum amount of money that the Actor is allowed to charge.
|
|
257
403
|
*/
|
|
258
404
|
getMaxTotalChargeUsd() {
|
|
259
|
-
if (this
|
|
405
|
+
if (this.#chargingState === undefined) {
|
|
260
406
|
throw new Error('ChargingManager is not initialized');
|
|
261
407
|
}
|
|
262
|
-
return this
|
|
408
|
+
return this.#maxTotalChargeUsd;
|
|
263
409
|
}
|
|
264
410
|
calculateTotalChargedAmount() {
|
|
265
|
-
if (this
|
|
411
|
+
if (this.#chargingState === undefined) {
|
|
266
412
|
throw new Error('ChargingManager is not initialized');
|
|
267
413
|
}
|
|
268
|
-
const result = Object.values(this
|
|
414
|
+
const result = Object.values(this.#chargingState)
|
|
269
415
|
.map(({ totalChargedAmount }) => totalChargedAmount)
|
|
270
416
|
.reduce((sum, inc) => sum + inc, 0);
|
|
271
417
|
// Keeping float precision issues at bay
|
|
@@ -276,7 +422,7 @@ export class ChargingManager {
|
|
|
276
422
|
* If the event is not registered, returns Infinity (free of charge)
|
|
277
423
|
*/
|
|
278
424
|
calculateMaxEventChargeCountWithinLimit(eventName) {
|
|
279
|
-
if (this
|
|
425
|
+
if (this.#chargingState === undefined) {
|
|
280
426
|
throw new Error('ChargingManager is not initialized');
|
|
281
427
|
}
|
|
282
428
|
const price = this.calculateEventPrice(eventName);
|
|
@@ -286,96 +432,68 @@ export class ChargingManager {
|
|
|
286
432
|
return this.calculateMaxChargesByPrice(price);
|
|
287
433
|
}
|
|
288
434
|
calculateEventPrice(eventName) {
|
|
289
|
-
return this
|
|
435
|
+
return this.#isAtHome ? this.#pricingInfo[eventName]?.price : 1; // Use a nonzero price for local development so that the maximum budget can be reached
|
|
290
436
|
}
|
|
291
437
|
calculateMaxChargesByPrice(price) {
|
|
292
438
|
// The raw number of events allowed by the budget
|
|
293
|
-
const unroundedResult = (this
|
|
439
|
+
const unroundedResult = (this.#maxTotalChargeUsd - this.calculateTotalChargedAmount()) / price;
|
|
294
440
|
// First round as Math.floor(4.9999999999999999) will incorrectly return 5
|
|
295
441
|
const roundedResult = Math.floor(Number(unroundedResult.toFixed(4)));
|
|
296
442
|
return Math.max(0, roundedResult);
|
|
297
443
|
}
|
|
298
444
|
/**
|
|
299
|
-
*
|
|
300
|
-
*
|
|
445
|
+
* Whether the remaining budget is insufficient to charge even a single event of the given type.
|
|
446
|
+
* Always false when nothing is charged in the first place.
|
|
301
447
|
*/
|
|
302
|
-
|
|
303
|
-
|
|
448
|
+
isEventChargeLimitReached(eventName) {
|
|
449
|
+
return this.isPayPerEvent && this.calculateMaxEventChargeCountWithinLimit(eventName) <= 0;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* How many events of each known type can still be charged within the limit.
|
|
453
|
+
*/
|
|
454
|
+
calculateChargeableWithinLimit() {
|
|
455
|
+
return Object.fromEntries(Object.keys(this.#pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)]));
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* How many of `itemsCount` items may be pushed to a dataset within the remaining budget.
|
|
459
|
+
*
|
|
460
|
+
* The budget is measured against the combined per-item price of the explicit `eventName` and - on
|
|
461
|
+
* the default dataset - the synthetic {@link DEFAULT_DATASET_ITEM_EVENT}, since pushing one item
|
|
462
|
+
* charges both.
|
|
463
|
+
*
|
|
464
|
+
* When the budget cannot cover a single item, one item is still allowed through so that the
|
|
465
|
+
* resulting overcharge makes the platform terminate the run - unless the run is already strictly
|
|
466
|
+
* over budget, in which case nothing is allowed through.
|
|
467
|
+
*/
|
|
468
|
+
calculatePushDataLimit(itemsCount, { eventName, isDefaultDataset = false } = {}) {
|
|
469
|
+
if (this.#chargingState === undefined) {
|
|
304
470
|
throw new Error('ChargingManager is not initialized');
|
|
305
471
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
return {
|
|
309
|
-
limitedItems: itemsArray,
|
|
310
|
-
eventsToCharge: {},
|
|
311
|
-
};
|
|
472
|
+
if (!this.isPayPerEvent || itemsCount === 0) {
|
|
473
|
+
return itemsCount;
|
|
312
474
|
}
|
|
313
|
-
const itemPrice = (
|
|
314
|
-
(
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
if (maxChargedCount >= itemsArray.length) {
|
|
318
|
-
return itemsArray.length;
|
|
319
|
-
}
|
|
320
|
-
// If the caller tries to push items even though the limit is depleted, overcharge by one
|
|
321
|
-
// so that the Platform terminates the run.
|
|
322
|
-
// But don't do this if already strictly over the budget - no point piling on charges.
|
|
323
|
-
if (itemsArray.length > 0 &&
|
|
324
|
-
maxChargedCount === 0 &&
|
|
325
|
-
this.calculateTotalChargedAmount() <= this.maxTotalChargeUsd) {
|
|
326
|
-
return 1;
|
|
327
|
-
}
|
|
328
|
-
return maxChargedCount;
|
|
329
|
-
})();
|
|
330
|
-
const eventsToCharge = {};
|
|
331
|
-
if (eventName !== undefined && itemsToKeep > 0) {
|
|
332
|
-
eventsToCharge[eventName] = itemsToKeep;
|
|
475
|
+
const itemPrice = (eventName === undefined ? 0 : (this.calculateEventPrice(eventName) ?? 0)) +
|
|
476
|
+
(isDefaultDataset ? (this.calculateEventPrice(DEFAULT_DATASET_ITEM_EVENT) ?? 0) : 0);
|
|
477
|
+
if (itemPrice === 0) {
|
|
478
|
+
return itemsCount;
|
|
333
479
|
}
|
|
334
|
-
|
|
335
|
-
|
|
480
|
+
const maxChargedCount = this.calculateMaxChargesByPrice(itemPrice);
|
|
481
|
+
if (maxChargedCount >= itemsCount) {
|
|
482
|
+
return itemsCount;
|
|
336
483
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
/**
|
|
344
|
-
* Helper for PPE-aware pushing of data to the dataset.
|
|
345
|
-
*
|
|
346
|
-
* 1. Calculate limits based on budget
|
|
347
|
-
* 2. Push limited items via the provided callback
|
|
348
|
-
* 3. Charge for the events
|
|
349
|
-
*
|
|
350
|
-
* @internal
|
|
351
|
-
*/
|
|
352
|
-
export async function pushDataAndCharge({ chargingManager, items, eventName, isDefaultDataset, pushFn, }) {
|
|
353
|
-
const { limitedItems, eventsToCharge } = chargingManager.calculatePushDataLimits({
|
|
354
|
-
items,
|
|
355
|
-
eventName,
|
|
356
|
-
isDefaultDataset,
|
|
357
|
-
});
|
|
358
|
-
if (limitedItems.length > 0) {
|
|
359
|
-
// Preserve original call shape for single items
|
|
360
|
-
await pushFn(Array.isArray(items) ? limitedItems : limitedItems[0]);
|
|
484
|
+
if (maxChargedCount > 0) {
|
|
485
|
+
return maxChargedCount;
|
|
486
|
+
}
|
|
487
|
+
return this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd ? 1 : 0;
|
|
361
488
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
// whether ANY of the charged events hit their limit.
|
|
372
|
-
return Object.values(results).reduce(mergeChargeResults);
|
|
489
|
+
/**
|
|
490
|
+
* Runs `fn` under the charge lock, which keeps a limit reservation and the charge that acts on it
|
|
491
|
+
* atomic against concurrent pushes. Only pay-per-event runs charge anything, so for every other
|
|
492
|
+
* run there is nothing to serialize and the lock is skipped.
|
|
493
|
+
*
|
|
494
|
+
* @internal
|
|
495
|
+
*/
|
|
496
|
+
async withChargeLock(fn) {
|
|
497
|
+
return this.isPayPerEvent ? await this.#chargeLock.runExclusive(fn) : await fn();
|
|
373
498
|
}
|
|
374
|
-
const itemsArray = Array.isArray(items) ? items : [items];
|
|
375
|
-
const allItemsTrimmed = itemsArray.length > 0 && limitedItems.length === 0;
|
|
376
|
-
return {
|
|
377
|
-
eventChargeLimitReached: allItemsTrimmed,
|
|
378
|
-
chargedCount: 0,
|
|
379
|
-
chargeableWithinLimit: {},
|
|
380
|
-
};
|
|
381
499
|
}
|