apify 4.0.0-beta.14 → 4.0.0-beta.141
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 +28 -2
- package/dist/actor.d.ts +393 -281
- package/dist/actor.js +734 -417
- package/dist/apify_dataset_backend.d.ts +22 -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 +26 -0
- package/dist/apify_key_value_store_backend.js +57 -0
- package/dist/apify_request_queue_backend.d.ts +81 -0
- package/dist/apify_request_queue_backend.js +110 -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 -47
- package/dist/charging.js +321 -223
- 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 +48 -28
- package/dist/configuration.js +67 -13
- 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 +13 -4
- package/dist/index.js +8 -3
- package/dist/input-schemas.d.ts +1 -1
- package/dist/platform_event_manager.d.ts +24 -9
- package/dist/platform_event_manager.js +213 -43
- 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,99 @@
|
|
|
1
|
-
import { Dataset,
|
|
1
|
+
import { Dataset, withDirectStorageAccess } 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
|
-
purgeChargingLogDataset;
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this
|
|
39
|
-
this
|
|
25
|
+
#LOCAL_CHARGING_LOG_DATASET_NAME = 'charging-log';
|
|
26
|
+
#maxTotalChargeUsd;
|
|
27
|
+
#isAtHome;
|
|
28
|
+
#actorRunId;
|
|
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
|
+
#purgeChargingLogDataset;
|
|
33
|
+
#notPpeWarningPrinted = false;
|
|
34
|
+
#pricingInfo = {};
|
|
35
|
+
#chargingState;
|
|
36
|
+
#chargingLogDataset;
|
|
37
|
+
/** Charges made with an idempotency key, by key, in insertion (and therefore expiry) order. */
|
|
38
|
+
#idempotentCharges = new Map();
|
|
39
|
+
#chargeLock = new ReentrantAsyncLock();
|
|
40
|
+
#apifyClient;
|
|
41
|
+
#configuration;
|
|
42
|
+
#getCurrentRun;
|
|
43
|
+
#getCurrentActor;
|
|
44
|
+
constructor(configuration, apifyClient, getCurrentRun, getCurrentActor) {
|
|
45
|
+
this.#configuration = configuration;
|
|
46
|
+
this.#maxTotalChargeUsd = configuration.maxTotalChargeUsd || Infinity; // convert `0` to `Infinity` in case the value is an empty string
|
|
47
|
+
this.#isAtHome = configuration.isAtHome;
|
|
48
|
+
this.#actorRunId = configuration.actorRunId;
|
|
49
|
+
this.#purgeChargingLogDataset = configuration.purgeOnStart;
|
|
50
|
+
this.#apifyClient = apifyClient;
|
|
51
|
+
this.#getCurrentRun = getCurrentRun;
|
|
52
|
+
this.#getCurrentActor = getCurrentActor;
|
|
40
53
|
}
|
|
54
|
+
/** A shortcut - true if the Actor runs with the pay-per-event pricing model. */
|
|
41
55
|
get isPayPerEvent() {
|
|
42
|
-
return this
|
|
56
|
+
return this.#pricingModel === 'PAY_PER_EVENT';
|
|
57
|
+
}
|
|
58
|
+
/** True in a multi-tenant Server Actor run, which charges per request with `requestId` only. */
|
|
59
|
+
get isMultiTenant() {
|
|
60
|
+
return this.#isMultiTenant;
|
|
43
61
|
}
|
|
44
62
|
async fetchPricingInfo() {
|
|
45
|
-
if (this
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
63
|
+
if (this.#configuration.actorPricingInfo && this.#configuration.chargedEventCounts) {
|
|
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
|
+
}
|
|
51
76
|
}
|
|
52
|
-
if (this
|
|
53
|
-
if (this
|
|
77
|
+
if (this.#isAtHome) {
|
|
78
|
+
if (this.#actorRunId === undefined) {
|
|
54
79
|
throw new Error('Actor run ID not found even though the Actor is running on Apify');
|
|
55
80
|
}
|
|
56
|
-
const run = await this
|
|
81
|
+
const run = await this.#getCurrentRun();
|
|
57
82
|
if (run === undefined) {
|
|
58
83
|
throw new Error('Actor run not found');
|
|
59
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
|
+
}
|
|
60
97
|
return {
|
|
61
98
|
pricingInfo: run.pricingInfo,
|
|
62
99
|
chargedEventCounts: run.chargedEventCounts,
|
|
@@ -66,7 +103,7 @@ export class ChargingManager {
|
|
|
66
103
|
return {
|
|
67
104
|
pricingInfo: undefined,
|
|
68
105
|
chargedEventCounts: {},
|
|
69
|
-
maxTotalChargeUsd: this
|
|
106
|
+
maxTotalChargeUsd: this.#configuration.maxTotalChargeUsd || Infinity,
|
|
70
107
|
};
|
|
71
108
|
}
|
|
72
109
|
/**
|
|
@@ -74,77 +111,65 @@ export class ChargingManager {
|
|
|
74
111
|
*/
|
|
75
112
|
async init() {
|
|
76
113
|
// Validate config - it may have changed since the instantiation
|
|
77
|
-
if (this.
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
if (this.configuration.testPayPerEvent) {
|
|
81
|
-
if (this.isAtHome) {
|
|
114
|
+
if (this.#configuration.testPayPerEvent) {
|
|
115
|
+
if (this.#isAtHome) {
|
|
82
116
|
throw new Error('Using the ACTOR_TEST_PAY_PER_EVENT environment variable is only supported in a local development environment');
|
|
83
117
|
}
|
|
84
118
|
}
|
|
85
119
|
// Retrieve pricing information
|
|
86
120
|
const { pricingInfo, chargedEventCounts, maxTotalChargeUsd } = await this.fetchPricingInfo();
|
|
87
|
-
if (this
|
|
88
|
-
this
|
|
121
|
+
if (this.#configuration.testPayPerEvent) {
|
|
122
|
+
this.#pricingModel = 'PAY_PER_EVENT';
|
|
89
123
|
}
|
|
90
124
|
else {
|
|
91
|
-
this
|
|
125
|
+
this.#pricingModel ??= pricingInfo?.pricingModel;
|
|
92
126
|
}
|
|
93
127
|
// Load per-event pricing information
|
|
94
128
|
if (pricingInfo?.pricingModel === 'PAY_PER_EVENT') {
|
|
95
|
-
for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents)) {
|
|
96
|
-
this
|
|
97
|
-
price: eventPricing.eventPriceUsd,
|
|
129
|
+
for (const [eventName, eventPricing] of Object.entries(pricingInfo.pricingPerEvent.actorChargeEvents ?? {})) {
|
|
130
|
+
this.#pricingInfo[eventName] = {
|
|
131
|
+
price: eventPricing.eventPriceUsd ?? 0,
|
|
98
132
|
title: eventPricing.eventTitle,
|
|
99
133
|
};
|
|
100
134
|
}
|
|
101
|
-
this
|
|
135
|
+
this.#maxTotalChargeUsd = maxTotalChargeUsd;
|
|
102
136
|
}
|
|
103
|
-
this
|
|
137
|
+
this.#chargingState = {};
|
|
104
138
|
for (const [eventName, chargeCount] of Object.entries(chargedEventCounts ?? {})) {
|
|
105
|
-
this
|
|
139
|
+
this.#chargingState[eventName] = {
|
|
106
140
|
chargeCount,
|
|
107
|
-
totalChargedAmount: chargeCount * (this
|
|
141
|
+
totalChargedAmount: chargeCount * (this.#pricingInfo[eventName]?.price ?? 0),
|
|
108
142
|
};
|
|
109
143
|
}
|
|
110
|
-
if (
|
|
144
|
+
if (this.#isAtHome || !this.isPayPerEvent) {
|
|
111
145
|
return;
|
|
112
146
|
}
|
|
113
|
-
//
|
|
114
|
-
if (this
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
if (this.purgeChargingLogDataset) {
|
|
120
|
-
const dataset = await Dataset.open(this.LOCAL_CHARGING_LOG_DATASET_NAME);
|
|
121
|
-
await dataset.drop();
|
|
122
|
-
}
|
|
123
|
-
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();
|
|
124
151
|
}
|
|
152
|
+
this.#chargingLogDataset = await Dataset.open(this.#LOCAL_CHARGING_LOG_DATASET_NAME);
|
|
125
153
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
const dataset = await this.apifyClient.datasets().getOrCreate();
|
|
133
|
-
await defaultStore.setValue(this.PLATFORM_CHARGING_LOG_DATASET_ID_KEY, dataset.id);
|
|
134
|
-
return dataset.id;
|
|
154
|
+
/**
|
|
155
|
+
* Whether {@link ChargingManager.init} has run. All charging operations (including
|
|
156
|
+
* {@link ChargingManager.getPricingInfo}) require an initialized manager.
|
|
157
|
+
*/
|
|
158
|
+
get isInitialized() {
|
|
159
|
+
return this.#chargingState !== undefined;
|
|
135
160
|
}
|
|
136
161
|
/**
|
|
137
162
|
* Get information about the pricing for this Actor.
|
|
138
163
|
*/
|
|
139
164
|
getPricingInfo() {
|
|
140
|
-
if (this
|
|
165
|
+
if (this.#chargingState === undefined) {
|
|
141
166
|
throw new Error('ChargingManager is not initialized');
|
|
142
167
|
}
|
|
143
168
|
return {
|
|
144
|
-
pricingModel: this
|
|
169
|
+
pricingModel: this.#pricingModel,
|
|
145
170
|
isPayPerEvent: this.isPayPerEvent,
|
|
146
|
-
maxTotalChargeUsd: this
|
|
147
|
-
perEventPrices: Object.fromEntries(Object.entries(this
|
|
171
|
+
maxTotalChargeUsd: this.#maxTotalChargeUsd,
|
|
172
|
+
perEventPrices: Object.fromEntries(Object.entries(this.#pricingInfo).map(([eventName, { price }]) => [eventName, price])),
|
|
148
173
|
};
|
|
149
174
|
}
|
|
150
175
|
/**
|
|
@@ -161,111 +186,212 @@ export class ChargingManager {
|
|
|
161
186
|
* rather than batching via `count` — this gives finer control over budget consumption
|
|
162
187
|
* and avoids situations where more work is requested than the budget allows.
|
|
163
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
|
+
*
|
|
164
193
|
* @param options The name of the event to charge for and the number of events to be charged.
|
|
165
194
|
*/
|
|
166
|
-
async charge({ eventName, count = 1 }) {
|
|
167
|
-
|
|
195
|
+
async charge({ eventName, count = 1, idempotencyKey, requestId }) {
|
|
196
|
+
if (idempotencyKey !== undefined && idempotencyKey.trim() === '') {
|
|
197
|
+
throw new Error('idempotencyKey must not be blank');
|
|
198
|
+
}
|
|
168
199
|
if (!this.isPayPerEvent) {
|
|
169
|
-
if (!this
|
|
200
|
+
if (!this.#notPpeWarningPrinted) {
|
|
170
201
|
log.warning('Ignored attempt to charge for an event - the Actor does not use the pay-per-event pricing');
|
|
171
|
-
this
|
|
202
|
+
this.#notPpeWarningPrinted = true;
|
|
172
203
|
}
|
|
173
204
|
return {
|
|
174
205
|
eventChargeLimitReached: false,
|
|
175
206
|
chargedCount: 0,
|
|
176
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
207
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
177
208
|
};
|
|
178
209
|
}
|
|
179
|
-
if (this
|
|
180
|
-
|
|
210
|
+
if (this.#isMultiTenant) {
|
|
211
|
+
return await this.chargeServerRequest(eventName, count, idempotencyKey, requestId);
|
|
181
212
|
}
|
|
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) {
|
|
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) {
|
|
197
216
|
return {
|
|
198
|
-
eventChargeLimitReached:
|
|
217
|
+
eventChargeLimitReached: false,
|
|
199
218
|
chargedCount: 0,
|
|
200
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
219
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
201
220
|
};
|
|
202
221
|
}
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
207
|
-
this.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
222
|
+
const chargingState = this.#chargingState;
|
|
223
|
+
if (chargingState === undefined) {
|
|
224
|
+
throw new Error('ChargingManager is not initialized');
|
|
225
|
+
}
|
|
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
|
+
};
|
|
218
245
|
}
|
|
219
|
-
|
|
220
|
-
|
|
246
|
+
const maxEventChargeCount = this.calculateMaxEventChargeCountWithinLimit(eventName);
|
|
247
|
+
const chargedCount = (() => {
|
|
248
|
+
if (count <= maxEventChargeCount) {
|
|
249
|
+
return count;
|
|
250
|
+
}
|
|
251
|
+
// If the caller tries to charge more than the budget allows, overcharge by one event
|
|
252
|
+
// so that the Actor is detected by the platform and terminated.
|
|
253
|
+
// But don't do this if already strictly over the budget - no point piling on charges.
|
|
254
|
+
if (this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd) {
|
|
255
|
+
return maxEventChargeCount + 1;
|
|
256
|
+
}
|
|
257
|
+
return 0;
|
|
258
|
+
})();
|
|
259
|
+
if (chargedCount === 0) {
|
|
260
|
+
return {
|
|
261
|
+
eventChargeLimitReached: count > 0, // Only true if user wanted to charge but couldn't
|
|
262
|
+
chargedCount: 0,
|
|
263
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
264
|
+
};
|
|
221
265
|
}
|
|
222
|
-
|
|
223
|
-
|
|
266
|
+
const pricingInfo = this.#pricingInfo[eventName] ?? {
|
|
267
|
+
price: this.#isAtHome ? 0 : 1, // Use a nonzero price for local development so that the maximum budget can be reached
|
|
268
|
+
title: `Unknown event '${eventName}'`,
|
|
269
|
+
};
|
|
270
|
+
if (this.#isAtHome) {
|
|
271
|
+
if (eventName.startsWith('apify-')) {
|
|
272
|
+
// Synthetic events (e.g. apify-default-dataset-item) are tracked locally only,
|
|
273
|
+
// the platform handles them automatically based on dataset writes.
|
|
274
|
+
}
|
|
275
|
+
else if (this.#pricingInfo[eventName] !== undefined) {
|
|
276
|
+
await this.#apifyClient.run(this.#actorRunId).charge({
|
|
277
|
+
eventName,
|
|
278
|
+
count: chargedCount,
|
|
279
|
+
idempotencyKey,
|
|
280
|
+
requestId,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
log.warning(`Attempting to charge for an unknown event '${eventName}'`);
|
|
285
|
+
}
|
|
224
286
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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({
|
|
304
|
+
eventName,
|
|
305
|
+
eventTitle: pricingInfo.title,
|
|
306
|
+
eventPriceUsd: pricingInfo.price,
|
|
307
|
+
chargedCount,
|
|
308
|
+
idempotencyKey,
|
|
309
|
+
requestId,
|
|
310
|
+
timestamp: new Date().toISOString(),
|
|
311
|
+
}));
|
|
312
|
+
}
|
|
313
|
+
if (chargedCount < count) {
|
|
314
|
+
const subject = count === 1 ? 'instance' : 'instances';
|
|
315
|
+
log.info(`Charging ${count} ${subject} of '${eventName}' event would exceed maxTotalChargeUsd - only ${chargedCount} events were charged`);
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
eventChargeLimitReached: this.isEventChargeLimitReached(eventName),
|
|
232
319
|
chargedCount,
|
|
233
|
-
|
|
234
|
-
}
|
|
320
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
321
|
+
};
|
|
322
|
+
});
|
|
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.
|
|
235
339
|
}
|
|
236
|
-
if (
|
|
237
|
-
|
|
238
|
-
|
|
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;
|
|
239
346
|
}
|
|
240
347
|
return {
|
|
241
|
-
eventChargeLimitReached:
|
|
348
|
+
eventChargeLimitReached: false,
|
|
242
349
|
chargedCount,
|
|
243
|
-
chargeableWithinLimit: calculateChargeableWithinLimit(),
|
|
350
|
+
chargeableWithinLimit: this.calculateChargeableWithinLimit(),
|
|
244
351
|
};
|
|
245
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
|
+
}
|
|
246
372
|
/**
|
|
247
373
|
* Get the number of events with given name that the Actor has charged for so far.
|
|
248
374
|
*/
|
|
249
375
|
getChargedEventCount(eventName) {
|
|
250
|
-
if (this
|
|
376
|
+
if (this.#chargingState === undefined) {
|
|
251
377
|
throw new Error('ChargingManager is not initialized');
|
|
252
378
|
}
|
|
253
|
-
return this
|
|
379
|
+
return this.#chargingState[eventName]?.chargeCount ?? 0;
|
|
254
380
|
}
|
|
255
381
|
/**
|
|
256
382
|
* Get the maximum amount of money that the Actor is allowed to charge.
|
|
257
383
|
*/
|
|
258
384
|
getMaxTotalChargeUsd() {
|
|
259
|
-
if (this
|
|
385
|
+
if (this.#chargingState === undefined) {
|
|
260
386
|
throw new Error('ChargingManager is not initialized');
|
|
261
387
|
}
|
|
262
|
-
return this
|
|
388
|
+
return this.#maxTotalChargeUsd;
|
|
263
389
|
}
|
|
264
390
|
calculateTotalChargedAmount() {
|
|
265
|
-
if (this
|
|
391
|
+
if (this.#chargingState === undefined) {
|
|
266
392
|
throw new Error('ChargingManager is not initialized');
|
|
267
393
|
}
|
|
268
|
-
const result = Object.values(this
|
|
394
|
+
const result = Object.values(this.#chargingState)
|
|
269
395
|
.map(({ totalChargedAmount }) => totalChargedAmount)
|
|
270
396
|
.reduce((sum, inc) => sum + inc, 0);
|
|
271
397
|
// Keeping float precision issues at bay
|
|
@@ -276,7 +402,7 @@ export class ChargingManager {
|
|
|
276
402
|
* If the event is not registered, returns Infinity (free of charge)
|
|
277
403
|
*/
|
|
278
404
|
calculateMaxEventChargeCountWithinLimit(eventName) {
|
|
279
|
-
if (this
|
|
405
|
+
if (this.#chargingState === undefined) {
|
|
280
406
|
throw new Error('ChargingManager is not initialized');
|
|
281
407
|
}
|
|
282
408
|
const price = this.calculateEventPrice(eventName);
|
|
@@ -286,96 +412,68 @@ export class ChargingManager {
|
|
|
286
412
|
return this.calculateMaxChargesByPrice(price);
|
|
287
413
|
}
|
|
288
414
|
calculateEventPrice(eventName) {
|
|
289
|
-
return this
|
|
415
|
+
return this.#isAtHome ? this.#pricingInfo[eventName]?.price : 1; // Use a nonzero price for local development so that the maximum budget can be reached
|
|
290
416
|
}
|
|
291
417
|
calculateMaxChargesByPrice(price) {
|
|
292
418
|
// The raw number of events allowed by the budget
|
|
293
|
-
const unroundedResult = (this
|
|
419
|
+
const unroundedResult = (this.#maxTotalChargeUsd - this.calculateTotalChargedAmount()) / price;
|
|
294
420
|
// First round as Math.floor(4.9999999999999999) will incorrectly return 5
|
|
295
421
|
const roundedResult = Math.floor(Number(unroundedResult.toFixed(4)));
|
|
296
422
|
return Math.max(0, roundedResult);
|
|
297
423
|
}
|
|
298
424
|
/**
|
|
299
|
-
*
|
|
300
|
-
*
|
|
425
|
+
* Whether the remaining budget is insufficient to charge even a single event of the given type.
|
|
426
|
+
* Always false when nothing is charged in the first place.
|
|
301
427
|
*/
|
|
302
|
-
|
|
303
|
-
|
|
428
|
+
isEventChargeLimitReached(eventName) {
|
|
429
|
+
return this.isPayPerEvent && this.calculateMaxEventChargeCountWithinLimit(eventName) <= 0;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* How many events of each known type can still be charged within the limit.
|
|
433
|
+
*/
|
|
434
|
+
calculateChargeableWithinLimit() {
|
|
435
|
+
return Object.fromEntries(Object.keys(this.#pricingInfo).map((name) => [name, this.calculateMaxEventChargeCountWithinLimit(name)]));
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* How many of `itemsCount` items may be pushed to a dataset within the remaining budget.
|
|
439
|
+
*
|
|
440
|
+
* The budget is measured against the combined per-item price of the explicit `eventName` and - on
|
|
441
|
+
* the default dataset - the synthetic {@link DEFAULT_DATASET_ITEM_EVENT}, since pushing one item
|
|
442
|
+
* charges both.
|
|
443
|
+
*
|
|
444
|
+
* When the budget cannot cover a single item, one item is still allowed through so that the
|
|
445
|
+
* resulting overcharge makes the platform terminate the run - unless the run is already strictly
|
|
446
|
+
* over budget, in which case nothing is allowed through.
|
|
447
|
+
*/
|
|
448
|
+
calculatePushDataLimit(itemsCount, { eventName, isDefaultDataset = false } = {}) {
|
|
449
|
+
if (this.#chargingState === undefined) {
|
|
304
450
|
throw new Error('ChargingManager is not initialized');
|
|
305
451
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
return {
|
|
309
|
-
limitedItems: itemsArray,
|
|
310
|
-
eventsToCharge: {},
|
|
311
|
-
};
|
|
452
|
+
if (!this.isPayPerEvent || itemsCount === 0) {
|
|
453
|
+
return itemsCount;
|
|
312
454
|
}
|
|
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;
|
|
455
|
+
const itemPrice = (eventName === undefined ? 0 : (this.calculateEventPrice(eventName) ?? 0)) +
|
|
456
|
+
(isDefaultDataset ? (this.calculateEventPrice(DEFAULT_DATASET_ITEM_EVENT) ?? 0) : 0);
|
|
457
|
+
if (itemPrice === 0) {
|
|
458
|
+
return itemsCount;
|
|
333
459
|
}
|
|
334
|
-
|
|
335
|
-
|
|
460
|
+
const maxChargedCount = this.calculateMaxChargesByPrice(itemPrice);
|
|
461
|
+
if (maxChargedCount >= itemsCount) {
|
|
462
|
+
return itemsCount;
|
|
336
463
|
}
|
|
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]);
|
|
464
|
+
if (maxChargedCount > 0) {
|
|
465
|
+
return maxChargedCount;
|
|
466
|
+
}
|
|
467
|
+
return this.calculateTotalChargedAmount() <= this.#maxTotalChargeUsd ? 1 : 0;
|
|
361
468
|
}
|
|
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);
|
|
469
|
+
/**
|
|
470
|
+
* Runs `fn` under the charge lock, which keeps a limit reservation and the charge that acts on it
|
|
471
|
+
* atomic against concurrent pushes. Only pay-per-event runs charge anything, so for every other
|
|
472
|
+
* run there is nothing to serialize and the lock is skipped.
|
|
473
|
+
*
|
|
474
|
+
* @internal
|
|
475
|
+
*/
|
|
476
|
+
async withChargeLock(fn) {
|
|
477
|
+
return this.isPayPerEvent ? await this.#chargeLock.runExclusive(fn) : await fn();
|
|
373
478
|
}
|
|
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
479
|
}
|