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