@fetchbrain.com/sdk 0.10.0 → 0.12.0
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 +30 -94
- package/dist/collector-3OZRBCM4.mjs +1030 -0
- package/dist/collector-3OZRBCM4.mjs.map +1 -0
- package/dist/index.d.ts +70 -104
- package/dist/index.js +1899 -337
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +815 -333
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.ts +1 -1
- package/dist/{types-BCbMwaYW.d.mts → types-Cfr8odPb.d.ts} +100 -63
- package/package.json +5 -3
- package/dist/index.d.mts +0 -449
- package/dist/mock/index.d.mts +0 -84
- package/dist/types-BCbMwaYW.d.ts +0 -385
package/dist/index.js
CHANGED
|
@@ -1,9 +1,1090 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var util = require('util');
|
|
5
|
+
var zlib = require('zlib');
|
|
3
6
|
var async_hooks = require('async_hooks');
|
|
4
|
-
var crypto$1 = require('crypto');
|
|
5
7
|
|
|
6
|
-
|
|
8
|
+
var __defProp = Object.defineProperty;
|
|
9
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
10
|
+
var __esm = (fn, res) => function __init() {
|
|
11
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
12
|
+
};
|
|
13
|
+
var __export = (target, all) => {
|
|
14
|
+
for (var name in all)
|
|
15
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// src/analytics/block.ts
|
|
19
|
+
function detectBlockType(statusCode, errorMessage) {
|
|
20
|
+
if (!errorMessage) return void 0;
|
|
21
|
+
const msg = errorMessage?.toLowerCase() || "";
|
|
22
|
+
if (msg.includes("captcha")) return "captcha";
|
|
23
|
+
if (msg.includes("timeout")) return "timeout";
|
|
24
|
+
if (msg.includes("blocked")) return "blocked";
|
|
25
|
+
if (msg.includes("rate limit")) return "429";
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
var init_block = __esm({
|
|
29
|
+
"src/analytics/block.ts"() {
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// src/analytics/url.ts
|
|
34
|
+
function keepSegment(raw) {
|
|
35
|
+
if (raw === "") return true;
|
|
36
|
+
if (raw.includes("%")) return false;
|
|
37
|
+
if (WORD.test(raw) || FILE.test(raw)) return true;
|
|
38
|
+
return raw.length <= 24 && TWO_WORDS.test(raw);
|
|
39
|
+
}
|
|
40
|
+
function generalizeUrlPath(url) {
|
|
41
|
+
try {
|
|
42
|
+
const path = new URL(url).pathname;
|
|
43
|
+
return path.split("/").map((s) => keepSegment(s) ? s : "*").join("/");
|
|
44
|
+
} catch {
|
|
45
|
+
return "/*";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
var WORD, TWO_WORDS, FILE;
|
|
49
|
+
var init_url = __esm({
|
|
50
|
+
"src/analytics/url.ts"() {
|
|
51
|
+
WORD = /^[A-Za-z]{1,19}$/;
|
|
52
|
+
TWO_WORDS = /^[A-Za-z]+[-_][A-Za-z]+$/;
|
|
53
|
+
FILE = /^[A-Za-z]{1,19}\.(?:html?|php|aspx?|jsp|xml|json|txt)$/i;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
function isPlainObject(v) {
|
|
57
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
58
|
+
}
|
|
59
|
+
function sanitizeContext(raw) {
|
|
60
|
+
if (!isPlainObject(raw)) return void 0;
|
|
61
|
+
try {
|
|
62
|
+
const out = {};
|
|
63
|
+
let n = 0;
|
|
64
|
+
let scanned = 0;
|
|
65
|
+
for (const key of Object.keys(raw)) {
|
|
66
|
+
if (n >= MAX_CONTEXT_KEYS || scanned++ >= MAX_CONTEXT_SCAN) break;
|
|
67
|
+
if (!KEY_RE.test(key)) continue;
|
|
68
|
+
const v = raw[key];
|
|
69
|
+
if (typeof v === "string") out[key] = v.slice(0, MAX_CONTEXT_VALUE);
|
|
70
|
+
else if (typeof v === "number" && Number.isFinite(v)) out[key] = v;
|
|
71
|
+
else continue;
|
|
72
|
+
n++;
|
|
73
|
+
}
|
|
74
|
+
return n > 0 ? out : void 0;
|
|
75
|
+
} catch {
|
|
76
|
+
return void 0;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function cleanValue(v) {
|
|
80
|
+
if (typeof v === "string") return v.slice(0, MAX_CUSTOM_STRING);
|
|
81
|
+
if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
|
|
82
|
+
if (typeof v === "boolean") return v;
|
|
83
|
+
return void 0;
|
|
84
|
+
}
|
|
85
|
+
function sanitizeCustom(name, props) {
|
|
86
|
+
if (typeof name !== "string" || name.length === 0 || name.length > MAX_NAME) return null;
|
|
87
|
+
if (name.startsWith("~") || FIXED_EVENTS.has(name)) return null;
|
|
88
|
+
try {
|
|
89
|
+
const src = isPlainObject(props) ? props : {};
|
|
90
|
+
const out = {};
|
|
91
|
+
if (name.startsWith("antibot.")) {
|
|
92
|
+
if (!Object.prototype.hasOwnProperty.call(RESERVED_EVENTS, name)) return null;
|
|
93
|
+
const schema = RESERVED_EVENTS[name];
|
|
94
|
+
for (const [key, spec] of Object.entries(schema)) {
|
|
95
|
+
const raw = src[key];
|
|
96
|
+
if (raw === void 0 || raw === null) {
|
|
97
|
+
if (spec.required) return null;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (typeof raw !== spec.type) return null;
|
|
101
|
+
const v = cleanValue(raw);
|
|
102
|
+
if (v === void 0) return null;
|
|
103
|
+
out[key] = v;
|
|
104
|
+
}
|
|
105
|
+
return { name, props: out };
|
|
106
|
+
}
|
|
107
|
+
let n = 0;
|
|
108
|
+
for (const key of Object.keys(src)) {
|
|
109
|
+
if (n >= MAX_CUSTOM_PROPS) break;
|
|
110
|
+
if (!KEY_RE.test(key)) continue;
|
|
111
|
+
const v = cleanValue(src[key]);
|
|
112
|
+
if (v === void 0) continue;
|
|
113
|
+
out[key] = v;
|
|
114
|
+
n++;
|
|
115
|
+
}
|
|
116
|
+
return { name, props: out };
|
|
117
|
+
} catch {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function hashClient(apifyUserId, salt) {
|
|
122
|
+
return crypto.createHmac("sha256", salt).update(apifyUserId).digest("hex").slice(0, 16);
|
|
123
|
+
}
|
|
124
|
+
var MAX_CONTEXT_KEYS, MAX_CONTEXT_VALUE, MAX_CONTEXT_SCAN, MAX_CUSTOM_PROPS, MAX_CUSTOM_STRING, MAX_NAME, KEY_RE, OVERFLOW_KEY, FIXED_EVENTS, RESERVED_EVENTS;
|
|
125
|
+
var init_events = __esm({
|
|
126
|
+
"src/analytics/events.ts"() {
|
|
127
|
+
MAX_CONTEXT_KEYS = 3;
|
|
128
|
+
MAX_CONTEXT_VALUE = 64;
|
|
129
|
+
MAX_CONTEXT_SCAN = 32;
|
|
130
|
+
MAX_CUSTOM_PROPS = 10;
|
|
131
|
+
MAX_CUSTOM_STRING = 200;
|
|
132
|
+
MAX_NAME = 64;
|
|
133
|
+
KEY_RE = /^[A-Za-z0-9_.-]{1,40}$/;
|
|
134
|
+
OVERFLOW_KEY = "~other";
|
|
135
|
+
FIXED_EVENTS = /* @__PURE__ */ new Set([
|
|
136
|
+
"run_started",
|
|
137
|
+
"run_finished",
|
|
138
|
+
"request",
|
|
139
|
+
"enqueued",
|
|
140
|
+
"record_pushed",
|
|
141
|
+
"error",
|
|
142
|
+
"quota_reached"
|
|
143
|
+
]);
|
|
144
|
+
RESERVED_EVENTS = {
|
|
145
|
+
"antibot.challenge": { protection: { type: "string", required: true }, kind: { type: "string" } },
|
|
146
|
+
"antibot.solve": {
|
|
147
|
+
provider: { type: "string", required: true },
|
|
148
|
+
type: { type: "string" },
|
|
149
|
+
ms: { type: "number", required: true },
|
|
150
|
+
cost: { type: "number" },
|
|
151
|
+
ok: { type: "boolean", required: true }
|
|
152
|
+
},
|
|
153
|
+
"antibot.token_end": { reason: { type: "string", required: true }, requests: { type: "number" } }
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
function isSecretRun(run) {
|
|
158
|
+
if (/[\d+=]/.test(run)) return true;
|
|
159
|
+
if (run.length >= 32) return true;
|
|
160
|
+
const uppers = run.match(UPPER_RE)?.length ?? 0;
|
|
161
|
+
return uppers >= 2 && uppers * 4 > run.length;
|
|
162
|
+
}
|
|
163
|
+
function scrubMessage(msg) {
|
|
164
|
+
return String(msg ?? "").slice(0, MAX_MESSAGE * 4).replace(AUTHORITY_RE, "<url>").replace(URL_RE, "<url>").replace(KEY_RE2, "<secret>").replace(JWT_RE, "<secret>").replace(KEYWORD_SECRET_RE, "<secret>").replace(EMAIL_RE, "<email>").replace(UUID_RE, "<uuid>").replace(IP_RE, "<ip>").replace(IP6_RE, "<ip>").replace(HOST_RE, (m, tld, path) => FILE_EXT.has(tld.toLowerCase()) ? m : path ? "<url>" : "<host>").replace(LONG_SECRET_RE, (m) => isSecretRun(m) ? "<secret>" : m).replace(STR_RE, "<str>").replace(PATH_RE, "<path>").replace(REL_PATH_RE, "<path>").replace(NUM_RE, "<n>").slice(0, MAX_MESSAGE);
|
|
165
|
+
}
|
|
166
|
+
function topProjectFrame(stack) {
|
|
167
|
+
if (!stack) return void 0;
|
|
168
|
+
for (const line of stack.split("\n")) {
|
|
169
|
+
const m = FRAME_RE.exec(line);
|
|
170
|
+
if (!m) continue;
|
|
171
|
+
const loc = m[2];
|
|
172
|
+
if (loc.includes("node_modules") || loc.startsWith("node:") || loc.startsWith("internal/")) continue;
|
|
173
|
+
const file = loc.split(/[\\/]/).pop() || loc;
|
|
174
|
+
const fn = (m[1] ?? "").replace(/^(?:async|new)\s+/, "").trim();
|
|
175
|
+
return `${file}:${fn || "<anonymous>"}`;
|
|
176
|
+
}
|
|
177
|
+
return void 0;
|
|
178
|
+
}
|
|
179
|
+
function fingerprint(errorClass, scrubbed, frame) {
|
|
180
|
+
return crypto.createHash("sha256").update(`${errorClass}
|
|
181
|
+
${scrubbed}
|
|
182
|
+
${frame ?? ""}`).digest("hex").slice(0, 16);
|
|
183
|
+
}
|
|
184
|
+
var MAX_MESSAGE, AUTHORITY_RE, URL_RE, KEY_RE2, KEYWORD_SECRET_RE, JWT_RE, LONG_SECRET_RE, UPPER_RE, EMAIL_RE, UUID_RE, IP_RE, IP6_RE, HOST_RE, FILE_EXT, STR_RE, PATH_RE, REL_PATH_RE, NUM_RE, FRAME_RE;
|
|
185
|
+
var init_scrub = __esm({
|
|
186
|
+
"src/analytics/scrub.ts"() {
|
|
187
|
+
MAX_MESSAGE = 500;
|
|
188
|
+
AUTHORITY_RE = /(?<![\w.])[\w.~%+-]+:[^\s"'<>]*@[\w.-]+(?::\d{1,5})?/g;
|
|
189
|
+
URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>)]+/gi;
|
|
190
|
+
KEY_RE2 = /\b(?:apify_api_|sk_live_|sk_test_|gh[pousr]_|xox[baprs]-|fb_[A-Za-z]+_)[A-Za-z0-9_-]{8,}/g;
|
|
191
|
+
KEYWORD_SECRET_RE = /\b(?:(?:bearer|basic|token|api[-_]?key|authorization|auth|password|passwd|pwd|secret|set-cookie|cookie|sessionid|session)(?![A-Za-z])(?:\s*[:=]|\s)\s*)+\S+/gi;
|
|
192
|
+
JWT_RE = /\beyJ[\w-]*\.[\w-]+(?:\.[\w-]*)?/g;
|
|
193
|
+
LONG_SECRET_RE = /(?<![\w+/=-])[A-Za-z0-9_+/-]{20,}={0,2}(?![\w+/=-])/g;
|
|
194
|
+
UPPER_RE = /[A-Z]/g;
|
|
195
|
+
EMAIL_RE = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
|
|
196
|
+
UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
|
|
197
|
+
IP_RE = /\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?(?!\d)/g;
|
|
198
|
+
IP6_RE = /(?<![\w:])(?:(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}|(?:[0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,5}|::[0-9a-f]{1,4})(?![\w:])/gi;
|
|
199
|
+
HOST_RE = /(?<![\w@.-])(?:[a-z0-9-]+\.)+([a-z]{2,24})(?::\d{1,5})?(?![\w-])(\/[^\s"'<>)]*)?/gi;
|
|
200
|
+
FILE_EXT = new Set(
|
|
201
|
+
"ts js mjs cjs json py md lock txt html css yml yaml map tsx jsx log sh toml env".split(" ")
|
|
202
|
+
);
|
|
203
|
+
STR_RE = /"[^"\n]*"|`[^`\n]*`|(?<![\w])'[^'\n]*'(?![\w])/g;
|
|
204
|
+
PATH_RE = /(?<![\w<>.])(?:[A-Za-z]:)?(?:[\\/][\w.@~+-]+){2,}[\\/]?/g;
|
|
205
|
+
REL_PATH_RE = /(?<![\w<>.:/\\-])(?:\.{1,2}[\\/][\w.@~+-]+(?:[\\/][\w.@~+-]+)*|[\w@~+-]+(?:[\\/][\w.@~+-]+){2,}|[\w@~+-]+[\\/][\w@~+-]+\.\w{1,5})/g;
|
|
206
|
+
NUM_RE = /(?<![A-Za-z_<])\d+(?:\.\d+)?/g;
|
|
207
|
+
FRAME_RE = /^\s*at\s+(?:(.*?)\s+\()?(.*?):\d+(?::\d+)?\)?\s*$/;
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// src/analytics/aggregates.ts
|
|
212
|
+
function bucketOf(ms) {
|
|
213
|
+
if (!(ms > 1)) return 0;
|
|
214
|
+
const k = Math.ceil(Math.log(ms) / LOG_R);
|
|
215
|
+
return k >= BUCKETS ? BUCKETS - 1 : k;
|
|
216
|
+
}
|
|
217
|
+
function percentile(h, total, p) {
|
|
218
|
+
if (total === 0) return void 0;
|
|
219
|
+
const rank = Math.ceil(total * p);
|
|
220
|
+
let seen = 0;
|
|
221
|
+
for (let k = 0; k < BUCKETS; k++) {
|
|
222
|
+
seen += h[k];
|
|
223
|
+
if (seen >= rank) return k === 0 ? 1 : Math.round(Math.exp((k - 0.5) * LOG_R));
|
|
224
|
+
}
|
|
225
|
+
return MAX_MS;
|
|
226
|
+
}
|
|
227
|
+
function newPattern(label) {
|
|
228
|
+
return { label, requests: 0, scraped: 0, blocked: 0, failed: 0, nav: new Uint32Array(BUCKETS), navN: 0 };
|
|
229
|
+
}
|
|
230
|
+
function toStats(p) {
|
|
231
|
+
const out = {
|
|
232
|
+
label: p.label,
|
|
233
|
+
requests: p.requests,
|
|
234
|
+
scraped: p.scraped,
|
|
235
|
+
blocked: p.blocked,
|
|
236
|
+
failed: p.failed
|
|
237
|
+
};
|
|
238
|
+
const navP95 = percentile(p.nav, p.navN, 0.95);
|
|
239
|
+
if (navP95 !== void 0) out.navP95 = navP95;
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
function customReport(c) {
|
|
243
|
+
const props = {};
|
|
244
|
+
for (const [k, p] of c.props) {
|
|
245
|
+
if (p.kind === "s") props[k] = p.other > 0 ? { kind: "s", top: Object.fromEntries(p.top), other: p.other } : { kind: "s", top: Object.fromEntries(p.top) };
|
|
246
|
+
else if (p.kind === "n") props[k] = p.min > p.max ? { kind: "n", sum: 0, min: 0, max: 0 } : { ...p };
|
|
247
|
+
else props[k] = { ...p };
|
|
248
|
+
}
|
|
249
|
+
return { count: c.count, labels: Object.fromEntries(c.labels), props };
|
|
250
|
+
}
|
|
251
|
+
var BUCKETS, MAX_MS, LOG_R, REPORT_PATTERNS, MAX_LIVE_PATTERNS, MAX_NAMES, MAX_PROPS, MAX_TOP, MAX_LABELS_PER_NAME, newCustom, Aggregates;
|
|
252
|
+
var init_aggregates = __esm({
|
|
253
|
+
"src/analytics/aggregates.ts"() {
|
|
254
|
+
init_events();
|
|
255
|
+
BUCKETS = 32;
|
|
256
|
+
MAX_MS = 12e4;
|
|
257
|
+
LOG_R = Math.log(MAX_MS) / (BUCKETS - 1);
|
|
258
|
+
REPORT_PATTERNS = 50;
|
|
259
|
+
MAX_LIVE_PATTERNS = 300;
|
|
260
|
+
MAX_NAMES = 50;
|
|
261
|
+
MAX_PROPS = 10;
|
|
262
|
+
MAX_TOP = 20;
|
|
263
|
+
MAX_LABELS_PER_NAME = 50;
|
|
264
|
+
newCustom = () => ({ count: 0, labels: /* @__PURE__ */ new Map(), props: /* @__PURE__ */ new Map() });
|
|
265
|
+
Aggregates = class {
|
|
266
|
+
constructor() {
|
|
267
|
+
this.patterns = /* @__PURE__ */ new Map();
|
|
268
|
+
this.custom_ = /* @__PURE__ */ new Map();
|
|
269
|
+
}
|
|
270
|
+
/** One real request at its final outcome (weight 1). O(1). */
|
|
271
|
+
request(label, urlPattern, outcome, navMs) {
|
|
272
|
+
let p = this.patterns.get(urlPattern);
|
|
273
|
+
if (!p) {
|
|
274
|
+
if (this.patterns.size < MAX_LIVE_PATTERNS) {
|
|
275
|
+
p = newPattern(label);
|
|
276
|
+
this.patterns.set(urlPattern, p);
|
|
277
|
+
} else {
|
|
278
|
+
p = this.overflow ?? (this.overflow = newPattern(""));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
p.requests++;
|
|
282
|
+
if (outcome === "scraped") p.scraped++;
|
|
283
|
+
else if (outcome === "blocked") p.blocked++;
|
|
284
|
+
else if (outcome === "failed") p.failed++;
|
|
285
|
+
if (typeof navMs === "number" && Number.isFinite(navMs)) {
|
|
286
|
+
p.nav[bucketOf(navMs)]++;
|
|
287
|
+
p.navN++;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** A developer event (never antibot.*, never sampled). Props are already sanitized. */
|
|
291
|
+
custom(name, label, props, weight = 1) {
|
|
292
|
+
if (name.startsWith("antibot.")) return;
|
|
293
|
+
const w = typeof weight === "number" && Number.isFinite(weight) && weight > 0 ? weight : 1;
|
|
294
|
+
let c = this.custom_.get(name);
|
|
295
|
+
if (!c) {
|
|
296
|
+
if (this.custom_.size < MAX_NAMES) {
|
|
297
|
+
c = newCustom();
|
|
298
|
+
this.custom_.set(name, c);
|
|
299
|
+
} else {
|
|
300
|
+
c = this.otherName ?? (this.otherName = newCustom());
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
c.count += w;
|
|
304
|
+
const lk = c.labels.has(label) || c.labels.size < MAX_LABELS_PER_NAME ? label : OVERFLOW_KEY;
|
|
305
|
+
c.labels.set(lk, (c.labels.get(lk) ?? 0) + w);
|
|
306
|
+
for (const key of Object.keys(props)) {
|
|
307
|
+
const v = props[key];
|
|
308
|
+
let ps = c.props.get(key);
|
|
309
|
+
if (!ps) {
|
|
310
|
+
if (c.props.size >= MAX_PROPS) continue;
|
|
311
|
+
ps = typeof v === "string" ? { kind: "s", top: /* @__PURE__ */ new Map(), other: 0 } : typeof v === "number" ? { kind: "n", sum: 0, min: Infinity, max: -Infinity } : { kind: "b", true: 0, false: 0 };
|
|
312
|
+
c.props.set(key, ps);
|
|
313
|
+
}
|
|
314
|
+
if (ps.kind === "s" && typeof v === "string") {
|
|
315
|
+
if (ps.top.has(v) || ps.top.size < MAX_TOP) ps.top.set(v, (ps.top.get(v) ?? 0) + w);
|
|
316
|
+
else ps.other += w;
|
|
317
|
+
} else if (ps.kind === "n" && typeof v === "number" && Number.isFinite(v)) {
|
|
318
|
+
ps.sum += v * w;
|
|
319
|
+
if (v < ps.min) ps.min = v;
|
|
320
|
+
if (v > ps.max) ps.max = v;
|
|
321
|
+
} else if (ps.kind === "b" && typeof v === "boolean") {
|
|
322
|
+
if (v) ps.true += w;
|
|
323
|
+
else ps.false += w;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
toReport() {
|
|
328
|
+
const patterns = {};
|
|
329
|
+
const ranked = [...this.patterns.entries()].sort((a, b) => b[1].requests - a[1].requests);
|
|
330
|
+
const keep = ranked.slice(0, REPORT_PATTERNS);
|
|
331
|
+
for (const [k, p] of keep) patterns[k] = toStats(p);
|
|
332
|
+
const rest = ranked.slice(REPORT_PATTERNS).map((e) => e[1]);
|
|
333
|
+
if (this.overflow) rest.push(this.overflow);
|
|
334
|
+
if (rest.length > 0) {
|
|
335
|
+
const o = newPattern("");
|
|
336
|
+
for (const p of rest) {
|
|
337
|
+
o.requests += p.requests;
|
|
338
|
+
o.scraped += p.scraped;
|
|
339
|
+
o.blocked += p.blocked;
|
|
340
|
+
o.failed += p.failed;
|
|
341
|
+
o.navN += p.navN;
|
|
342
|
+
for (let i = 0; i < BUCKETS; i++) o.nav[i] += p.nav[i];
|
|
343
|
+
}
|
|
344
|
+
patterns[OVERFLOW_KEY] = toStats(o);
|
|
345
|
+
}
|
|
346
|
+
const custom = {};
|
|
347
|
+
for (const [n, c] of this.custom_) custom[n] = customReport(c);
|
|
348
|
+
if (this.otherName) custom[OVERFLOW_KEY] = customReport(this.otherName);
|
|
349
|
+
return { patterns, custom };
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
function startSeqFromEnv(env = process.env, now = Date.now()) {
|
|
355
|
+
try {
|
|
356
|
+
const raw = env.APIFY_STARTED_AT || env.ACTOR_STARTED_AT;
|
|
357
|
+
if (!raw) return 0;
|
|
358
|
+
const startedAt = Date.parse(raw);
|
|
359
|
+
if (!Number.isFinite(startedAt)) return 0;
|
|
360
|
+
const seq = Math.max(0, Math.floor((now - startedAt) / 1e3)) * 1e3;
|
|
361
|
+
return Number.isSafeInteger(seq) && seq < MAX_SEQ ? seq : 0;
|
|
362
|
+
} catch {
|
|
363
|
+
return 0;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
var gzipAsync, MAX_BATCH_BYTES, EVENTS_MARK, EVENTS_MARK_JSON, eventsPlaceholder, MAX_SEQ, MAX_PAUSE_MS, BACKOFF_BASE_MS, BACKOFF_MAX_MS, AnalyticsQueue;
|
|
367
|
+
var init_queue = __esm({
|
|
368
|
+
"src/analytics/queue.ts"() {
|
|
369
|
+
gzipAsync = util.promisify(zlib.gzip);
|
|
370
|
+
MAX_BATCH_BYTES = 200 * 1024;
|
|
371
|
+
EVENTS_MARK = "\0fetchbrain-events\0";
|
|
372
|
+
EVENTS_MARK_JSON = JSON.stringify(EVENTS_MARK);
|
|
373
|
+
eventsPlaceholder = { toJSON: () => EVENTS_MARK };
|
|
374
|
+
MAX_SEQ = 1e12;
|
|
375
|
+
MAX_PAUSE_MS = 24 * 60 * 60 * 1e3;
|
|
376
|
+
BACKOFF_BASE_MS = 5e3;
|
|
377
|
+
BACKOFF_MAX_MS = 6e4;
|
|
378
|
+
AnalyticsQueue = class {
|
|
379
|
+
constructor(send, opts = {}) {
|
|
380
|
+
this.send = send;
|
|
381
|
+
this.dropped = 0;
|
|
382
|
+
this.sampleRate = 1;
|
|
383
|
+
/** The last batch was cut by size: keep sending instead of waiting for a full batch. */
|
|
384
|
+
this.cut = false;
|
|
385
|
+
// Absolute indexes: the oldest event is `startIdx`, the next write is `endIdx`.
|
|
386
|
+
this.startIdx = 0;
|
|
387
|
+
this.endIdx = 0;
|
|
388
|
+
this.generation = 0;
|
|
389
|
+
this.failures = 0;
|
|
390
|
+
this.notBefore = 0;
|
|
391
|
+
// backoff gate
|
|
392
|
+
this.pausedUntil = 0;
|
|
393
|
+
/** Extras that did not fit the previous batch (pathological label counts); at most maxBatch. */
|
|
394
|
+
this.carry = [];
|
|
395
|
+
const startSeq = opts.startSeq;
|
|
396
|
+
this.nextSeq = typeof startSeq === "number" && Number.isSafeInteger(startSeq) && startSeq >= 0 && startSeq < MAX_SEQ ? startSeq : 0;
|
|
397
|
+
this.maxBatch = opts.maxBatch ?? 250;
|
|
398
|
+
this.flushMs = opts.flushMs ?? 3e4;
|
|
399
|
+
this.capacity = opts.capacity ?? 1e4;
|
|
400
|
+
this.finalFlushTimeoutMs = opts.finalFlushTimeoutMs ?? 1800;
|
|
401
|
+
this.maxBatchAttempts = opts.maxBatchAttempts ?? 5;
|
|
402
|
+
this.maxBatchAgeMs = opts.maxBatchAgeMs ?? 6e5;
|
|
403
|
+
this.maxBatchBytes = opts.maxBatchBytes ?? MAX_BATCH_BYTES;
|
|
404
|
+
this.compress = opts.compress ?? ((j) => gzipAsync(j));
|
|
405
|
+
this.wrap = opts.wrap ?? ((events) => events);
|
|
406
|
+
this.ring = new Array(this.capacity);
|
|
407
|
+
}
|
|
408
|
+
/** Events currently buffered. */
|
|
409
|
+
get size() {
|
|
410
|
+
return this.endIdx - this.startIdx;
|
|
411
|
+
}
|
|
412
|
+
/** Hold every send until `until` (epoch ms), clamped to ≤24 h ahead, like a server pause. NaN is ignored. */
|
|
413
|
+
pause(until) {
|
|
414
|
+
if (typeof until !== "number" || Number.isNaN(until)) return;
|
|
415
|
+
this.pausedUntil = Math.max(this.pausedUntil, Math.min(until, Date.now() + MAX_PAUSE_MS));
|
|
416
|
+
}
|
|
417
|
+
setBeforeFlush(fn) {
|
|
418
|
+
this.beforeFlush = fn;
|
|
419
|
+
}
|
|
420
|
+
push(e) {
|
|
421
|
+
if (this.endIdx - this.startIdx >= this.capacity) {
|
|
422
|
+
this.ring[this.startIdx % this.capacity] = void 0;
|
|
423
|
+
this.startIdx++;
|
|
424
|
+
this.dropped++;
|
|
425
|
+
}
|
|
426
|
+
this.ring[this.endIdx % this.capacity] = e;
|
|
427
|
+
this.endIdx++;
|
|
428
|
+
if (this.endIdx - this.startIdx >= this.maxBatch && this.canKick()) this.kick();
|
|
429
|
+
}
|
|
430
|
+
start() {
|
|
431
|
+
if (this.timer) clearInterval(this.timer);
|
|
432
|
+
this.timer = setInterval(() => this.kick(), this.flushMs);
|
|
433
|
+
this.timer.unref();
|
|
434
|
+
}
|
|
435
|
+
async stop() {
|
|
436
|
+
if (this.timer) clearInterval(this.timer);
|
|
437
|
+
this.timer = void 0;
|
|
438
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
439
|
+
this.retryTimer = void 0;
|
|
440
|
+
let deadline;
|
|
441
|
+
const timeout = new Promise((resolve) => {
|
|
442
|
+
deadline = setTimeout(resolve, this.finalFlushTimeoutMs);
|
|
443
|
+
deadline.unref();
|
|
444
|
+
});
|
|
445
|
+
try {
|
|
446
|
+
await Promise.race([this.drain(), timeout]);
|
|
447
|
+
} catch {
|
|
448
|
+
} finally {
|
|
449
|
+
if (deadline) clearTimeout(deadline);
|
|
450
|
+
if (this.inflight) {
|
|
451
|
+
this.generation++;
|
|
452
|
+
this.abort?.abort();
|
|
453
|
+
if (this.current && !this.pending) this.pending = this.current;
|
|
454
|
+
this.current = void 0;
|
|
455
|
+
this.inflight = void 0;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** Synchronous gate so a gated push() allocates nothing. */
|
|
460
|
+
canKick() {
|
|
461
|
+
if (this.inflight || !this.timer) return false;
|
|
462
|
+
const now = Date.now();
|
|
463
|
+
return now >= this.notBefore && now >= this.pausedUntil;
|
|
464
|
+
}
|
|
465
|
+
kick() {
|
|
466
|
+
void this.flush(false).catch(() => {
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
async drain() {
|
|
470
|
+
const gen = this.generation;
|
|
471
|
+
if (this.inflight) await this.inflight.catch(() => false);
|
|
472
|
+
if (gen !== this.generation) return;
|
|
473
|
+
await this.flush(true);
|
|
474
|
+
}
|
|
475
|
+
/** Send batches until the ring has less than a full batch (or, when final, is empty). */
|
|
476
|
+
async flush(final) {
|
|
477
|
+
if (this.inflight) return;
|
|
478
|
+
const gen = this.generation;
|
|
479
|
+
const run = (async () => {
|
|
480
|
+
let ok2 = true;
|
|
481
|
+
for (; ; ) {
|
|
482
|
+
if (gen !== this.generation) return false;
|
|
483
|
+
const now = Date.now();
|
|
484
|
+
if (now < this.pausedUntil) return ok2;
|
|
485
|
+
if (!final && now < this.notBefore) return ok2;
|
|
486
|
+
ok2 = await this.sendOne(gen);
|
|
487
|
+
if (!ok2 || gen !== this.generation) return false;
|
|
488
|
+
const left = this.size;
|
|
489
|
+
if (left === 0 && this.carry.length === 0) return true;
|
|
490
|
+
if (!final && left < this.maxBatch && this.carry.length === 0 && !this.cut) return true;
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
this.inflight = run;
|
|
494
|
+
let ok = false;
|
|
495
|
+
try {
|
|
496
|
+
ok = await run;
|
|
497
|
+
} catch {
|
|
498
|
+
ok = false;
|
|
499
|
+
}
|
|
500
|
+
if (gen !== this.generation) return;
|
|
501
|
+
this.inflight = void 0;
|
|
502
|
+
if (!ok) this.scheduleRetry();
|
|
503
|
+
}
|
|
504
|
+
scheduleRetry() {
|
|
505
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
506
|
+
if (!this.timer) return;
|
|
507
|
+
const wait = Math.max(0, this.notBefore - Date.now(), this.pausedUntil - Date.now());
|
|
508
|
+
this.retryTimer = setTimeout(() => this.kick(), wait);
|
|
509
|
+
this.retryTimer.unref();
|
|
510
|
+
}
|
|
511
|
+
/** Build and send one batch. True on success or when there was nothing to send. */
|
|
512
|
+
async sendOne(gen) {
|
|
513
|
+
let job = this.pending;
|
|
514
|
+
if (!job) {
|
|
515
|
+
let extras = [];
|
|
516
|
+
try {
|
|
517
|
+
extras = this.beforeFlush?.() ?? [];
|
|
518
|
+
} catch {
|
|
519
|
+
extras = [];
|
|
520
|
+
}
|
|
521
|
+
if (this.carry.length > 0) {
|
|
522
|
+
extras = this.carry.concat(extras);
|
|
523
|
+
this.carry = [];
|
|
524
|
+
}
|
|
525
|
+
if (extras.length > this.maxBatch) {
|
|
526
|
+
this.setCarry(extras.slice(this.maxBatch));
|
|
527
|
+
extras = extras.slice(0, this.maxBatch);
|
|
528
|
+
}
|
|
529
|
+
const n = Math.min(this.size, this.maxBatch - extras.length);
|
|
530
|
+
if (n === 0 && extras.length === 0) return true;
|
|
531
|
+
const b0 = this.startIdx;
|
|
532
|
+
const batch = [];
|
|
533
|
+
for (let i = 0; i < n; i++) batch.push(this.ring[(b0 + i) % this.capacity]);
|
|
534
|
+
for (const e of extras) batch.push(e);
|
|
535
|
+
const seq = this.nextSeq++;
|
|
536
|
+
let built;
|
|
537
|
+
try {
|
|
538
|
+
built = this.serialize(batch, seq);
|
|
539
|
+
} catch {
|
|
540
|
+
this.consume(b0, n);
|
|
541
|
+
return true;
|
|
542
|
+
}
|
|
543
|
+
this.cut = built.k < batch.length;
|
|
544
|
+
if (built.k < n) {
|
|
545
|
+
this.setCarry(extras.concat(this.carry));
|
|
546
|
+
job = { seq, batch: batch.slice(0, built.k), b0, n: built.k, attempts: 0, firstAt: Date.now(), json: built.json };
|
|
547
|
+
} else {
|
|
548
|
+
if (built.k < batch.length) this.setCarry(extras.slice(built.k - n).concat(this.carry));
|
|
549
|
+
job = { seq, batch: batch.slice(0, built.k), b0, n, attempts: 0, firstAt: Date.now(), json: built.json };
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
this.current = job;
|
|
553
|
+
const ac = new AbortController();
|
|
554
|
+
this.abort = ac;
|
|
555
|
+
let gz;
|
|
556
|
+
try {
|
|
557
|
+
if (!job.gz) {
|
|
558
|
+
job.gz = await this.compress(job.json ?? JSON.stringify(this.wrap(job.batch, job.seq)));
|
|
559
|
+
job.json = void 0;
|
|
560
|
+
}
|
|
561
|
+
gz = job.gz;
|
|
562
|
+
} catch {
|
|
563
|
+
if (gen !== this.generation) return false;
|
|
564
|
+
this.current = void 0;
|
|
565
|
+
this.pending = void 0;
|
|
566
|
+
this.consume(job.b0, job.n);
|
|
567
|
+
return true;
|
|
568
|
+
}
|
|
569
|
+
if (gen !== this.generation) return false;
|
|
570
|
+
let result = null;
|
|
571
|
+
try {
|
|
572
|
+
result = await this.send(gz, ac.signal);
|
|
573
|
+
} catch {
|
|
574
|
+
result = null;
|
|
575
|
+
}
|
|
576
|
+
if (gen !== this.generation) return false;
|
|
577
|
+
this.current = void 0;
|
|
578
|
+
if (result === null) {
|
|
579
|
+
job.attempts++;
|
|
580
|
+
this.failures++;
|
|
581
|
+
const delay = Math.min(BACKOFF_BASE_MS * 2 ** (this.failures - 1), BACKOFF_MAX_MS);
|
|
582
|
+
this.notBefore = Date.now() + delay;
|
|
583
|
+
if (job.attempts >= this.maxBatchAttempts || Date.now() - job.firstAt >= this.maxBatchAgeMs) {
|
|
584
|
+
this.dropped += job.batch.length;
|
|
585
|
+
this.pending = void 0;
|
|
586
|
+
this.consume(job.b0, job.n);
|
|
587
|
+
} else {
|
|
588
|
+
this.pending = job;
|
|
589
|
+
}
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
if (result.retry) {
|
|
593
|
+
if (typeof result.pauseUntil === "number") this.pause(result.pauseUntil);
|
|
594
|
+
if (Date.now() - job.firstAt >= this.maxBatchAgeMs) {
|
|
595
|
+
this.dropped += job.batch.length;
|
|
596
|
+
this.pending = void 0;
|
|
597
|
+
this.consume(job.b0, job.n);
|
|
598
|
+
} else {
|
|
599
|
+
this.pending = job;
|
|
600
|
+
}
|
|
601
|
+
return false;
|
|
602
|
+
}
|
|
603
|
+
this.failures = 0;
|
|
604
|
+
this.notBefore = 0;
|
|
605
|
+
if (typeof result.pauseUntil === "number") this.pause(result.pauseUntil);
|
|
606
|
+
if (result.drop) {
|
|
607
|
+
this.dropped += job.batch.length;
|
|
608
|
+
this.pending = void 0;
|
|
609
|
+
this.consume(job.b0, job.n);
|
|
610
|
+
return true;
|
|
611
|
+
}
|
|
612
|
+
if (typeof result.sampleRate === "number") this.sampleRate = result.sampleRate;
|
|
613
|
+
this.pending = void 0;
|
|
614
|
+
this.consume(job.b0, job.n);
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* The payload for the longest prefix of `batch` that fits maxBatchBytes (at least one event, so a
|
|
619
|
+
* lone oversized event can't stall the queue; the API refuses it and it is dropped). Each event is
|
|
620
|
+
* serialized once. Throws only if an event can't be serialized.
|
|
621
|
+
*/
|
|
622
|
+
serialize(batch, seq) {
|
|
623
|
+
const envelope = JSON.stringify(this.wrap(eventsPlaceholder, seq));
|
|
624
|
+
const at = envelope.indexOf(EVENTS_MARK_JSON);
|
|
625
|
+
if (at < 0) return { json: JSON.stringify(this.wrap(batch, seq)), k: batch.length };
|
|
626
|
+
let bytes = Buffer.byteLength(envelope) - Buffer.byteLength(EVENTS_MARK_JSON) + 2;
|
|
627
|
+
const parts = [];
|
|
628
|
+
for (const e of batch) {
|
|
629
|
+
const part = JSON.stringify(e);
|
|
630
|
+
const b = Buffer.byteLength(part) + (parts.length > 0 ? 1 : 0);
|
|
631
|
+
if (parts.length > 0 && bytes + b > this.maxBatchBytes) break;
|
|
632
|
+
parts.push(part);
|
|
633
|
+
bytes += b;
|
|
634
|
+
}
|
|
635
|
+
const json = envelope.slice(0, at) + "[" + parts.join(",") + "]" + envelope.slice(at + EVENTS_MARK_JSON.length);
|
|
636
|
+
return { json, k: parts.length };
|
|
637
|
+
}
|
|
638
|
+
/** Extras waiting for a later batch, bounded to one batch (the oldest beyond it drop, counted). */
|
|
639
|
+
setCarry(events) {
|
|
640
|
+
const over = events.length - this.maxBatch;
|
|
641
|
+
if (over > 0) {
|
|
642
|
+
this.dropped += over;
|
|
643
|
+
events = events.slice(over);
|
|
644
|
+
}
|
|
645
|
+
this.carry = events;
|
|
646
|
+
}
|
|
647
|
+
consume(b0, n) {
|
|
648
|
+
const newStart = Math.max(this.startIdx, b0 + n);
|
|
649
|
+
for (let i = this.startIdx; i < newStart; i++) this.ring[i % this.capacity] = void 0;
|
|
650
|
+
this.startIdx = newStart;
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
// src/analytics/collector.ts
|
|
657
|
+
var collector_exports = {};
|
|
658
|
+
__export(collector_exports, {
|
|
659
|
+
AnalyticsQueue: () => AnalyticsQueue,
|
|
660
|
+
Collector: () => Collector,
|
|
661
|
+
SDK_VERSION: () => SDK_VERSION,
|
|
662
|
+
startSeqFromEnv: () => startSeqFromEnv
|
|
663
|
+
});
|
|
664
|
+
function errorClassOf(err) {
|
|
665
|
+
try {
|
|
666
|
+
if (err instanceof Error) {
|
|
667
|
+
const n = err.constructor?.name || err.name;
|
|
668
|
+
return typeof n === "string" && /^[\w$.]{1,64}$/.test(n) ? n : "Error";
|
|
669
|
+
}
|
|
670
|
+
return err === null ? "null" : typeof err;
|
|
671
|
+
} catch {
|
|
672
|
+
return "Error";
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
function rawMessageOf(err) {
|
|
676
|
+
try {
|
|
677
|
+
if (err instanceof Error) return typeof err.message === "string" ? err.message : String(err.message);
|
|
678
|
+
if (typeof err === "string") return err;
|
|
679
|
+
return String(err);
|
|
680
|
+
} catch {
|
|
681
|
+
return "";
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function stackOf(err) {
|
|
685
|
+
try {
|
|
686
|
+
const s = err?.stack;
|
|
687
|
+
return typeof s === "string" ? s : void 0;
|
|
688
|
+
} catch {
|
|
689
|
+
return void 0;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
function newLabelState() {
|
|
693
|
+
return {
|
|
694
|
+
stats: {
|
|
695
|
+
requests: 0,
|
|
696
|
+
scraped: 0,
|
|
697
|
+
recalled: 0,
|
|
698
|
+
skipped: 0,
|
|
699
|
+
bypassed: 0,
|
|
700
|
+
failed: 0,
|
|
701
|
+
blocked: 0,
|
|
702
|
+
blockedAttempts: 0,
|
|
703
|
+
retries: 0,
|
|
704
|
+
records: 0,
|
|
705
|
+
bytes: 0,
|
|
706
|
+
// Keyed by developer labels: no prototype, so "__proto__" is an ordinary key.
|
|
707
|
+
enqueued: /* @__PURE__ */ Object.create(null),
|
|
708
|
+
alreadyQueued: /* @__PURE__ */ Object.create(null),
|
|
709
|
+
status: {}
|
|
710
|
+
},
|
|
711
|
+
pendingRecords: 0,
|
|
712
|
+
nav: new Uint32Array(BUCKETS),
|
|
713
|
+
navN: 0,
|
|
714
|
+
handler: new Uint32Array(BUCKETS),
|
|
715
|
+
handlerN: 0
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function domainOf(url) {
|
|
719
|
+
try {
|
|
720
|
+
return new URL(url).hostname;
|
|
721
|
+
} catch {
|
|
722
|
+
return "";
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
var SDK_VERSION, BLOCKED_STATUS, BLOCKED_MESSAGE_TYPES, MAX_LABELS, MAX_STATUS_CODES, MAX_CHILD_LABELS, SAMPLE_THRESHOLD, SLOTS, SLOT_MS, ROUTINE, MAX_FINGERPRINTS, MAX_RAW_KEYS, RAW_KEY_CHARS, OVERFLOW_FINGERPRINT, MAX_REJECTED_NAMES_LOGGED, hasOwn, isNum, RESERVED_PROPS, Collector;
|
|
726
|
+
var init_collector = __esm({
|
|
727
|
+
"src/analytics/collector.ts"() {
|
|
728
|
+
init_block();
|
|
729
|
+
init_url();
|
|
730
|
+
init_events();
|
|
731
|
+
init_scrub();
|
|
732
|
+
init_aggregates();
|
|
733
|
+
init_queue();
|
|
734
|
+
SDK_VERSION = "0.12.0" ;
|
|
735
|
+
BLOCKED_STATUS = /* @__PURE__ */ new Set([403, 429, 503]);
|
|
736
|
+
BLOCKED_MESSAGE_TYPES = /* @__PURE__ */ new Set(["captcha", "blocked", "429"]);
|
|
737
|
+
MAX_LABELS = 50;
|
|
738
|
+
MAX_STATUS_CODES = 20;
|
|
739
|
+
MAX_CHILD_LABELS = 50;
|
|
740
|
+
SAMPLE_THRESHOLD = 200;
|
|
741
|
+
SLOTS = 10;
|
|
742
|
+
SLOT_MS = 1e3;
|
|
743
|
+
ROUTINE = /* @__PURE__ */ new Set(["scraped", "recalled", "skipped"]);
|
|
744
|
+
MAX_FINGERPRINTS = 1e3;
|
|
745
|
+
MAX_RAW_KEYS = 2e3;
|
|
746
|
+
RAW_KEY_CHARS = 300;
|
|
747
|
+
OVERFLOW_FINGERPRINT = "overflow";
|
|
748
|
+
MAX_REJECTED_NAMES_LOGGED = 100;
|
|
749
|
+
hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
750
|
+
isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
751
|
+
RESERVED_PROPS = /* @__PURE__ */ new Set([
|
|
752
|
+
"client",
|
|
753
|
+
"scraper",
|
|
754
|
+
"runId",
|
|
755
|
+
"seq",
|
|
756
|
+
"ts",
|
|
757
|
+
"label",
|
|
758
|
+
"crawlerType",
|
|
759
|
+
"sdkVersion",
|
|
760
|
+
"platform",
|
|
761
|
+
"weight",
|
|
762
|
+
"context"
|
|
763
|
+
]);
|
|
764
|
+
Collector = class {
|
|
765
|
+
constructor(queue, base, opts = {}) {
|
|
766
|
+
this.queue = queue;
|
|
767
|
+
this.base = base;
|
|
768
|
+
this.seq = 0;
|
|
769
|
+
this.labels = /* @__PURE__ */ new Map();
|
|
770
|
+
this.aggregates = new Aggregates();
|
|
771
|
+
// Rate window state.
|
|
772
|
+
this.slots = new Uint32Array(SLOTS);
|
|
773
|
+
this.slotAbs = -1;
|
|
774
|
+
// absolute index (time / SLOT_MS) of the newest slot
|
|
775
|
+
this.windowSum = 0;
|
|
776
|
+
// Error grouping.
|
|
777
|
+
this.groups = /* @__PURE__ */ new Map();
|
|
778
|
+
this.rawKeys = /* @__PURE__ */ new Map();
|
|
779
|
+
// class+message+frame -> fingerprint
|
|
780
|
+
this.rejectedNames = /* @__PURE__ */ new Set();
|
|
781
|
+
const start = opts.startSeq;
|
|
782
|
+
if (typeof start === "number" && Number.isSafeInteger(start) && start > 0) this.seq = start;
|
|
783
|
+
this.now = opts.now ?? Date.now;
|
|
784
|
+
this.random = opts.random ?? Math.random;
|
|
785
|
+
this.debug = opts.debug ?? (() => {
|
|
786
|
+
});
|
|
787
|
+
queue.setBeforeFlush(() => this.drainRecords());
|
|
788
|
+
}
|
|
789
|
+
/** Validated `context` keys from the developer's callback result (≤3 keys, values ≤64 chars). */
|
|
790
|
+
sanitizeContext(raw) {
|
|
791
|
+
return sanitizeContext(raw);
|
|
792
|
+
}
|
|
793
|
+
/** Salted buyer hash; exposed here so enhance.ts never imports events.ts statically. */
|
|
794
|
+
static hashClient(apifyUserId, salt) {
|
|
795
|
+
return hashClient(apifyUserId, salt);
|
|
796
|
+
}
|
|
797
|
+
label(label) {
|
|
798
|
+
let s = this.labels.get(label);
|
|
799
|
+
if (s) return s;
|
|
800
|
+
const key = this.labels.size < MAX_LABELS ? label : OVERFLOW_KEY;
|
|
801
|
+
s = this.labels.get(key);
|
|
802
|
+
if (!s) {
|
|
803
|
+
s = newLabelState();
|
|
804
|
+
this.labels.set(key, s);
|
|
805
|
+
}
|
|
806
|
+
return s;
|
|
807
|
+
}
|
|
808
|
+
/** Base props, applied last so no caller field can overwrite them. */
|
|
809
|
+
props(label) {
|
|
810
|
+
return { ...this.base, seq: this.seq++, ts: Date.now(), label };
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Block type of a failed attempt, or undefined when it was not blocked. Blocked =
|
|
814
|
+
* status 403/429/503 or a captcha/blocked/rate-limit message; 404, 500, timeouts
|
|
815
|
+
* and plain handler errors are failures, not blocks.
|
|
816
|
+
*/
|
|
817
|
+
blockType(statusCode, message) {
|
|
818
|
+
if (statusCode !== void 0 && BLOCKED_STATUS.has(statusCode)) return String(statusCode);
|
|
819
|
+
const byMsg = message ? detectBlockType(void 0, message) : void 0;
|
|
820
|
+
return byMsg !== void 0 && BLOCKED_MESSAGE_TYPES.has(byMsg) ? byMsg : void 0;
|
|
821
|
+
}
|
|
822
|
+
request(p) {
|
|
823
|
+
const s = this.label(p.label);
|
|
824
|
+
const st = s.stats;
|
|
825
|
+
st.requests++;
|
|
826
|
+
st[p.outcome]++;
|
|
827
|
+
st.retries += p.retries;
|
|
828
|
+
const blockedAttempts = p.blockedAttempts ?? 0;
|
|
829
|
+
st.blockedAttempts += blockedAttempts;
|
|
830
|
+
if (isNum(p.bytes)) st.bytes += p.bytes;
|
|
831
|
+
if (isNum(p.navMs)) {
|
|
832
|
+
s.nav[bucketOf(p.navMs)]++;
|
|
833
|
+
s.navN++;
|
|
834
|
+
}
|
|
835
|
+
if (isNum(p.handlerMs)) {
|
|
836
|
+
s.handler[bucketOf(p.handlerMs)]++;
|
|
837
|
+
s.handlerN++;
|
|
838
|
+
}
|
|
839
|
+
if (isNum(p.statusCode)) {
|
|
840
|
+
const code = String(p.statusCode);
|
|
841
|
+
if (code in st.status || Object.keys(st.status).length < MAX_STATUS_CODES) {
|
|
842
|
+
st.status[code] = (st.status[code] ?? 0) + 1;
|
|
843
|
+
} else {
|
|
844
|
+
st.status.other = (st.status.other ?? 0) + 1;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const urlPattern = generalizeUrlPath(p.url);
|
|
848
|
+
this.aggregates.request(p.label, urlPattern, p.outcome, isNum(p.navMs) ? p.navMs : void 0);
|
|
849
|
+
const keep = this.sampleRequest(p.outcome);
|
|
850
|
+
if (keep === 0) return;
|
|
851
|
+
let context;
|
|
852
|
+
if (typeof p.context === "function") {
|
|
853
|
+
try {
|
|
854
|
+
context = p.context();
|
|
855
|
+
} catch {
|
|
856
|
+
context = void 0;
|
|
857
|
+
}
|
|
858
|
+
} else {
|
|
859
|
+
context = p.context;
|
|
860
|
+
}
|
|
861
|
+
const event = {
|
|
862
|
+
name: "request",
|
|
863
|
+
props: {
|
|
864
|
+
outcome: p.outcome,
|
|
865
|
+
retries: p.retries,
|
|
866
|
+
statusCode: p.statusCode,
|
|
867
|
+
domain: domainOf(p.url),
|
|
868
|
+
urlPattern,
|
|
869
|
+
navMs: p.navMs,
|
|
870
|
+
handlerMs: p.handlerMs,
|
|
871
|
+
recallMs: p.recallMs,
|
|
872
|
+
bytes: p.bytes,
|
|
873
|
+
blockType: p.blockType,
|
|
874
|
+
blockedAttempts,
|
|
875
|
+
context,
|
|
876
|
+
// Absent weight = 1 (every non-sampled event).
|
|
877
|
+
weight: keep === 1 ? void 0 : keep,
|
|
878
|
+
...this.props(p.label)
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
this.queue.push(event);
|
|
882
|
+
}
|
|
883
|
+
/** Requests/s over the last 10 s; counts this request. O(1) amortized. */
|
|
884
|
+
tickRate() {
|
|
885
|
+
const t = this.now();
|
|
886
|
+
const abs = Math.floor(t / SLOT_MS);
|
|
887
|
+
if (this.slotAbs < 0) this.slotAbs = abs;
|
|
888
|
+
if (abs > this.slotAbs) {
|
|
889
|
+
const gap = Math.min(abs - this.slotAbs, SLOTS);
|
|
890
|
+
for (let i = 1; i <= gap; i++) {
|
|
891
|
+
const k = (this.slotAbs + i) % SLOTS;
|
|
892
|
+
this.windowSum -= this.slots[k];
|
|
893
|
+
this.slots[k] = 0;
|
|
894
|
+
}
|
|
895
|
+
this.slotAbs = abs;
|
|
896
|
+
}
|
|
897
|
+
this.slots[this.slotAbs % SLOTS]++;
|
|
898
|
+
this.windowSum++;
|
|
899
|
+
return this.windowSum / (SLOTS * SLOT_MS / 1e3);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* 0 = drop, 1 = keep with weight 1, otherwise keep with this weight (1/p).
|
|
903
|
+
* Only routine scraped/recalled/skipped events are sampled, and only above
|
|
904
|
+
* 200 requests/s or when the server asked for a lower sampleRate.
|
|
905
|
+
*/
|
|
906
|
+
sampleRequest(outcome) {
|
|
907
|
+
const rate = this.tickRate();
|
|
908
|
+
if (!ROUTINE.has(outcome)) return 1;
|
|
909
|
+
const sr = this.queue.sampleRate;
|
|
910
|
+
const serverRate = typeof sr === "number" && sr > 0 && sr <= 1 ? sr : 1;
|
|
911
|
+
const p = Math.min(1, SAMPLE_THRESHOLD / rate) * serverRate;
|
|
912
|
+
if (!(p > 0) || p >= 1) return 1;
|
|
913
|
+
return this.random() < p ? 1 / p : 0;
|
|
914
|
+
}
|
|
915
|
+
/** Records pushed (dataset items). Summed per label; sent as one record_pushed per label per batch. */
|
|
916
|
+
records(label, count) {
|
|
917
|
+
if (!isNum(count) || count <= 0) return;
|
|
918
|
+
const s = this.label(label);
|
|
919
|
+
s.stats.records += count;
|
|
920
|
+
s.pendingRecords += count;
|
|
921
|
+
}
|
|
922
|
+
drainRecords() {
|
|
923
|
+
const out = [];
|
|
924
|
+
for (const [label, s] of this.labels) {
|
|
925
|
+
if (s.pendingRecords <= 0) continue;
|
|
926
|
+
out.push({ name: "record_pushed", props: { count: s.pendingRecords, ...this.props(label) } });
|
|
927
|
+
s.pendingRecords = 0;
|
|
928
|
+
}
|
|
929
|
+
return out;
|
|
930
|
+
}
|
|
931
|
+
/** Children one handler call enqueued under one child label (count = newly added). */
|
|
932
|
+
enqueued(parentLabel, childLabel, count, alreadyQueued = 0) {
|
|
933
|
+
const added = isNum(count) && count > 0 ? count : 0;
|
|
934
|
+
const already = isNum(alreadyQueued) && alreadyQueued > 0 ? alreadyQueued : 0;
|
|
935
|
+
if (added + already === 0) return;
|
|
936
|
+
const st = this.label(parentLabel).stats;
|
|
937
|
+
const child = hasOwn(st.enqueued, childLabel) || hasOwn(st.alreadyQueued, childLabel) || Object.keys(st.enqueued).length < MAX_CHILD_LABELS ? childLabel : OVERFLOW_KEY;
|
|
938
|
+
st.enqueued[child] = (hasOwn(st.enqueued, child) ? st.enqueued[child] : 0) + added;
|
|
939
|
+
st.alreadyQueued[child] = (hasOwn(st.alreadyQueued, child) ? st.alreadyQueued[child] : 0) + already;
|
|
940
|
+
this.queue.push({
|
|
941
|
+
name: "enqueued",
|
|
942
|
+
props: { childLabel: child, count: added, alreadyQueued: already, ...this.props(parentLabel) }
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* A request's final failure. Grouped by fingerprint (class + scrubbed message +
|
|
947
|
+
* top project frame); the message is scrubbed once per new raw message and the
|
|
948
|
+
* result cached. Each event carries the cumulative per-run count for its
|
|
949
|
+
* fingerprint (the server sets it, never adds).
|
|
950
|
+
*
|
|
951
|
+
* Bounds: at most 1,000 fingerprints per run. Past that, a new fingerprint is
|
|
952
|
+
* counted under the single fingerprint "overflow" (class "Overflow", empty
|
|
953
|
+
* message). The raw-message cache holds ≤2,000 truncated keys; past that, new
|
|
954
|
+
* raw messages are scrubbed without caching.
|
|
955
|
+
*/
|
|
956
|
+
error(label, err, context) {
|
|
957
|
+
const errorClass = errorClassOf(err);
|
|
958
|
+
const raw = rawMessageOf(err);
|
|
959
|
+
let frame;
|
|
960
|
+
try {
|
|
961
|
+
frame = topProjectFrame(stackOf(err));
|
|
962
|
+
} catch {
|
|
963
|
+
frame = void 0;
|
|
964
|
+
}
|
|
965
|
+
const rawKey = `${errorClass}
|
|
966
|
+
${frame ?? ""}
|
|
967
|
+
${raw.slice(0, RAW_KEY_CHARS)}`;
|
|
968
|
+
let fp = this.rawKeys.get(rawKey);
|
|
969
|
+
let message = "";
|
|
970
|
+
if (fp === void 0) {
|
|
971
|
+
try {
|
|
972
|
+
message = scrubMessage(raw);
|
|
973
|
+
} catch {
|
|
974
|
+
message = "";
|
|
975
|
+
}
|
|
976
|
+
fp = fingerprint(errorClass, message, frame);
|
|
977
|
+
if (this.rawKeys.size < MAX_RAW_KEYS) this.rawKeys.set(rawKey, fp);
|
|
978
|
+
}
|
|
979
|
+
let g = this.groups.get(fp);
|
|
980
|
+
if (!g) {
|
|
981
|
+
if (this.groups.size < MAX_FINGERPRINTS) {
|
|
982
|
+
g = { fingerprint: fp, errorClass, message, frame, count: 0 };
|
|
983
|
+
this.groups.set(fp, g);
|
|
984
|
+
} else {
|
|
985
|
+
g = this.groups.get(OVERFLOW_FINGERPRINT);
|
|
986
|
+
if (!g) {
|
|
987
|
+
g = { fingerprint: OVERFLOW_FINGERPRINT, errorClass: "Overflow", message: "", count: 0 };
|
|
988
|
+
this.groups.set(OVERFLOW_FINGERPRINT, g);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
g.count++;
|
|
993
|
+
this.queue.push({
|
|
994
|
+
name: "error",
|
|
995
|
+
props: {
|
|
996
|
+
fingerprint: g.fingerprint,
|
|
997
|
+
errorClass: g.errorClass,
|
|
998
|
+
message: g.message,
|
|
999
|
+
frame: g.frame,
|
|
1000
|
+
count: g.count,
|
|
1001
|
+
context,
|
|
1002
|
+
...this.props(label)
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
runStarted(p) {
|
|
1007
|
+
this.queue.push({
|
|
1008
|
+
name: "run_started",
|
|
1009
|
+
props: {
|
|
1010
|
+
memoryMb: isNum(p.memoryMb) ? p.memoryMb : void 0,
|
|
1011
|
+
maxConcurrency: isNum(p.maxConcurrency) ? p.maxConcurrency : void 0,
|
|
1012
|
+
...this.props("")
|
|
1013
|
+
}
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
/** The account hit a monthly limit. The caller emits it at most once per run per cap. */
|
|
1017
|
+
quotaReached(cap) {
|
|
1018
|
+
this.queue.push({ name: "quota_reached", props: { cap, ...this.props("") } });
|
|
1019
|
+
}
|
|
1020
|
+
/** Exact run totals from the in-memory counters (failed = failed + blocked final outcomes). */
|
|
1021
|
+
runFinished(p) {
|
|
1022
|
+
let requests = 0;
|
|
1023
|
+
let records = 0;
|
|
1024
|
+
let failed = 0;
|
|
1025
|
+
for (const s of this.labels.values()) {
|
|
1026
|
+
requests += s.stats.requests;
|
|
1027
|
+
records += s.stats.records;
|
|
1028
|
+
failed += s.stats.failed + s.stats.blocked;
|
|
1029
|
+
}
|
|
1030
|
+
this.queue.push({
|
|
1031
|
+
name: "run_finished",
|
|
1032
|
+
props: { requests, records, failed, durationMs: isNum(p.durationMs) ? p.durationMs : 0, ...this.props("") }
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* A developer event. Never sampled. Invalid names/props are dropped; each rejected
|
|
1037
|
+
* name (reserved, fixed, or invalid) logs one debug line per run.
|
|
1038
|
+
*/
|
|
1039
|
+
capture(name, props, label = "", context) {
|
|
1040
|
+
const clean = sanitizeCustom(name, props);
|
|
1041
|
+
if (!clean) {
|
|
1042
|
+
if (typeof name === "string" && name.length > 0) {
|
|
1043
|
+
const key = name.slice(0, 64);
|
|
1044
|
+
if (!this.rejectedNames.has(key) && this.rejectedNames.size < MAX_REJECTED_NAMES_LOGGED) {
|
|
1045
|
+
this.rejectedNames.add(key);
|
|
1046
|
+
this.debug(`Analytics: event "${key}" rejected (reserved or invalid name, or invalid props)`);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const custom = {};
|
|
1052
|
+
for (const k of Object.keys(clean.props)) if (!RESERVED_PROPS.has(k)) custom[k] = clean.props[k];
|
|
1053
|
+
if (!clean.name.startsWith("antibot.")) this.aggregates.custom(clean.name, label, custom);
|
|
1054
|
+
this.queue.push({
|
|
1055
|
+
name: clean.name,
|
|
1056
|
+
custom: true,
|
|
1057
|
+
// Base keys are reserved: a custom prop with those names is dropped, never overrides them.
|
|
1058
|
+
props: { ...custom, weight: void 0, context, ...this.props(label) }
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
/** Exact per-run URL-pattern and custom-event aggregates for the run report. */
|
|
1062
|
+
aggregateReport() {
|
|
1063
|
+
return this.aggregates.toReport();
|
|
1064
|
+
}
|
|
1065
|
+
/** Exact counters per label (copies), with percentiles from the histograms. */
|
|
1066
|
+
labelStats() {
|
|
1067
|
+
const out = {};
|
|
1068
|
+
for (const [label, s] of this.labels) {
|
|
1069
|
+
const st = {
|
|
1070
|
+
...s.stats,
|
|
1071
|
+
enqueued: { ...s.stats.enqueued },
|
|
1072
|
+
alreadyQueued: { ...s.stats.alreadyQueued },
|
|
1073
|
+
status: { ...s.stats.status }
|
|
1074
|
+
};
|
|
1075
|
+
const navP50 = percentile(s.nav, s.navN, 0.5);
|
|
1076
|
+
const navP95 = percentile(s.nav, s.navN, 0.95);
|
|
1077
|
+
const handlerP95 = percentile(s.handler, s.handlerN, 0.95);
|
|
1078
|
+
if (navP50 !== void 0) st.navP50 = navP50;
|
|
1079
|
+
if (navP95 !== void 0) st.navP95 = navP95;
|
|
1080
|
+
if (handlerP95 !== void 0) st.handlerP95 = handlerP95;
|
|
1081
|
+
out[label] = st;
|
|
1082
|
+
}
|
|
1083
|
+
return out;
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
7
1088
|
|
|
8
1089
|
// src/circuit-breaker.ts
|
|
9
1090
|
var DEFAULT_CONFIG = {
|
|
@@ -479,6 +1560,14 @@ var ApiError = class extends Error {
|
|
|
479
1560
|
this.name = "ApiError";
|
|
480
1561
|
}
|
|
481
1562
|
};
|
|
1563
|
+
var TERMINAL_ANALYTICS_STATUSES = /* @__PURE__ */ new Set([400, 413, 415, 422]);
|
|
1564
|
+
var ANALYTICS_RATE_LIMIT_PAUSE_SEC = 10;
|
|
1565
|
+
var BadReplyError = class extends Error {
|
|
1566
|
+
constructor(message) {
|
|
1567
|
+
super(message);
|
|
1568
|
+
this.name = "BadReplyError";
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
482
1571
|
function parseRetryAfter(header) {
|
|
483
1572
|
if (!header) return void 0;
|
|
484
1573
|
const secs = Number(header);
|
|
@@ -517,13 +1606,20 @@ var FetchBrainClient = class {
|
|
|
517
1606
|
this.warnedOversizeLearn = false;
|
|
518
1607
|
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
519
1608
|
this.learnCapWarnedUntil = 0;
|
|
1609
|
+
/**
|
|
1610
|
+
* The monthly recall limit answered HARD_CAP_EXCEEDED. Recall (handler-time and
|
|
1611
|
+
* enqueue-time bulk) stops for the rest of the run. Per client instance; reset by
|
|
1612
|
+
* beginRun() so each new run() tries once more (a plan can reset between runs).
|
|
1613
|
+
*/
|
|
1614
|
+
this.recallCapped = false;
|
|
520
1615
|
/** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
|
|
521
|
-
this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
|
|
1616
|
+
this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [], known: 0 };
|
|
522
1617
|
this.logger = createLogger(config.debug ? "debug" : "info", true);
|
|
523
1618
|
this.config = {
|
|
524
1619
|
apiKey: config.apiKey,
|
|
525
1620
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
526
1621
|
memory: config.memory || "recent",
|
|
1622
|
+
recall: config.recall ?? true,
|
|
527
1623
|
learning: config.learning ?? true,
|
|
528
1624
|
alwaysRun: config.alwaysRun ?? false,
|
|
529
1625
|
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
@@ -532,8 +1628,6 @@ var FetchBrainClient = class {
|
|
|
532
1628
|
debug: config.debug || false,
|
|
533
1629
|
extractForLearning: config.extractForLearning,
|
|
534
1630
|
learnUrlField: config.learnUrlField,
|
|
535
|
-
telemetry: config.telemetry ?? { enabled: false },
|
|
536
|
-
// opt-in
|
|
537
1631
|
batch: config.batch,
|
|
538
1632
|
circuitBreaker: config.circuitBreaker,
|
|
539
1633
|
skipLabels: config.skipLabels,
|
|
@@ -546,6 +1640,8 @@ var FetchBrainClient = class {
|
|
|
546
1640
|
// enhance-only; stored so getConfig() round-trips
|
|
547
1641
|
scraper: config.scraper,
|
|
548
1642
|
changeDetection: config.changeDetection,
|
|
1643
|
+
analytics: config.analytics,
|
|
1644
|
+
// enhance-only; stored so getConfig() round-trips
|
|
549
1645
|
reportRuns: config.reportRuns ?? true
|
|
550
1646
|
};
|
|
551
1647
|
const scraper = resolveScraperName(config.scraper);
|
|
@@ -564,6 +1660,11 @@ var FetchBrainClient = class {
|
|
|
564
1660
|
this.logger,
|
|
565
1661
|
"Ask"
|
|
566
1662
|
);
|
|
1663
|
+
this.analyticsCircuitBreaker = new CircuitBreaker(
|
|
1664
|
+
this.config.circuitBreaker,
|
|
1665
|
+
this.logger,
|
|
1666
|
+
"Analytics"
|
|
1667
|
+
);
|
|
567
1668
|
this.batcher = new RequestBatcher(
|
|
568
1669
|
(items) => this.executeBatchQuery(items),
|
|
569
1670
|
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
@@ -577,11 +1678,45 @@ var FetchBrainClient = class {
|
|
|
577
1678
|
}
|
|
578
1679
|
/** True when recalls must not reach the API right now (crawl continues without). */
|
|
579
1680
|
recallBlocked() {
|
|
580
|
-
return this.isKeyRejected() || this.circuitBreaker.isOpen();
|
|
1681
|
+
return this.recallCapped || this.isKeyRejected() || this.circuitBreaker.isOpen();
|
|
1682
|
+
}
|
|
1683
|
+
/** Where the account stands against its limits: recall cap wins over learn cap. */
|
|
1684
|
+
quotaState() {
|
|
1685
|
+
if (this.recallCapped) return "recall_cap";
|
|
1686
|
+
if (Date.now() < this.learnCapWarnedUntil) return "learn_cap";
|
|
1687
|
+
return "ok";
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Start of a run(): the recall limit is retried once (plans can reset between
|
|
1691
|
+
* runs); if the API still answers HARD_CAP_EXCEEDED, recall stops again for
|
|
1692
|
+
* that run. The learn cap is month-bound and keeps its own pause.
|
|
1693
|
+
*/
|
|
1694
|
+
beginRun() {
|
|
1695
|
+
this.recallCapped = false;
|
|
1696
|
+
}
|
|
1697
|
+
/** Called (never throws into the caller) when a limit is first seen. Pass undefined to clear. */
|
|
1698
|
+
onQuotaReached(listener) {
|
|
1699
|
+
this.quotaListener = listener;
|
|
1700
|
+
}
|
|
1701
|
+
notifyQuota(cap) {
|
|
1702
|
+
try {
|
|
1703
|
+
this.quotaListener?.(cap);
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
this.logger.debug("Quota listener failed:", err);
|
|
1706
|
+
}
|
|
581
1707
|
}
|
|
582
1708
|
isKeyRejected() {
|
|
583
1709
|
return Date.now() < this.keyRejectedUntil;
|
|
584
1710
|
}
|
|
1711
|
+
/** A 403 HARD_CAP_EXCEEDED on recall: warn once, pause recall for the run, tell the listener. */
|
|
1712
|
+
noteRecallCap(error) {
|
|
1713
|
+
if (!(error instanceof ApiError) || error.status !== 403 || error.code !== "HARD_CAP_EXCEEDED" && error.serverError !== "HARD_CAP_EXCEEDED" || this.recallCapped) {
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
this.recallCapped = true;
|
|
1717
|
+
this.logger.warn("Monthly recall limit reached \u2014 recall is paused until your plan resets; pages are fetched normally.");
|
|
1718
|
+
this.notifyQuota("recall");
|
|
1719
|
+
}
|
|
585
1720
|
/**
|
|
586
1721
|
* React to a 4xx the API returned. These are not outages (they don't open the
|
|
587
1722
|
* shared breaker). A 401 means the next calls would fail the same way, so all
|
|
@@ -701,7 +1836,7 @@ var FetchBrainClient = class {
|
|
|
701
1836
|
* Ask a natural-language question, answered from everything the account has learned
|
|
702
1837
|
*
|
|
703
1838
|
* `model` picks the generation model for answer mode from the server's
|
|
704
|
-
* menu (e.g. "llama-3.3-70b", "
|
|
1839
|
+
* menu (e.g. "llama-3.3-70b", "glm-5.3" — larger models use more Ask
|
|
705
1840
|
* credits), or "byok" to answer with your own linked provider model.
|
|
706
1841
|
* Omit it for the default model.
|
|
707
1842
|
*
|
|
@@ -779,8 +1914,10 @@ var FetchBrainClient = class {
|
|
|
779
1914
|
}
|
|
780
1915
|
return results;
|
|
781
1916
|
} catch (error) {
|
|
782
|
-
if (!isOutage(error))
|
|
783
|
-
|
|
1917
|
+
if (!isOutage(error)) {
|
|
1918
|
+
this.noteRefusal(error);
|
|
1919
|
+
this.noteRecallCap(error);
|
|
1920
|
+
} else if (outcome) outcome.outage = true;
|
|
784
1921
|
else this.circuitBreaker.recordFailure();
|
|
785
1922
|
throw error;
|
|
786
1923
|
}
|
|
@@ -799,6 +1936,10 @@ var FetchBrainClient = class {
|
|
|
799
1936
|
const request = { entries };
|
|
800
1937
|
const ignore = this.config.changeDetection?.ignoreFields;
|
|
801
1938
|
if (ignore && ignore.length > 0) request.ignore = ignore;
|
|
1939
|
+
if (this.config.recall === false) {
|
|
1940
|
+
request.observe = true;
|
|
1941
|
+
request.memory = this.config.memory;
|
|
1942
|
+
}
|
|
802
1943
|
const platformBuildId = getPlatformBuildId();
|
|
803
1944
|
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
804
1945
|
request.build = platformBuildId;
|
|
@@ -819,6 +1960,7 @@ var FetchBrainClient = class {
|
|
|
819
1960
|
const now = /* @__PURE__ */ new Date();
|
|
820
1961
|
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
821
1962
|
this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
|
|
1963
|
+
this.notifyQuota("learn");
|
|
822
1964
|
if (this.learnCapWarnedUntil < monthStart) {
|
|
823
1965
|
this.learnCapWarnedUntil = monthStart;
|
|
824
1966
|
this.logger.warn(
|
|
@@ -865,6 +2007,7 @@ var FetchBrainClient = class {
|
|
|
865
2007
|
stats.changed += num(response.changed);
|
|
866
2008
|
stats.unchanged += num(response.unchanged);
|
|
867
2009
|
stats.firstSeen += num(response.firstSeen);
|
|
2010
|
+
stats.known = (stats.known ?? 0) + num(response.known);
|
|
868
2011
|
const drift = Array.isArray(response.drift) ? response.drift : [];
|
|
869
2012
|
for (const item of drift) {
|
|
870
2013
|
if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
|
|
@@ -891,7 +2034,7 @@ var FetchBrainClient = class {
|
|
|
891
2034
|
* failure or timeout it returns no flags.
|
|
892
2035
|
*/
|
|
893
2036
|
async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
|
|
894
|
-
if (this.config.reportRuns === false || this.
|
|
2037
|
+
if (this.config.reportRuns === false || this.isKeyRejected() || this.circuitBreaker.isOpen()) return [];
|
|
895
2038
|
try {
|
|
896
2039
|
const response = await this.makeRequest(
|
|
897
2040
|
"/v1/runs",
|
|
@@ -906,12 +2049,95 @@ var FetchBrainClient = class {
|
|
|
906
2049
|
return [];
|
|
907
2050
|
}
|
|
908
2051
|
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Ship one gzipped analytics batch. Never throws. null = retry later (outage,
|
|
2054
|
+
* breaker open, key rejected, other 4xx, 429 without Retry-After, bad 2xx body);
|
|
2055
|
+
* `{ drop: true }` = the server permanently refused this batch (400/413/415/422),
|
|
2056
|
+
* so discard it.
|
|
2057
|
+
*/
|
|
2058
|
+
async postAnalyticsEvents(body, _runId, signal) {
|
|
2059
|
+
if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
|
|
2060
|
+
try {
|
|
2061
|
+
const response = await this.makeRequest(
|
|
2062
|
+
"/v1/analytics/events",
|
|
2063
|
+
{
|
|
2064
|
+
method: "POST",
|
|
2065
|
+
body,
|
|
2066
|
+
headers: {
|
|
2067
|
+
"Content-Type": "application/json",
|
|
2068
|
+
"Content-Encoding": "gzip"
|
|
2069
|
+
}
|
|
2070
|
+
},
|
|
2071
|
+
DEFAULT_LEARN_TIMEOUT,
|
|
2072
|
+
{ signal, lenientBody: true }
|
|
2073
|
+
);
|
|
2074
|
+
this.analyticsCircuitBreaker.recordSuccess();
|
|
2075
|
+
const out = {};
|
|
2076
|
+
if (response && typeof response.sampleRate === "number") out.sampleRate = response.sampleRate;
|
|
2077
|
+
if (response && typeof response.pauseUntil === "number") out.pauseUntil = response.pauseUntil;
|
|
2078
|
+
return out;
|
|
2079
|
+
} catch (error) {
|
|
2080
|
+
this.noteRefusal(error);
|
|
2081
|
+
if (signal?.aborted) {
|
|
2082
|
+
return null;
|
|
2083
|
+
} else if (error instanceof BadReplyError) {
|
|
2084
|
+
this.analyticsCircuitBreaker.recordFailure();
|
|
2085
|
+
this.logger.debug("Analytics reply was not JSON:", error);
|
|
2086
|
+
return null;
|
|
2087
|
+
} else if (isOutage(error)) {
|
|
2088
|
+
this.analyticsCircuitBreaker.recordFailure();
|
|
2089
|
+
} else if (error instanceof ApiError) {
|
|
2090
|
+
if (error.status === 429) {
|
|
2091
|
+
const hinted = error.retryAfterSec;
|
|
2092
|
+
const waitSec = typeof hinted === "number" && Number.isFinite(hinted) && hinted > 0 ? Math.min(Math.max(hinted, 1), 3600) : ANALYTICS_RATE_LIMIT_PAUSE_SEC;
|
|
2093
|
+
return { pauseUntil: Date.now() + waitSec * 1e3, retry: true };
|
|
2094
|
+
} else if (TERMINAL_ANALYTICS_STATUSES.has(error.status)) {
|
|
2095
|
+
this.logger.debug("Analytics batch refused:", error);
|
|
2096
|
+
return { drop: true };
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
this.logger.debug("Analytics events post failed:", error);
|
|
2100
|
+
return null;
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
/** The resolved scraper name (valid option, else env var); undefined = default memory. */
|
|
2104
|
+
getScraperName() {
|
|
2105
|
+
return this.scraperName;
|
|
2106
|
+
}
|
|
2107
|
+
/** Fetch the analytics config for this key. Never throws: failure returns null. */
|
|
2108
|
+
async getAnalyticsConfig() {
|
|
2109
|
+
if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
|
|
2110
|
+
try {
|
|
2111
|
+
const r = await this.makeRequest("/v1/analytics/config", { method: "GET" });
|
|
2112
|
+
this.analyticsCircuitBreaker.recordSuccess();
|
|
2113
|
+
if (!r || typeof r.enabled !== "boolean") return null;
|
|
2114
|
+
const salt = typeof r.salt === "string" ? r.salt : "";
|
|
2115
|
+
if (!r.enabled) return { enabled: false, salt, sampleRate: 1 };
|
|
2116
|
+
return {
|
|
2117
|
+
salt,
|
|
2118
|
+
sampleRate: typeof r.sampleRate === "number" ? r.sampleRate : 1,
|
|
2119
|
+
...typeof r.pauseUntil === "number" ? { pauseUntil: r.pauseUntil } : {},
|
|
2120
|
+
enabled: true
|
|
2121
|
+
};
|
|
2122
|
+
} catch (error) {
|
|
2123
|
+
this.noteRefusal(error);
|
|
2124
|
+
if (isOutage(error)) this.analyticsCircuitBreaker.recordFailure();
|
|
2125
|
+
this.logger.debug("Analytics config fetch failed:", error);
|
|
2126
|
+
return null;
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
909
2129
|
/**
|
|
910
2130
|
* Make an HTTP request to the API
|
|
911
2131
|
*/
|
|
912
|
-
async makeRequest(path, options, timeout) {
|
|
2132
|
+
async makeRequest(path, options, timeout, extra) {
|
|
913
2133
|
const url = `${this.config.baseUrl}${path}`;
|
|
914
2134
|
const controller = new AbortController();
|
|
2135
|
+
const external = extra?.signal;
|
|
2136
|
+
const onExternalAbort = () => controller.abort();
|
|
2137
|
+
if (external) {
|
|
2138
|
+
if (external.aborted) controller.abort();
|
|
2139
|
+
else external.addEventListener("abort", onExternalAbort, { once: true });
|
|
2140
|
+
}
|
|
915
2141
|
const timeoutId = setTimeout(
|
|
916
2142
|
() => controller.abort(),
|
|
917
2143
|
timeout ?? this.config.timeout
|
|
@@ -975,9 +2201,24 @@ var FetchBrainClient = class {
|
|
|
975
2201
|
parseRetryAfter(response.headers.get("Retry-After"))
|
|
976
2202
|
);
|
|
977
2203
|
}
|
|
2204
|
+
if (extra?.lenientBody) {
|
|
2205
|
+
const text = await readBody(response, (r) => r.text());
|
|
2206
|
+
if (response.status === 204 || text.length === 0) return {};
|
|
2207
|
+
let parsed;
|
|
2208
|
+
try {
|
|
2209
|
+
parsed = JSON.parse(text);
|
|
2210
|
+
} catch {
|
|
2211
|
+
throw new BadReplyError("Unexpected non-JSON reply");
|
|
2212
|
+
}
|
|
2213
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2214
|
+
throw new BadReplyError("Unexpected reply shape");
|
|
2215
|
+
}
|
|
2216
|
+
return parsed;
|
|
2217
|
+
}
|
|
978
2218
|
return await readBody(response, (r) => r.json());
|
|
979
2219
|
} finally {
|
|
980
2220
|
clearTimeout(timeoutId);
|
|
2221
|
+
external?.removeEventListener("abort", onExternalAbort);
|
|
981
2222
|
}
|
|
982
2223
|
}
|
|
983
2224
|
/**
|
|
@@ -1019,181 +2260,42 @@ var FetchBrainClient = class {
|
|
|
1019
2260
|
async flushLearnBatch() {
|
|
1020
2261
|
await this.learnBatcher.forceFlush();
|
|
1021
2262
|
}
|
|
1022
|
-
/**
|
|
1023
|
-
* Send telemetry data to the API
|
|
1024
|
-
* This is fire-and-forget - failures are silently ignored
|
|
1025
|
-
*/
|
|
1026
|
-
async sendTelemetry(entries) {
|
|
1027
|
-
if (!this.config.telemetry?.enabled || entries.length === 0) {
|
|
1028
|
-
return;
|
|
1029
|
-
}
|
|
1030
|
-
try {
|
|
1031
|
-
await this.makeRequest("/v1/telemetry", {
|
|
1032
|
-
method: "POST",
|
|
1033
|
-
body: JSON.stringify({ entries })
|
|
1034
|
-
});
|
|
1035
|
-
} catch {
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
/**
|
|
1039
|
-
* Check if telemetry is enabled
|
|
1040
|
-
*/
|
|
1041
|
-
isTelemetryEnabled() {
|
|
1042
|
-
return this.config.telemetry?.enabled ?? false;
|
|
1043
|
-
}
|
|
1044
|
-
/**
|
|
1045
|
-
* Get telemetry config
|
|
1046
|
-
*/
|
|
1047
|
-
getTelemetryConfig() {
|
|
1048
|
-
return this.config.telemetry;
|
|
1049
|
-
}
|
|
1050
2263
|
};
|
|
1051
2264
|
|
|
1052
|
-
// src/
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
2265
|
+
// src/enhance.ts
|
|
2266
|
+
var collectorModule;
|
|
2267
|
+
function loadCollector() {
|
|
2268
|
+
return collectorModule ?? (collectorModule = Promise.resolve().then(() => (init_collector(), collector_exports)).catch(() => {
|
|
2269
|
+
collectorModule = void 0;
|
|
2270
|
+
return void 0;
|
|
2271
|
+
}));
|
|
1059
2272
|
}
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
2273
|
+
var MAX_TALLY_LABELS = 50;
|
|
2274
|
+
var DEFAULT_CHILD_LABEL = "_nolabel";
|
|
2275
|
+
var ANALYTICS_CONFIG_TIMEOUT_MS = 500;
|
|
2276
|
+
var MAX_BLOCKED_TRACKED = 1e4;
|
|
2277
|
+
var msSince = (t0) => Math.round(performance.now() - t0);
|
|
2278
|
+
function statusFrom(response) {
|
|
2279
|
+
const r = response;
|
|
2280
|
+
if (!r) return void 0;
|
|
2281
|
+
if (typeof r.statusCode === "number") return r.statusCode;
|
|
2282
|
+
if (typeof r.status === "function") {
|
|
2283
|
+
const s = r.status.call(r);
|
|
2284
|
+
return typeof s === "number" ? s : void 0;
|
|
1065
2285
|
}
|
|
1066
|
-
}
|
|
1067
|
-
function generalizeUrlPath(url) {
|
|
1068
|
-
try {
|
|
1069
|
-
const parsed = new URL(url);
|
|
1070
|
-
const path = parsed.pathname;
|
|
1071
|
-
return path.replace(/\/\d+/g, "/*").replace(/\/[a-f0-9-]{36}/gi, "/*").replace(/\/[a-zA-Z0-9]{20,}/g, "/*").replace(/\?.*$/, "");
|
|
1072
|
-
} catch {
|
|
1073
|
-
return "/*";
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
function detectBlockType(statusCode, errorMessage) {
|
|
1077
|
-
if (!statusCode && !errorMessage) return void 0;
|
|
1078
|
-
if (statusCode === 403) return "403";
|
|
1079
|
-
if (statusCode === 429) return "429";
|
|
1080
|
-
if (statusCode === 503) return "503";
|
|
1081
|
-
if (statusCode && statusCode >= 400) return `${statusCode}`;
|
|
1082
|
-
const msg = errorMessage?.toLowerCase() || "";
|
|
1083
|
-
if (msg.includes("captcha")) return "captcha";
|
|
1084
|
-
if (msg.includes("timeout")) return "timeout";
|
|
1085
|
-
if (msg.includes("blocked")) return "blocked";
|
|
1086
|
-
if (msg.includes("rate limit")) return "429";
|
|
1087
2286
|
return void 0;
|
|
1088
2287
|
}
|
|
1089
|
-
function
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
if (
|
|
1093
|
-
|
|
1094
|
-
if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
|
|
1095
|
-
if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
|
|
1096
|
-
return "residential";
|
|
1097
|
-
}
|
|
1098
|
-
return "datacenter";
|
|
2288
|
+
function bodyBytes(context) {
|
|
2289
|
+
const body = context.body;
|
|
2290
|
+
if (Buffer.isBuffer(body)) return body.length;
|
|
2291
|
+
if (typeof body === "string") return Buffer.byteLength(body);
|
|
2292
|
+
return void 0;
|
|
1099
2293
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
const url = context.request.url;
|
|
1105
|
-
const statusCode = context.response?.status || context.response?.statusCode;
|
|
1106
|
-
const telemetry = {
|
|
1107
|
-
domain: extractDomain(url),
|
|
1108
|
-
urlHash: await hashString(url),
|
|
1109
|
-
urlPattern: generalizeUrlPath(url),
|
|
1110
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1111
|
-
};
|
|
1112
|
-
if (config.sharePerformance !== false) {
|
|
1113
|
-
telemetry.statusCode = statusCode;
|
|
1114
|
-
telemetry.retryCount = context.request.retryCount;
|
|
1115
|
-
if (timing) {
|
|
1116
|
-
telemetry.responseTimeMs = timing.responseTime;
|
|
1117
|
-
telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
|
|
1118
|
-
telemetry.contentSize = timing.contentSize;
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
if (config.shareProxyInfo !== false && context.proxyInfo) {
|
|
1122
|
-
telemetry.proxyCountry = context.proxyInfo.countryCode;
|
|
1123
|
-
telemetry.proxyType = extractProxyType(context.proxyInfo.url);
|
|
1124
|
-
telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
|
|
1125
|
-
}
|
|
1126
|
-
if (config.shareSitePatterns !== false) {
|
|
1127
|
-
const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
|
|
1128
|
-
telemetry.blocked = isBlocked || !!error;
|
|
1129
|
-
telemetry.blockType = detectBlockType(statusCode, error?.message);
|
|
1130
|
-
}
|
|
1131
|
-
if (context.session) {
|
|
1132
|
-
telemetry.sessionAge = context.session.usageCount;
|
|
1133
|
-
telemetry.sessionErrorScore = context.session.errorScore;
|
|
1134
|
-
}
|
|
1135
|
-
telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
|
|
1136
|
-
telemetry.requestLabel = context.request.label;
|
|
1137
|
-
return telemetry;
|
|
2294
|
+
function headerBytes(response) {
|
|
2295
|
+
const headers = response?.headers;
|
|
2296
|
+
const len = headers && typeof headers === "object" ? Number(headers["content-length"]) : NaN;
|
|
2297
|
+
return Number.isFinite(len) && len >= 0 ? len : void 0;
|
|
1138
2298
|
}
|
|
1139
|
-
var TelemetryBuffer = class {
|
|
1140
|
-
constructor(options = {}) {
|
|
1141
|
-
this.buffer = [];
|
|
1142
|
-
this.maxSize = options.maxSize ?? 50;
|
|
1143
|
-
this.flushInterval = options.flushInterval ?? 3e4;
|
|
1144
|
-
this.flushCallback = options.onFlush;
|
|
1145
|
-
this.startFlushTimer();
|
|
1146
|
-
}
|
|
1147
|
-
/**
|
|
1148
|
-
* Add telemetry entry to buffer
|
|
1149
|
-
*/
|
|
1150
|
-
add(entry) {
|
|
1151
|
-
if (!entry) return;
|
|
1152
|
-
this.buffer.push(entry);
|
|
1153
|
-
if (this.buffer.length >= this.maxSize) {
|
|
1154
|
-
this.flush();
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
/**
|
|
1158
|
-
* Flush buffer and send telemetry
|
|
1159
|
-
*/
|
|
1160
|
-
async flush() {
|
|
1161
|
-
if (this.buffer.length === 0) return [];
|
|
1162
|
-
const entries = [...this.buffer];
|
|
1163
|
-
this.buffer = [];
|
|
1164
|
-
if (this.flushCallback) {
|
|
1165
|
-
try {
|
|
1166
|
-
await this.flushCallback(entries);
|
|
1167
|
-
} catch (err) {
|
|
1168
|
-
console.debug("Telemetry flush failed:", err);
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
return entries;
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Get current buffer size
|
|
1175
|
-
*/
|
|
1176
|
-
get size() {
|
|
1177
|
-
return this.buffer.length;
|
|
1178
|
-
}
|
|
1179
|
-
startFlushTimer() {
|
|
1180
|
-
this.flushTimer = setInterval(() => {
|
|
1181
|
-
this.flush();
|
|
1182
|
-
}, this.flushInterval);
|
|
1183
|
-
this.flushTimer.unref?.();
|
|
1184
|
-
}
|
|
1185
|
-
/**
|
|
1186
|
-
* Stop the flush timer and flush remaining entries
|
|
1187
|
-
*/
|
|
1188
|
-
async stop() {
|
|
1189
|
-
if (this.flushTimer) {
|
|
1190
|
-
clearInterval(this.flushTimer);
|
|
1191
|
-
}
|
|
1192
|
-
await this.flush();
|
|
1193
|
-
}
|
|
1194
|
-
};
|
|
1195
|
-
|
|
1196
|
-
// src/enhance.ts
|
|
1197
2299
|
var REPORT_MAX_LABELS = 50;
|
|
1198
2300
|
var REPORT_LABEL_MAX_CHARS = 64;
|
|
1199
2301
|
var RUN_ID_MAX_CHARS = 128;
|
|
@@ -1201,14 +2303,14 @@ var NO_LABEL = "_nolabel";
|
|
|
1201
2303
|
var platformRunSeq = /* @__PURE__ */ new Map();
|
|
1202
2304
|
function nextRunId() {
|
|
1203
2305
|
const platform = process.env.APIFY_ACTOR_RUN_ID;
|
|
1204
|
-
if (!platform) return crypto
|
|
2306
|
+
if (!platform) return crypto.randomUUID();
|
|
1205
2307
|
const id = platform.slice(0, RUN_ID_MAX_CHARS - 8);
|
|
1206
2308
|
const n = (platformRunSeq.get(id) ?? 0) + 1;
|
|
1207
2309
|
platformRunSeq.set(id, n);
|
|
1208
2310
|
return n === 1 ? id : `${id}-${n}`;
|
|
1209
2311
|
}
|
|
1210
2312
|
function labelText(label) {
|
|
1211
|
-
if (typeof label === "string") return label;
|
|
2313
|
+
if (typeof label === "string") return label.replace(/^[\s~]+/, "");
|
|
1212
2314
|
if (typeof label === "number" || typeof label === "boolean") return String(label);
|
|
1213
2315
|
return void 0;
|
|
1214
2316
|
}
|
|
@@ -1221,6 +2323,25 @@ function describeDrift(d) {
|
|
|
1221
2323
|
const detail = d.kind === "type_changed" ? `type ${clipText(d.from, 32)} \u2192 ${clipText(d.to, 32)}` : `filled ${pct(Number(d.from))} \u2192 ${pct(Number(d.to))}`;
|
|
1222
2324
|
return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
|
|
1223
2325
|
}
|
|
2326
|
+
function safeBeginRun(client) {
|
|
2327
|
+
try {
|
|
2328
|
+
client.beginRun();
|
|
2329
|
+
} catch {
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
function safeQuotaState(client) {
|
|
2333
|
+
try {
|
|
2334
|
+
return client.quotaState();
|
|
2335
|
+
} catch {
|
|
2336
|
+
return "ok";
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
function safeOnQuotaReached(client, listener) {
|
|
2340
|
+
try {
|
|
2341
|
+
client.onQuotaReached(listener);
|
|
2342
|
+
} catch {
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
1224
2345
|
function safeChangeStats(client) {
|
|
1225
2346
|
try {
|
|
1226
2347
|
return client.getChangeStats();
|
|
@@ -1302,9 +2423,53 @@ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
|
|
|
1302
2423
|
}
|
|
1303
2424
|
}
|
|
1304
2425
|
var asyncContext = new async_hooks.AsyncLocalStorage();
|
|
2426
|
+
var noopCapture = () => {
|
|
2427
|
+
};
|
|
2428
|
+
var recordCount = (data) => Array.isArray(data) ? data.length : 1;
|
|
2429
|
+
function childLabelOf(r) {
|
|
2430
|
+
if (!r || typeof r !== "object") return DEFAULT_CHILD_LABEL;
|
|
2431
|
+
try {
|
|
2432
|
+
const o = r;
|
|
2433
|
+
const text = labelText(o.label ?? o.userData?.label)?.trim().slice(0, REPORT_LABEL_MAX_CHARS);
|
|
2434
|
+
return text || DEFAULT_CHILD_LABEL;
|
|
2435
|
+
} catch {
|
|
2436
|
+
return DEFAULT_CHILD_LABEL;
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
function tallyAdd(t, label, added, already) {
|
|
2440
|
+
const key = t.has(label) || t.size < MAX_TALLY_LABELS ? label : "~other";
|
|
2441
|
+
const cur = t.get(key);
|
|
2442
|
+
if (cur) {
|
|
2443
|
+
cur[0] += added;
|
|
2444
|
+
cur[1] += already;
|
|
2445
|
+
} else {
|
|
2446
|
+
t.set(key, [added, already]);
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
function userDataForCallback(userData) {
|
|
2450
|
+
if (!userData) return {};
|
|
2451
|
+
let hasSdkKey = false;
|
|
2452
|
+
for (const k of SDK_USERDATA_KEYS) if (k in userData) hasSdkKey = true;
|
|
2453
|
+
if (!hasSdkKey) return userData;
|
|
2454
|
+
const out = {};
|
|
2455
|
+
for (const [k, v] of Object.entries(userData)) if (!SDK_USERDATA_KEYS.has(k)) out[k] = v;
|
|
2456
|
+
return out;
|
|
2457
|
+
}
|
|
1305
2458
|
function getCurrentContext() {
|
|
1306
2459
|
return asyncContext.getStore();
|
|
1307
2460
|
}
|
|
2461
|
+
async function fetchAnalyticsConfig(client) {
|
|
2462
|
+
let timer;
|
|
2463
|
+
const timeout = new Promise((resolve) => {
|
|
2464
|
+
timer = setTimeout(() => resolve(null), ANALYTICS_CONFIG_TIMEOUT_MS);
|
|
2465
|
+
timer.unref?.();
|
|
2466
|
+
});
|
|
2467
|
+
try {
|
|
2468
|
+
return await Promise.race([client.getAnalyticsConfig().catch(() => null), timeout]);
|
|
2469
|
+
} finally {
|
|
2470
|
+
if (timer) clearTimeout(timer);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
1308
2473
|
function shouldRunHandler(alwaysRun, label) {
|
|
1309
2474
|
if (alwaysRun === void 0 || alwaysRun === false) {
|
|
1310
2475
|
return false;
|
|
@@ -1355,19 +2520,9 @@ var FetchBrain = class {
|
|
|
1355
2520
|
* @returns Enhanced crawler with same interface
|
|
1356
2521
|
*/
|
|
1357
2522
|
static enhance(crawler, config) {
|
|
1358
|
-
const client = new FetchBrainClient(config);
|
|
2523
|
+
const client = Object.assign(new FetchBrainClient(config), { capture: noopCapture });
|
|
1359
2524
|
const logger = createLogger(config.debug ? "debug" : "info", true);
|
|
1360
|
-
const
|
|
1361
|
-
const telemetryBuffer = new TelemetryBuffer({
|
|
1362
|
-
maxSize: 50,
|
|
1363
|
-
flushInterval: 3e4,
|
|
1364
|
-
onFlush: async (entries) => {
|
|
1365
|
-
if (telemetryConfig.enabled) {
|
|
1366
|
-
await client.sendTelemetry(entries);
|
|
1367
|
-
logger.debug(`Telemetry: sent ${entries.length} entries`);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
});
|
|
2525
|
+
const observe = config.recall === false;
|
|
1371
2526
|
const runStats = {
|
|
1372
2527
|
totalRequests: 0,
|
|
1373
2528
|
recalled: 0,
|
|
@@ -1446,19 +2601,302 @@ var FetchBrain = class {
|
|
|
1446
2601
|
return void 0;
|
|
1447
2602
|
};
|
|
1448
2603
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
2604
|
+
const analyticsOn = config.analytics?.enabled === true;
|
|
2605
|
+
if (analyticsOn) void loadCollector();
|
|
2606
|
+
let collector;
|
|
2607
|
+
const attempts = /* @__PURE__ */ new WeakMap();
|
|
2608
|
+
const blockedByRequest = /* @__PURE__ */ new Map();
|
|
2609
|
+
const emittedThenFailed = /* @__PURE__ */ new Set();
|
|
2610
|
+
const attemptOf = (ctx) => {
|
|
2611
|
+
let a = attempts.get(ctx);
|
|
2612
|
+
if (!a) {
|
|
2613
|
+
a = {};
|
|
2614
|
+
attempts.set(ctx, a);
|
|
2615
|
+
}
|
|
2616
|
+
return a;
|
|
2617
|
+
};
|
|
2618
|
+
const requestKey = (r) => String(r.id ?? r.uniqueKey ?? r.url);
|
|
2619
|
+
const emitRequest = (c, ctx, a, outcome, blockType) => {
|
|
2620
|
+
if (a.emitted) return;
|
|
2621
|
+
a.emitted = true;
|
|
2622
|
+
const request = ctx.request;
|
|
2623
|
+
const key = requestKey(request);
|
|
2624
|
+
if (emittedThenFailed.size > 0 && emittedThenFailed.has(key)) return;
|
|
2625
|
+
const blockedAttempts = blockedByRequest.get(key) ?? 0;
|
|
2626
|
+
if (blockedAttempts) blockedByRequest.delete(key);
|
|
2627
|
+
c.request({
|
|
2628
|
+
label: reportLabel(request.label),
|
|
2629
|
+
outcome,
|
|
2630
|
+
retries: typeof request.retryCount === "number" ? request.retryCount : 0,
|
|
2631
|
+
url: request.url,
|
|
2632
|
+
statusCode: a.statusCode,
|
|
2633
|
+
navMs: a.navMs,
|
|
2634
|
+
handlerMs: a.handlerMs,
|
|
2635
|
+
recallMs: a.recallMs,
|
|
2636
|
+
bytes: a.bytes,
|
|
2637
|
+
blockType,
|
|
2638
|
+
blockedAttempts,
|
|
2639
|
+
// Evaluated only if the event survives sampling.
|
|
2640
|
+
context: () => contextFor(c, a, request)
|
|
2641
|
+
});
|
|
2642
|
+
};
|
|
2643
|
+
const recordSuccess = (context, outcome, handlerMs, recallMs) => {
|
|
2644
|
+
const c = collector;
|
|
2645
|
+
if (!c) return;
|
|
2646
|
+
try {
|
|
2647
|
+
const a = attemptOf(context);
|
|
2648
|
+
if (a.failed) return;
|
|
2649
|
+
a.handlerMs = handlerMs;
|
|
2650
|
+
a.recallMs = recallMs;
|
|
2651
|
+
a.bytes = bodyBytes(context) ?? a.bytes;
|
|
2652
|
+
emitRequest(c, context, a, outcome);
|
|
2653
|
+
} catch (analyticsErr) {
|
|
2654
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2655
|
+
}
|
|
2656
|
+
};
|
|
2657
|
+
const noteFailure = (c, ctx, err) => {
|
|
2658
|
+
const a = attemptOf(ctx);
|
|
2659
|
+
a.failed = true;
|
|
2660
|
+
if (a.emitted && emittedThenFailed.size < MAX_BLOCKED_TRACKED) {
|
|
2661
|
+
emittedThenFailed.add(requestKey(ctx.request));
|
|
2662
|
+
}
|
|
2663
|
+
a.statusCode ?? (a.statusCode = statusFrom(ctx.response));
|
|
2664
|
+
const message = err instanceof Error ? err.message : typeof err === "string" ? err : void 0;
|
|
2665
|
+
const blockType = c.blockType(a.statusCode, message);
|
|
2666
|
+
if (blockType && !a.blockCounted) {
|
|
2667
|
+
a.blockCounted = true;
|
|
2668
|
+
const key = requestKey(ctx.request);
|
|
2669
|
+
const n = blockedByRequest.get(key);
|
|
2670
|
+
if (n !== void 0 || blockedByRequest.size < MAX_BLOCKED_TRACKED) blockedByRequest.set(key, (n ?? 0) + 1);
|
|
2671
|
+
}
|
|
2672
|
+
return { a, blockType };
|
|
2673
|
+
};
|
|
2674
|
+
const contextFn = config.analytics?.context;
|
|
2675
|
+
const contextFor = (c, a, request) => {
|
|
2676
|
+
if (!contextFn) return void 0;
|
|
2677
|
+
if (a.ctxDone) return a.ctx;
|
|
2678
|
+
a.ctxDone = true;
|
|
2679
|
+
try {
|
|
2680
|
+
const raw = contextFn({
|
|
2681
|
+
url: request.url,
|
|
2682
|
+
label: labelText(request.label),
|
|
2683
|
+
userData: userDataForCallback(request.userData)
|
|
2684
|
+
});
|
|
2685
|
+
if (raw && typeof raw.then === "function") {
|
|
2686
|
+
Promise.resolve(raw).catch(() => {
|
|
2687
|
+
});
|
|
2688
|
+
return void 0;
|
|
2689
|
+
}
|
|
2690
|
+
a.ctx = c.sanitizeContext(raw);
|
|
2691
|
+
} catch {
|
|
2692
|
+
a.ctx = void 0;
|
|
2693
|
+
}
|
|
2694
|
+
return a.ctx;
|
|
2695
|
+
};
|
|
2696
|
+
const noteRecords = (label, n) => {
|
|
2697
|
+
const c = collector;
|
|
2698
|
+
if (!c) return;
|
|
2699
|
+
try {
|
|
2700
|
+
c.records(label, n);
|
|
2701
|
+
} catch (analyticsErr) {
|
|
2702
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2703
|
+
}
|
|
2704
|
+
};
|
|
2705
|
+
const captureFor = (context, request, label) => (name, props) => {
|
|
2706
|
+
const c = collector;
|
|
2707
|
+
if (!c) return;
|
|
2708
|
+
try {
|
|
2709
|
+
c.capture(name, props, label, contextFor(c, attemptOf(context), request));
|
|
2710
|
+
} catch (analyticsErr) {
|
|
2711
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2712
|
+
}
|
|
2713
|
+
};
|
|
2714
|
+
const emitTally = (parentLabel, t) => {
|
|
2715
|
+
const c = collector;
|
|
2716
|
+
if (!c) return;
|
|
2717
|
+
for (const [child, [added, already]] of t) c.enqueued(parentLabel, child, added, already);
|
|
2718
|
+
};
|
|
2719
|
+
const wrapFanOut = (context, parentLabel) => {
|
|
2720
|
+
const handlerTally = /* @__PURE__ */ new Map();
|
|
2721
|
+
let late;
|
|
2722
|
+
let flushed = false;
|
|
2723
|
+
const merge = (t) => {
|
|
2724
|
+
const into = flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally;
|
|
2725
|
+
for (const [label, [added, already]] of t) tallyAdd(into, label, added, already);
|
|
2726
|
+
};
|
|
2727
|
+
const settle = () => {
|
|
2728
|
+
if (flushed && late && late.size > 0) {
|
|
2729
|
+
const t = late;
|
|
2730
|
+
late = void 0;
|
|
2731
|
+
emitTally(parentLabel, t);
|
|
2732
|
+
}
|
|
2733
|
+
};
|
|
2734
|
+
const flush = () => {
|
|
2735
|
+
if (flushed) return;
|
|
2736
|
+
flushed = true;
|
|
2737
|
+
try {
|
|
2738
|
+
emitTally(parentLabel, handlerTally);
|
|
2739
|
+
} catch (analyticsErr) {
|
|
2740
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2741
|
+
}
|
|
2742
|
+
};
|
|
2743
|
+
const origLinks = context.enqueueLinks;
|
|
2744
|
+
if (typeof origLinks === "function") {
|
|
2745
|
+
context.enqueueLinks = async function(options) {
|
|
2746
|
+
const tally = /* @__PURE__ */ new Map();
|
|
2747
|
+
let viewUsed = false;
|
|
2748
|
+
let opts = options;
|
|
2749
|
+
if (collector) {
|
|
2750
|
+
try {
|
|
2751
|
+
const crawlerRef = context.crawler;
|
|
2752
|
+
const rq = options?.requestQueue ?? (typeof crawlerRef?.getRequestQueue === "function" ? await crawlerRef.getRequestQueue() : void 0);
|
|
2753
|
+
const addBatched = rq?.addRequestsBatched;
|
|
2754
|
+
if (rq && typeof addBatched === "function") {
|
|
2755
|
+
const view = Object.create(rq);
|
|
2756
|
+
view.addRequestsBatched = async (reqs, o) => {
|
|
2757
|
+
const res2 = await addBatched.call(rq, reqs, o);
|
|
2758
|
+
try {
|
|
2759
|
+
viewUsed = true;
|
|
2760
|
+
if (Array.isArray(reqs)) {
|
|
2761
|
+
const present = /* @__PURE__ */ new Set();
|
|
2762
|
+
const added = res2?.addedRequests;
|
|
2763
|
+
if (Array.isArray(added)) {
|
|
2764
|
+
for (const pr of added) {
|
|
2765
|
+
if (pr && pr.wasAlreadyPresent === true) present.add(pr.uniqueKey);
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
for (const r of reqs) {
|
|
2769
|
+
const already = present.has(r?.uniqueKey);
|
|
2770
|
+
tallyAdd(tally, childLabelOf(r), already ? 0 : 1, already ? 1 : 0);
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
} catch {
|
|
2774
|
+
}
|
|
2775
|
+
return res2;
|
|
2776
|
+
};
|
|
2777
|
+
opts = { ...options ?? {}, requestQueue: view };
|
|
2778
|
+
}
|
|
2779
|
+
} catch {
|
|
2780
|
+
opts = options;
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
const res = await origLinks.call(this, opts);
|
|
2784
|
+
try {
|
|
2785
|
+
if (collector) {
|
|
2786
|
+
if (!viewUsed) {
|
|
2787
|
+
const label = childLabelOf(options);
|
|
2788
|
+
const processed = res?.processedRequests;
|
|
2789
|
+
if (Array.isArray(processed)) {
|
|
2790
|
+
for (const pr of processed) {
|
|
2791
|
+
const already = pr?.wasAlreadyPresent === true;
|
|
2792
|
+
tallyAdd(tally, label, already ? 0 : 1, already ? 1 : 0);
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
merge(tally);
|
|
2797
|
+
settle();
|
|
2798
|
+
}
|
|
2799
|
+
} catch (analyticsErr) {
|
|
2800
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2801
|
+
}
|
|
2802
|
+
return res;
|
|
2803
|
+
};
|
|
2804
|
+
}
|
|
2805
|
+
const origAdd = context.addRequests;
|
|
2806
|
+
if (typeof origAdd === "function") {
|
|
2807
|
+
context.addRequests = async function(requests, options) {
|
|
2808
|
+
if (!collector) return origAdd.call(this, requests, options);
|
|
2809
|
+
if (Array.isArray(requests)) {
|
|
2810
|
+
const res = await origAdd.call(this, requests, options);
|
|
2811
|
+
try {
|
|
2812
|
+
const tally = /* @__PURE__ */ new Map();
|
|
2813
|
+
for (const r of requests) tallyAdd(tally, childLabelOf(r), 1, 0);
|
|
2814
|
+
merge(tally);
|
|
2815
|
+
settle();
|
|
2816
|
+
} catch (analyticsErr) {
|
|
2817
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2818
|
+
}
|
|
2819
|
+
return res;
|
|
2820
|
+
}
|
|
2821
|
+
const iterable = requests;
|
|
2822
|
+
if (!iterable || typeof iterable !== "object" || typeof iterable[Symbol.iterator] !== "function" && typeof iterable[Symbol.asyncIterator] !== "function") {
|
|
2823
|
+
return origAdd.call(this, requests, options);
|
|
2824
|
+
}
|
|
2825
|
+
async function* counted() {
|
|
2826
|
+
try {
|
|
2827
|
+
for await (const r of requests) {
|
|
2828
|
+
try {
|
|
2829
|
+
tallyAdd(flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally, childLabelOf(r), 1, 0);
|
|
2830
|
+
} catch {
|
|
2831
|
+
}
|
|
2832
|
+
yield r;
|
|
2833
|
+
}
|
|
2834
|
+
} finally {
|
|
2835
|
+
try {
|
|
2836
|
+
settle();
|
|
2837
|
+
} catch {
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
return origAdd.call(this, counted(), options);
|
|
2842
|
+
};
|
|
2843
|
+
}
|
|
2844
|
+
return flush;
|
|
2845
|
+
};
|
|
2846
|
+
const clientCapture = (name, props) => {
|
|
2847
|
+
try {
|
|
2848
|
+
const store = asyncContext.getStore();
|
|
2849
|
+
if (store?.capture && store.client === client) return store.capture(name, props);
|
|
2850
|
+
collector?.capture(name, props, NO_LABEL);
|
|
2851
|
+
} catch (analyticsErr) {
|
|
2852
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2853
|
+
}
|
|
2854
|
+
};
|
|
2855
|
+
client.capture = clientCapture;
|
|
1449
2856
|
const wrappedHandler = async (context) => {
|
|
1450
2857
|
crawlStarted = true;
|
|
1451
2858
|
const { request } = context;
|
|
1452
2859
|
const url = request.url;
|
|
1453
2860
|
const label = request.label;
|
|
1454
|
-
const startTime = Date.now();
|
|
1455
2861
|
runStats.totalRequests++;
|
|
2862
|
+
const aLabel = collector ? reportLabel(label) : NO_LABEL;
|
|
1456
2863
|
if (skipLabels && skipLabels.has(label || "default")) {
|
|
1457
2864
|
runStats.bypassed++;
|
|
1458
2865
|
if (config.debug) {
|
|
1459
2866
|
logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
|
|
1460
2867
|
}
|
|
1461
|
-
|
|
2868
|
+
const b0 = analyticsOn ? performance.now() : 0;
|
|
2869
|
+
if (collector) {
|
|
2870
|
+
const bypassPush = context.pushData;
|
|
2871
|
+
if (bypassPush) {
|
|
2872
|
+
context.pushData = async (data) => {
|
|
2873
|
+
const res = await bypassPush.call(context, data);
|
|
2874
|
+
noteRecords(aLabel, recordCount(data));
|
|
2875
|
+
return res;
|
|
2876
|
+
};
|
|
2877
|
+
}
|
|
2878
|
+
const flushFanOut = wrapFanOut(context, aLabel);
|
|
2879
|
+
const bypassContext = {
|
|
2880
|
+
request: buildRawRequest(request),
|
|
2881
|
+
client,
|
|
2882
|
+
learning: false,
|
|
2883
|
+
aiKnown: false,
|
|
2884
|
+
relearn: false,
|
|
2885
|
+
items: [],
|
|
2886
|
+
capture: captureFor(context, request, aLabel),
|
|
2887
|
+
records: (n) => noteRecords(aLabel, n)
|
|
2888
|
+
};
|
|
2889
|
+
try {
|
|
2890
|
+
await asyncContext.run(bypassContext, async () => {
|
|
2891
|
+
await originalHandler.call(crawler, context);
|
|
2892
|
+
});
|
|
2893
|
+
} finally {
|
|
2894
|
+
flushFanOut();
|
|
2895
|
+
}
|
|
2896
|
+
} else {
|
|
2897
|
+
await originalHandler.call(crawler, context);
|
|
2898
|
+
}
|
|
2899
|
+
if (analyticsOn) recordSuccess(context, "bypassed", msSince(b0), void 0);
|
|
1462
2900
|
return;
|
|
1463
2901
|
}
|
|
1464
2902
|
setScrapeContext({
|
|
@@ -1471,6 +2909,8 @@ var FetchBrain = class {
|
|
|
1471
2909
|
const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
|
|
1472
2910
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
|
|
1473
2911
|
let consumedStash;
|
|
2912
|
+
let recallMs;
|
|
2913
|
+
let handlerMs;
|
|
1474
2914
|
try {
|
|
1475
2915
|
const preRecalled = request.userData?.__fetchBrainResult;
|
|
1476
2916
|
let aiResult;
|
|
@@ -1480,12 +2920,18 @@ var FetchBrain = class {
|
|
|
1480
2920
|
consumedStash = stashedData;
|
|
1481
2921
|
aiResult = { known: true, data: stashedData };
|
|
1482
2922
|
} else {
|
|
2923
|
+
const r0 = analyticsOn ? performance.now() : 0;
|
|
1483
2924
|
aiResult = await client.recall(rawRequest);
|
|
2925
|
+
if (analyticsOn) recallMs = msSince(r0);
|
|
1484
2926
|
}
|
|
1485
2927
|
} else if (preRecalled) {
|
|
1486
2928
|
aiResult = preRecalled;
|
|
2929
|
+
} else if (observe) {
|
|
2930
|
+
aiResult = { known: false };
|
|
1487
2931
|
} else {
|
|
2932
|
+
const r0 = analyticsOn ? performance.now() : 0;
|
|
1488
2933
|
aiResult = await client.recall(rawRequest);
|
|
2934
|
+
if (analyticsOn) recallMs = msSince(r0);
|
|
1489
2935
|
}
|
|
1490
2936
|
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1491
2937
|
if (aiResult.fallback) {
|
|
@@ -1522,10 +2968,13 @@ var FetchBrain = class {
|
|
|
1522
2968
|
if (aiResult.known && aiResult.data && originalPushData) {
|
|
1523
2969
|
usedAIData = true;
|
|
1524
2970
|
await originalPushData.call(context, aiResult.data);
|
|
2971
|
+
noteRecords(aLabel, recordCount(aiResult.data));
|
|
1525
2972
|
if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
|
|
1526
2973
|
await fireOnRecalled(aiResult.data);
|
|
1527
2974
|
}
|
|
1528
|
-
}
|
|
2975
|
+
},
|
|
2976
|
+
// Custom analytics event for this request; a no-op when analytics is off. Never throws.
|
|
2977
|
+
capture: clientCapture
|
|
1529
2978
|
};
|
|
1530
2979
|
request.userData = {
|
|
1531
2980
|
...request.userData,
|
|
@@ -1538,6 +2987,7 @@ var FetchBrain = class {
|
|
|
1538
2987
|
if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
|
|
1539
2988
|
if (originalPushData) {
|
|
1540
2989
|
await originalPushData.call(context, aiResult.data);
|
|
2990
|
+
noteRecords(aLabel, recordCount(aiResult.data));
|
|
1541
2991
|
}
|
|
1542
2992
|
try {
|
|
1543
2993
|
if (!request.userData?.__fetchBrainCounted) {
|
|
@@ -1555,6 +3005,10 @@ var FetchBrain = class {
|
|
|
1555
3005
|
logger.debug(`Run stats skipped: ${countErr}`);
|
|
1556
3006
|
}
|
|
1557
3007
|
await fireOnRecalled(aiResult.data);
|
|
3008
|
+
if (analyticsOn) {
|
|
3009
|
+
const fetchSkipped = request.skipNavigation === true;
|
|
3010
|
+
recordSuccess(context, fetchSkipped ? "skipped" : "recalled", void 0, recallMs);
|
|
3011
|
+
}
|
|
1558
3012
|
return;
|
|
1559
3013
|
}
|
|
1560
3014
|
const counts = labelCounts(request.label);
|
|
@@ -1567,22 +3021,27 @@ var FetchBrain = class {
|
|
|
1567
3021
|
logger.debug(`Learning${urlSuffix(shownUrl())}`);
|
|
1568
3022
|
}
|
|
1569
3023
|
const learnItems = [];
|
|
1570
|
-
if (originalPushData && config.learning !== false) {
|
|
3024
|
+
if (originalPushData && (config.learning !== false || collector)) {
|
|
1571
3025
|
context.pushData = async (data) => {
|
|
1572
|
-
if (!usedAIData && (!aiResult.known || relearn)) {
|
|
3026
|
+
if (config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
|
|
1573
3027
|
learnItems.push(...Array.isArray(data) ? data : [data]);
|
|
1574
3028
|
}
|
|
1575
|
-
|
|
3029
|
+
const res = await originalPushData.call(context, data);
|
|
3030
|
+
noteRecords(aLabel, recordCount(data));
|
|
3031
|
+
return res;
|
|
1576
3032
|
};
|
|
1577
3033
|
}
|
|
3034
|
+
const flushFanOut = collector ? wrapFanOut(context, aLabel) : void 0;
|
|
1578
3035
|
const requestContext = {
|
|
1579
3036
|
request: rawRequest,
|
|
1580
3037
|
client,
|
|
1581
3038
|
learning: config.learning !== false,
|
|
1582
3039
|
aiKnown: aiResult.known,
|
|
1583
3040
|
relearn,
|
|
1584
|
-
items: learnItems
|
|
3041
|
+
items: learnItems,
|
|
3042
|
+
...collector ? { capture: captureFor(context, request, aLabel), records: (n) => noteRecords(aLabel, n) } : {}
|
|
1585
3043
|
};
|
|
3044
|
+
const h0 = analyticsOn ? performance.now() : 0;
|
|
1586
3045
|
try {
|
|
1587
3046
|
await asyncContext.run(requestContext, async () => {
|
|
1588
3047
|
await originalHandler.call(crawler, context);
|
|
@@ -1590,6 +3049,9 @@ var FetchBrain = class {
|
|
|
1590
3049
|
} catch (handlerErr) {
|
|
1591
3050
|
if (counts) counts.failed++;
|
|
1592
3051
|
throw handlerErr;
|
|
3052
|
+
} finally {
|
|
3053
|
+
if (analyticsOn) handlerMs = msSince(h0);
|
|
3054
|
+
flushFanOut?.();
|
|
1593
3055
|
}
|
|
1594
3056
|
try {
|
|
1595
3057
|
if (!request.userData?.__fetchBrainCounted) {
|
|
@@ -1611,75 +3073,16 @@ var FetchBrain = class {
|
|
|
1611
3073
|
pendingLearns.add(pending);
|
|
1612
3074
|
void pending.finally(() => pendingLearns.delete(pending));
|
|
1613
3075
|
}
|
|
1614
|
-
if (
|
|
1615
|
-
try {
|
|
1616
|
-
const telemetry = await collectTelemetry(
|
|
1617
|
-
{
|
|
1618
|
-
request: {
|
|
1619
|
-
url,
|
|
1620
|
-
retryCount: request.retryCount,
|
|
1621
|
-
label,
|
|
1622
|
-
userData: request.userData
|
|
1623
|
-
},
|
|
1624
|
-
response: {
|
|
1625
|
-
statusCode: context.response?.statusCode || context.response?.status
|
|
1626
|
-
},
|
|
1627
|
-
proxyInfo: context.proxyInfo ? {
|
|
1628
|
-
url: context.proxyInfo.url,
|
|
1629
|
-
hostname: context.proxyInfo.hostname,
|
|
1630
|
-
countryCode: context.proxyInfo.countryCode
|
|
1631
|
-
} : void 0,
|
|
1632
|
-
session: context.session ? {
|
|
1633
|
-
errorScore: context.session.errorScore,
|
|
1634
|
-
usageCount: context.session.usageCount
|
|
1635
|
-
} : void 0,
|
|
1636
|
-
crawler: {
|
|
1637
|
-
constructor: { name: crawlerType }
|
|
1638
|
-
}
|
|
1639
|
-
},
|
|
1640
|
-
{
|
|
1641
|
-
startTime,
|
|
1642
|
-
endTime: Date.now(),
|
|
1643
|
-
responseTime: Date.now() - startTime,
|
|
1644
|
-
contentSize: context.response?.body?.length
|
|
1645
|
-
},
|
|
1646
|
-
telemetryConfig
|
|
1647
|
-
);
|
|
1648
|
-
if (telemetry) {
|
|
1649
|
-
telemetryBuffer.add(telemetry);
|
|
1650
|
-
}
|
|
1651
|
-
} catch (err) {
|
|
1652
|
-
logger.debug(`Telemetry collection error: ${err}`);
|
|
1653
|
-
}
|
|
1654
|
-
}
|
|
3076
|
+
if (analyticsOn) recordSuccess(context, "scraped", handlerMs, recallMs);
|
|
1655
3077
|
} catch (err) {
|
|
1656
3078
|
if (consumedStash) {
|
|
1657
3079
|
stashSet(stashKey(rawRequest), consumedStash);
|
|
1658
3080
|
}
|
|
1659
|
-
if (
|
|
3081
|
+
if (analyticsOn && collector) {
|
|
1660
3082
|
try {
|
|
1661
|
-
const
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
url,
|
|
1665
|
-
retryCount: request.retryCount,
|
|
1666
|
-
label
|
|
1667
|
-
},
|
|
1668
|
-
crawler: {
|
|
1669
|
-
constructor: { name: crawlerType }
|
|
1670
|
-
}
|
|
1671
|
-
},
|
|
1672
|
-
{
|
|
1673
|
-
startTime,
|
|
1674
|
-
endTime: Date.now(),
|
|
1675
|
-
responseTime: Date.now() - startTime
|
|
1676
|
-
},
|
|
1677
|
-
telemetryConfig,
|
|
1678
|
-
err instanceof Error ? err : new Error(String(err))
|
|
1679
|
-
);
|
|
1680
|
-
if (telemetry) {
|
|
1681
|
-
telemetryBuffer.add(telemetry);
|
|
1682
|
-
}
|
|
3083
|
+
const a = attemptOf(context);
|
|
3084
|
+
a.handlerMs = handlerMs;
|
|
3085
|
+
a.recallMs = recallMs;
|
|
1683
3086
|
} catch {
|
|
1684
3087
|
}
|
|
1685
3088
|
}
|
|
@@ -1691,10 +3094,64 @@ var FetchBrain = class {
|
|
|
1691
3094
|
const crawlerAny = crawler;
|
|
1692
3095
|
crawlerAny[handlerKey] = wrappedHandler;
|
|
1693
3096
|
logger.debug(`Wrapped ${handlerKey}`);
|
|
3097
|
+
if (analyticsOn) {
|
|
3098
|
+
const preNav = (ctx) => {
|
|
3099
|
+
if (!collector) return;
|
|
3100
|
+
try {
|
|
3101
|
+
attemptOf(ctx).navStart = performance.now();
|
|
3102
|
+
} catch {
|
|
3103
|
+
}
|
|
3104
|
+
};
|
|
3105
|
+
const postNav = (ctx) => {
|
|
3106
|
+
if (!collector) return;
|
|
3107
|
+
try {
|
|
3108
|
+
const a = attemptOf(ctx);
|
|
3109
|
+
if (a.navStart !== void 0) a.navMs = msSince(a.navStart);
|
|
3110
|
+
a.statusCode = statusFrom(ctx.response);
|
|
3111
|
+
a.bytes = headerBytes(ctx.response);
|
|
3112
|
+
} catch {
|
|
3113
|
+
}
|
|
3114
|
+
};
|
|
3115
|
+
if (Array.isArray(crawlerAny.preNavigationHooks)) {
|
|
3116
|
+
crawlerAny.preNavigationHooks = [...crawlerAny.preNavigationHooks, preNav];
|
|
3117
|
+
}
|
|
3118
|
+
if (Array.isArray(crawlerAny.postNavigationHooks)) {
|
|
3119
|
+
crawlerAny.postNavigationHooks = [postNav, ...crawlerAny.postNavigationHooks];
|
|
3120
|
+
}
|
|
3121
|
+
const userErrorHandler = crawlerAny.errorHandler;
|
|
3122
|
+
crawlerAny.errorHandler = function(...args) {
|
|
3123
|
+
const c = collector;
|
|
3124
|
+
if (c) {
|
|
3125
|
+
try {
|
|
3126
|
+
noteFailure(c, args[0], args[1]);
|
|
3127
|
+
} catch (analyticsErr) {
|
|
3128
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
return typeof userErrorHandler === "function" ? userErrorHandler.apply(this, args) : void 0;
|
|
3132
|
+
};
|
|
3133
|
+
const userFailedHandler = crawlerAny.failedRequestHandler;
|
|
3134
|
+
crawlerAny.failedRequestHandler = function(...args) {
|
|
3135
|
+
const c = collector;
|
|
3136
|
+
if (c) {
|
|
3137
|
+
try {
|
|
3138
|
+
const ctx = args[0];
|
|
3139
|
+
const { a, blockType } = noteFailure(c, ctx, args[1]);
|
|
3140
|
+
const req = ctx.request;
|
|
3141
|
+
c.error(reportLabel(req.label), args[1], contextFor(c, a, req));
|
|
3142
|
+
emitRequest(c, ctx, a, blockType ? "blocked" : "failed", blockType);
|
|
3143
|
+
} catch (analyticsErr) {
|
|
3144
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
3145
|
+
}
|
|
3146
|
+
}
|
|
3147
|
+
return typeof userFailedHandler === "function" ? userFailedHandler.apply(this, args) : void 0;
|
|
3148
|
+
};
|
|
3149
|
+
}
|
|
1694
3150
|
if (typeof crawlerAny.run === "function") {
|
|
1695
3151
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
1696
3152
|
crawlerAny.run = async (...args) => {
|
|
1697
3153
|
runStats.startTime = Date.now();
|
|
3154
|
+
safeBeginRun(client);
|
|
1698
3155
|
const runStartedAt = new Date(runStats.startTime).toISOString();
|
|
1699
3156
|
labelStats.clear();
|
|
1700
3157
|
const runBase = {
|
|
@@ -1710,94 +3167,190 @@ var FetchBrain = class {
|
|
|
1710
3167
|
};
|
|
1711
3168
|
const changeBase = safeChangeStats(client);
|
|
1712
3169
|
const runId = nextRunId();
|
|
3170
|
+
let analyticsQueue;
|
|
3171
|
+
let reportClient;
|
|
3172
|
+
let reportAnalytics;
|
|
3173
|
+
if (analyticsOn) {
|
|
3174
|
+
try {
|
|
3175
|
+
const [mod, cfg] = await Promise.all([loadCollector(), fetchAnalyticsConfig(client)]);
|
|
3176
|
+
if (mod && cfg?.enabled !== false) {
|
|
3177
|
+
const analyticsRunId = runId;
|
|
3178
|
+
const scraper = client.getScraperName();
|
|
3179
|
+
const batchStartSeq = mod.startSeqFromEnv();
|
|
3180
|
+
analyticsQueue = new mod.AnalyticsQueue(
|
|
3181
|
+
(gz, signal) => client.postAnalyticsEvents(gz, analyticsRunId, signal),
|
|
3182
|
+
{
|
|
3183
|
+
wrap: (events, seq) => ({ runId: analyticsRunId, scraper, seq, events }),
|
|
3184
|
+
// Unique across Apify migrations: a restarted process must not reuse the earlier seqs.
|
|
3185
|
+
startSeq: batchStartSeq
|
|
3186
|
+
}
|
|
3187
|
+
);
|
|
3188
|
+
if (cfg) {
|
|
3189
|
+
if (Number.isFinite(cfg.sampleRate) && cfg.sampleRate > 0 && cfg.sampleRate <= 1) {
|
|
3190
|
+
analyticsQueue.sampleRate = cfg.sampleRate;
|
|
3191
|
+
}
|
|
3192
|
+
if (typeof cfg.pauseUntil === "number") analyticsQueue.pause(cfg.pauseUntil);
|
|
3193
|
+
}
|
|
3194
|
+
const apifyUserId = process.env.APIFY_USER_ID;
|
|
3195
|
+
const clientHash = apifyUserId && cfg?.salt ? mod.Collector.hashClient(apifyUserId, cfg.salt) : void 0;
|
|
3196
|
+
collector = new mod.Collector(
|
|
3197
|
+
analyticsQueue,
|
|
3198
|
+
{
|
|
3199
|
+
runId: analyticsRunId,
|
|
3200
|
+
scraper,
|
|
3201
|
+
...clientHash ? { client: clientHash } : {},
|
|
3202
|
+
crawlerType,
|
|
3203
|
+
sdkVersion: mod.SDK_VERSION,
|
|
3204
|
+
platform: process.env.APIFY_IS_AT_HOME || process.env.APIFY_ACTOR_ID ? "apify" : "other"
|
|
3205
|
+
},
|
|
3206
|
+
{
|
|
3207
|
+
debug: (msg) => logger.debug(msg),
|
|
3208
|
+
// Event seqs after a migration start above the earlier process's (batch seq
|
|
3209
|
+
// is whole seconds x 1000, so x 1000 again leaves 1e6 events per second of run).
|
|
3210
|
+
startSeq: batchStartSeq * 1e3
|
|
3211
|
+
}
|
|
3212
|
+
);
|
|
3213
|
+
reportClient = clientHash;
|
|
3214
|
+
const quotaSeen = /* @__PURE__ */ new Set();
|
|
3215
|
+
safeOnQuotaReached(client, (cap) => {
|
|
3216
|
+
if (quotaSeen.has(cap)) return;
|
|
3217
|
+
quotaSeen.add(cap);
|
|
3218
|
+
collector?.quotaReached(cap);
|
|
3219
|
+
});
|
|
3220
|
+
blockedByRequest.clear();
|
|
3221
|
+
emittedThenFailed.clear();
|
|
3222
|
+
const memoryMb = Number(process.env.APIFY_MEMORY_MBYTES);
|
|
3223
|
+
const maxConcurrency = crawlerAny.autoscaledPoolOptions?.maxConcurrency;
|
|
3224
|
+
collector.runStarted({
|
|
3225
|
+
memoryMb: Number.isFinite(memoryMb) && memoryMb > 0 ? memoryMb : void 0,
|
|
3226
|
+
maxConcurrency: typeof maxConcurrency === "number" ? maxConcurrency : void 0
|
|
3227
|
+
});
|
|
3228
|
+
analyticsQueue.start();
|
|
3229
|
+
}
|
|
3230
|
+
} catch (analyticsErr) {
|
|
3231
|
+
collector = void 0;
|
|
3232
|
+
analyticsQueue = void 0;
|
|
3233
|
+
reportClient = void 0;
|
|
3234
|
+
safeOnQuotaReached(client, void 0);
|
|
3235
|
+
logger.debug(`Analytics off for this run: ${analyticsErr}`);
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
1713
3238
|
try {
|
|
1714
3239
|
const result = await originalRun(...args);
|
|
1715
3240
|
return result;
|
|
1716
3241
|
} finally {
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
3242
|
+
let analyticsStop;
|
|
3243
|
+
if (analyticsQueue) {
|
|
3244
|
+
try {
|
|
3245
|
+
collector?.runFinished({ durationMs: Date.now() - runStats.startTime });
|
|
3246
|
+
if (collector) reportAnalytics = { labels: collector.labelStats(), ...collector.aggregateReport() };
|
|
3247
|
+
} catch (analyticsErr) {
|
|
3248
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
3249
|
+
}
|
|
3250
|
+
analyticsStop = analyticsQueue.stop().catch((analyticsErr) => {
|
|
3251
|
+
logger.debug(`Analytics flush skipped: ${analyticsErr}`);
|
|
3252
|
+
});
|
|
3253
|
+
collector = void 0;
|
|
1723
3254
|
}
|
|
1724
|
-
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1725
|
-
1
|
|
1726
|
-
);
|
|
1727
|
-
const run = {
|
|
1728
|
-
totalRequests: runStats.totalRequests - runBase.totalRequests,
|
|
1729
|
-
bypassed: runStats.bypassed - runBase.bypassed,
|
|
1730
|
-
dropped: runStats.dropped - runBase.dropped,
|
|
1731
|
-
scraped: runStats.scraped - runBase.scraped,
|
|
1732
|
-
learned: runStats.learned - runBase.learned,
|
|
1733
|
-
recalled: runStats.recalled - runBase.recalled,
|
|
1734
|
-
aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
|
|
1735
|
-
requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
|
|
1736
|
-
lateRecalls: runStats.lateRecalls - runBase.lateRecalls
|
|
1737
|
-
};
|
|
1738
|
-
const managedRequests = run.totalRequests - run.bypassed;
|
|
1739
|
-
const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
1740
|
-
let changes = { changed: 0, drift: [] };
|
|
1741
3255
|
try {
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
};
|
|
1749
|
-
} catch (diffErr) {
|
|
1750
|
-
logger.debug(`Change summary skipped: ${diffErr}`);
|
|
1751
|
-
}
|
|
1752
|
-
const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
|
|
1753
|
-
logger.info(
|
|
1754
|
-
`\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} (${savingsPercent}%), requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
|
|
1755
|
-
);
|
|
1756
|
-
if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
|
|
1757
|
-
logger.info(
|
|
1758
|
-
`${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
|
|
3256
|
+
safeOnQuotaReached(client, void 0);
|
|
3257
|
+
logger.debug("Flushing pending learn requests on crawl complete");
|
|
3258
|
+
await client.flushLearnBatch();
|
|
3259
|
+
await Promise.allSettled([...pendingLearns]);
|
|
3260
|
+
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
3261
|
+
1
|
|
1759
3262
|
);
|
|
1760
|
-
|
|
1761
|
-
|
|
3263
|
+
const run = {
|
|
3264
|
+
totalRequests: runStats.totalRequests - runBase.totalRequests,
|
|
3265
|
+
bypassed: runStats.bypassed - runBase.bypassed,
|
|
3266
|
+
dropped: runStats.dropped - runBase.dropped,
|
|
3267
|
+
scraped: runStats.scraped - runBase.scraped,
|
|
3268
|
+
learned: runStats.learned - runBase.learned,
|
|
3269
|
+
recalled: runStats.recalled - runBase.recalled,
|
|
3270
|
+
aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
|
|
3271
|
+
requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
|
|
3272
|
+
lateRecalls: runStats.lateRecalls - runBase.lateRecalls
|
|
3273
|
+
};
|
|
3274
|
+
const managedRequests = run.totalRequests - run.bypassed;
|
|
3275
|
+
const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
3276
|
+
let changes = { changed: 0, drift: [], known: 0 };
|
|
1762
3277
|
try {
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
3278
|
+
const now = safeChangeStats(client);
|
|
3279
|
+
const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
|
|
3280
|
+
const seen = new Set(changeBase.drift.map(key));
|
|
3281
|
+
changes = {
|
|
3282
|
+
changed: Math.max(0, now.changed - changeBase.changed) || 0,
|
|
3283
|
+
drift: now.drift.filter((d) => !seen.has(key(d))),
|
|
3284
|
+
known: Math.max(0, (now.known ?? 0) - (changeBase.known ?? 0)) || 0
|
|
3285
|
+
};
|
|
3286
|
+
} catch (diffErr) {
|
|
3287
|
+
logger.debug(`Change summary skipped: ${diffErr}`);
|
|
1766
3288
|
}
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1776
|
-
scraped: run.scraped,
|
|
1777
|
-
learned: run.learned,
|
|
1778
|
-
recalled: run.recalled,
|
|
1779
|
-
requestsSkipped: run.requestsSkipped,
|
|
1780
|
-
lateRecalls: run.lateRecalls,
|
|
1781
|
-
bypassed: run.bypassed,
|
|
1782
|
-
labels
|
|
1783
|
-
});
|
|
1784
|
-
for (const flag of Array.isArray(flags) ? flags : []) {
|
|
1785
|
-
if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
|
|
1786
|
-
continue;
|
|
1787
|
-
}
|
|
1788
|
-
const label = clipText(flag.label, 64);
|
|
1789
|
-
logger.warn(
|
|
1790
|
-
flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
|
|
3289
|
+
const showChanged = observe || config.changeDetection?.enabled === true || changes.changed > 0;
|
|
3290
|
+
if (observe) {
|
|
3291
|
+
logger.info(
|
|
3292
|
+
`\u{1F440} Observe run finished: learned: ${run.learned}, scraped: ${run.scraped}, changed: ${changes.changed}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + `, duration: ${duration}s`
|
|
3293
|
+
);
|
|
3294
|
+
if (changes.known > 0) {
|
|
3295
|
+
logger.info(
|
|
3296
|
+
`${changes.known} ${changes.known === 1 ? "page was" : "pages were"} already known \u2014 recall (the default) would have skipped ${changes.known === 1 ? "that fetch" : "those fetches"}.`
|
|
1791
3297
|
);
|
|
1792
3298
|
}
|
|
1793
|
-
}
|
|
1794
|
-
|
|
3299
|
+
} else logger.info(
|
|
3300
|
+
`\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} ` + (safeQuotaState(client) === "recall_cap" ? "(monthly recall limit reached)" : `(${savingsPercent}%)`) + `, requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
|
|
3301
|
+
);
|
|
3302
|
+
if (!observe && run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
|
|
3303
|
+
logger.info(
|
|
3304
|
+
`${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
|
|
3305
|
+
);
|
|
3306
|
+
}
|
|
3307
|
+
for (const item of changes.drift) {
|
|
3308
|
+
try {
|
|
3309
|
+
logger.warn(describeDrift(item));
|
|
3310
|
+
} catch (warnErr) {
|
|
3311
|
+
logger.debug(`Drift warning skipped: ${warnErr}`);
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
if (config.reportRuns !== false) {
|
|
3315
|
+
try {
|
|
3316
|
+
const labels = Object.fromEntries(labelStats);
|
|
3317
|
+
const flags = await client.reportRun({
|
|
3318
|
+
runId,
|
|
3319
|
+
build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
|
|
3320
|
+
startedAt: runStartedAt,
|
|
3321
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3322
|
+
scraped: run.scraped,
|
|
3323
|
+
learned: run.learned,
|
|
3324
|
+
recalled: run.recalled,
|
|
3325
|
+
requestsSkipped: run.requestsSkipped,
|
|
3326
|
+
// recall:false: pages memory already knew were fetched anyway —
|
|
3327
|
+
// the same untapped savings late recalls report.
|
|
3328
|
+
lateRecalls: observe ? changes.known : run.lateRecalls,
|
|
3329
|
+
bypassed: run.bypassed,
|
|
3330
|
+
labels,
|
|
3331
|
+
...reportClient ? { client: reportClient } : {},
|
|
3332
|
+
...reportAnalytics ? { analytics: reportAnalytics } : {}
|
|
3333
|
+
});
|
|
3334
|
+
for (const flag of Array.isArray(flags) ? flags : []) {
|
|
3335
|
+
if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
|
|
3336
|
+
continue;
|
|
3337
|
+
}
|
|
3338
|
+
const label = clipText(flag.label, 64);
|
|
3339
|
+
logger.warn(
|
|
3340
|
+
flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
|
|
3341
|
+
);
|
|
3342
|
+
}
|
|
3343
|
+
} catch (reportErr) {
|
|
3344
|
+
logger.debug(`Run report skipped: ${reportErr}`);
|
|
3345
|
+
}
|
|
1795
3346
|
}
|
|
3347
|
+
} finally {
|
|
3348
|
+
await analyticsStop;
|
|
1796
3349
|
}
|
|
1797
3350
|
}
|
|
1798
3351
|
};
|
|
1799
3352
|
}
|
|
1800
|
-
if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
3353
|
+
if (!observe && config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
1801
3354
|
const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
|
|
1802
3355
|
if (crawlerAny.retryOnBlocked) {
|
|
1803
3356
|
logger.info(
|
|
@@ -1926,14 +3479,23 @@ async function pushData(data, dataset, datasetName) {
|
|
|
1926
3479
|
} else {
|
|
1927
3480
|
await dataset.pushData(data);
|
|
1928
3481
|
}
|
|
3482
|
+
try {
|
|
3483
|
+
ctx?.records?.(Array.isArray(data) ? data.length : 1);
|
|
3484
|
+
} catch {
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
function capture(name, props) {
|
|
3488
|
+
try {
|
|
3489
|
+
asyncContext.getStore()?.capture?.(name, props);
|
|
3490
|
+
} catch {
|
|
3491
|
+
}
|
|
1929
3492
|
}
|
|
1930
3493
|
|
|
1931
3494
|
exports.CircuitBreaker = CircuitBreaker;
|
|
1932
3495
|
exports.FetchBrain = FetchBrain;
|
|
1933
3496
|
exports.FetchBrainClient = FetchBrainClient;
|
|
1934
3497
|
exports.RequestBatcher = RequestBatcher;
|
|
1935
|
-
exports.
|
|
1936
|
-
exports.collectTelemetry = collectTelemetry;
|
|
3498
|
+
exports.capture = capture;
|
|
1937
3499
|
exports.createFetchBrain = createFetchBrain;
|
|
1938
3500
|
exports.createLogger = createLogger;
|
|
1939
3501
|
exports.getCurrentContext = getCurrentContext;
|