@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.mjs
CHANGED
|
@@ -477,6 +477,14 @@ var ApiError = class extends Error {
|
|
|
477
477
|
this.name = "ApiError";
|
|
478
478
|
}
|
|
479
479
|
};
|
|
480
|
+
var TERMINAL_ANALYTICS_STATUSES = /* @__PURE__ */ new Set([400, 413, 415, 422]);
|
|
481
|
+
var ANALYTICS_RATE_LIMIT_PAUSE_SEC = 10;
|
|
482
|
+
var BadReplyError = class extends Error {
|
|
483
|
+
constructor(message) {
|
|
484
|
+
super(message);
|
|
485
|
+
this.name = "BadReplyError";
|
|
486
|
+
}
|
|
487
|
+
};
|
|
480
488
|
function parseRetryAfter(header) {
|
|
481
489
|
if (!header) return void 0;
|
|
482
490
|
const secs = Number(header);
|
|
@@ -515,13 +523,20 @@ var FetchBrainClient = class {
|
|
|
515
523
|
this.warnedOversizeLearn = false;
|
|
516
524
|
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
517
525
|
this.learnCapWarnedUntil = 0;
|
|
526
|
+
/**
|
|
527
|
+
* The monthly recall limit answered HARD_CAP_EXCEEDED. Recall (handler-time and
|
|
528
|
+
* enqueue-time bulk) stops for the rest of the run. Per client instance; reset by
|
|
529
|
+
* beginRun() so each new run() tries once more (a plan can reset between runs).
|
|
530
|
+
*/
|
|
531
|
+
this.recallCapped = false;
|
|
518
532
|
/** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
|
|
519
|
-
this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
|
|
533
|
+
this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [], known: 0 };
|
|
520
534
|
this.logger = createLogger(config.debug ? "debug" : "info", true);
|
|
521
535
|
this.config = {
|
|
522
536
|
apiKey: config.apiKey,
|
|
523
537
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
524
538
|
memory: config.memory || "recent",
|
|
539
|
+
recall: config.recall ?? true,
|
|
525
540
|
learning: config.learning ?? true,
|
|
526
541
|
alwaysRun: config.alwaysRun ?? false,
|
|
527
542
|
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
@@ -530,8 +545,6 @@ var FetchBrainClient = class {
|
|
|
530
545
|
debug: config.debug || false,
|
|
531
546
|
extractForLearning: config.extractForLearning,
|
|
532
547
|
learnUrlField: config.learnUrlField,
|
|
533
|
-
telemetry: config.telemetry ?? { enabled: false },
|
|
534
|
-
// opt-in
|
|
535
548
|
batch: config.batch,
|
|
536
549
|
circuitBreaker: config.circuitBreaker,
|
|
537
550
|
skipLabels: config.skipLabels,
|
|
@@ -544,6 +557,8 @@ var FetchBrainClient = class {
|
|
|
544
557
|
// enhance-only; stored so getConfig() round-trips
|
|
545
558
|
scraper: config.scraper,
|
|
546
559
|
changeDetection: config.changeDetection,
|
|
560
|
+
analytics: config.analytics,
|
|
561
|
+
// enhance-only; stored so getConfig() round-trips
|
|
547
562
|
reportRuns: config.reportRuns ?? true
|
|
548
563
|
};
|
|
549
564
|
const scraper = resolveScraperName(config.scraper);
|
|
@@ -562,6 +577,11 @@ var FetchBrainClient = class {
|
|
|
562
577
|
this.logger,
|
|
563
578
|
"Ask"
|
|
564
579
|
);
|
|
580
|
+
this.analyticsCircuitBreaker = new CircuitBreaker(
|
|
581
|
+
this.config.circuitBreaker,
|
|
582
|
+
this.logger,
|
|
583
|
+
"Analytics"
|
|
584
|
+
);
|
|
565
585
|
this.batcher = new RequestBatcher(
|
|
566
586
|
(items) => this.executeBatchQuery(items),
|
|
567
587
|
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
@@ -575,11 +595,45 @@ var FetchBrainClient = class {
|
|
|
575
595
|
}
|
|
576
596
|
/** True when recalls must not reach the API right now (crawl continues without). */
|
|
577
597
|
recallBlocked() {
|
|
578
|
-
return this.isKeyRejected() || this.circuitBreaker.isOpen();
|
|
598
|
+
return this.recallCapped || this.isKeyRejected() || this.circuitBreaker.isOpen();
|
|
599
|
+
}
|
|
600
|
+
/** Where the account stands against its limits: recall cap wins over learn cap. */
|
|
601
|
+
quotaState() {
|
|
602
|
+
if (this.recallCapped) return "recall_cap";
|
|
603
|
+
if (Date.now() < this.learnCapWarnedUntil) return "learn_cap";
|
|
604
|
+
return "ok";
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Start of a run(): the recall limit is retried once (plans can reset between
|
|
608
|
+
* runs); if the API still answers HARD_CAP_EXCEEDED, recall stops again for
|
|
609
|
+
* that run. The learn cap is month-bound and keeps its own pause.
|
|
610
|
+
*/
|
|
611
|
+
beginRun() {
|
|
612
|
+
this.recallCapped = false;
|
|
613
|
+
}
|
|
614
|
+
/** Called (never throws into the caller) when a limit is first seen. Pass undefined to clear. */
|
|
615
|
+
onQuotaReached(listener) {
|
|
616
|
+
this.quotaListener = listener;
|
|
617
|
+
}
|
|
618
|
+
notifyQuota(cap) {
|
|
619
|
+
try {
|
|
620
|
+
this.quotaListener?.(cap);
|
|
621
|
+
} catch (err) {
|
|
622
|
+
this.logger.debug("Quota listener failed:", err);
|
|
623
|
+
}
|
|
579
624
|
}
|
|
580
625
|
isKeyRejected() {
|
|
581
626
|
return Date.now() < this.keyRejectedUntil;
|
|
582
627
|
}
|
|
628
|
+
/** A 403 HARD_CAP_EXCEEDED on recall: warn once, pause recall for the run, tell the listener. */
|
|
629
|
+
noteRecallCap(error) {
|
|
630
|
+
if (!(error instanceof ApiError) || error.status !== 403 || error.code !== "HARD_CAP_EXCEEDED" && error.serverError !== "HARD_CAP_EXCEEDED" || this.recallCapped) {
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
this.recallCapped = true;
|
|
634
|
+
this.logger.warn("Monthly recall limit reached \u2014 recall is paused until your plan resets; pages are fetched normally.");
|
|
635
|
+
this.notifyQuota("recall");
|
|
636
|
+
}
|
|
583
637
|
/**
|
|
584
638
|
* React to a 4xx the API returned. These are not outages (they don't open the
|
|
585
639
|
* shared breaker). A 401 means the next calls would fail the same way, so all
|
|
@@ -699,7 +753,7 @@ var FetchBrainClient = class {
|
|
|
699
753
|
* Ask a natural-language question, answered from everything the account has learned
|
|
700
754
|
*
|
|
701
755
|
* `model` picks the generation model for answer mode from the server's
|
|
702
|
-
* menu (e.g. "llama-3.3-70b", "
|
|
756
|
+
* menu (e.g. "llama-3.3-70b", "glm-5.3" — larger models use more Ask
|
|
703
757
|
* credits), or "byok" to answer with your own linked provider model.
|
|
704
758
|
* Omit it for the default model.
|
|
705
759
|
*
|
|
@@ -777,8 +831,10 @@ var FetchBrainClient = class {
|
|
|
777
831
|
}
|
|
778
832
|
return results;
|
|
779
833
|
} catch (error) {
|
|
780
|
-
if (!isOutage(error))
|
|
781
|
-
|
|
834
|
+
if (!isOutage(error)) {
|
|
835
|
+
this.noteRefusal(error);
|
|
836
|
+
this.noteRecallCap(error);
|
|
837
|
+
} else if (outcome) outcome.outage = true;
|
|
782
838
|
else this.circuitBreaker.recordFailure();
|
|
783
839
|
throw error;
|
|
784
840
|
}
|
|
@@ -797,6 +853,10 @@ var FetchBrainClient = class {
|
|
|
797
853
|
const request = { entries };
|
|
798
854
|
const ignore = this.config.changeDetection?.ignoreFields;
|
|
799
855
|
if (ignore && ignore.length > 0) request.ignore = ignore;
|
|
856
|
+
if (this.config.recall === false) {
|
|
857
|
+
request.observe = true;
|
|
858
|
+
request.memory = this.config.memory;
|
|
859
|
+
}
|
|
800
860
|
const platformBuildId = getPlatformBuildId();
|
|
801
861
|
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
802
862
|
request.build = platformBuildId;
|
|
@@ -817,6 +877,7 @@ var FetchBrainClient = class {
|
|
|
817
877
|
const now = /* @__PURE__ */ new Date();
|
|
818
878
|
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
819
879
|
this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
|
|
880
|
+
this.notifyQuota("learn");
|
|
820
881
|
if (this.learnCapWarnedUntil < monthStart) {
|
|
821
882
|
this.learnCapWarnedUntil = monthStart;
|
|
822
883
|
this.logger.warn(
|
|
@@ -863,6 +924,7 @@ var FetchBrainClient = class {
|
|
|
863
924
|
stats.changed += num(response.changed);
|
|
864
925
|
stats.unchanged += num(response.unchanged);
|
|
865
926
|
stats.firstSeen += num(response.firstSeen);
|
|
927
|
+
stats.known = (stats.known ?? 0) + num(response.known);
|
|
866
928
|
const drift = Array.isArray(response.drift) ? response.drift : [];
|
|
867
929
|
for (const item of drift) {
|
|
868
930
|
if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
|
|
@@ -889,7 +951,7 @@ var FetchBrainClient = class {
|
|
|
889
951
|
* failure or timeout it returns no flags.
|
|
890
952
|
*/
|
|
891
953
|
async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
|
|
892
|
-
if (this.config.reportRuns === false || this.
|
|
954
|
+
if (this.config.reportRuns === false || this.isKeyRejected() || this.circuitBreaker.isOpen()) return [];
|
|
893
955
|
try {
|
|
894
956
|
const response = await this.makeRequest(
|
|
895
957
|
"/v1/runs",
|
|
@@ -904,12 +966,95 @@ var FetchBrainClient = class {
|
|
|
904
966
|
return [];
|
|
905
967
|
}
|
|
906
968
|
}
|
|
969
|
+
/**
|
|
970
|
+
* Ship one gzipped analytics batch. Never throws. null = retry later (outage,
|
|
971
|
+
* breaker open, key rejected, other 4xx, 429 without Retry-After, bad 2xx body);
|
|
972
|
+
* `{ drop: true }` = the server permanently refused this batch (400/413/415/422),
|
|
973
|
+
* so discard it.
|
|
974
|
+
*/
|
|
975
|
+
async postAnalyticsEvents(body, _runId, signal) {
|
|
976
|
+
if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
|
|
977
|
+
try {
|
|
978
|
+
const response = await this.makeRequest(
|
|
979
|
+
"/v1/analytics/events",
|
|
980
|
+
{
|
|
981
|
+
method: "POST",
|
|
982
|
+
body,
|
|
983
|
+
headers: {
|
|
984
|
+
"Content-Type": "application/json",
|
|
985
|
+
"Content-Encoding": "gzip"
|
|
986
|
+
}
|
|
987
|
+
},
|
|
988
|
+
DEFAULT_LEARN_TIMEOUT,
|
|
989
|
+
{ signal, lenientBody: true }
|
|
990
|
+
);
|
|
991
|
+
this.analyticsCircuitBreaker.recordSuccess();
|
|
992
|
+
const out = {};
|
|
993
|
+
if (response && typeof response.sampleRate === "number") out.sampleRate = response.sampleRate;
|
|
994
|
+
if (response && typeof response.pauseUntil === "number") out.pauseUntil = response.pauseUntil;
|
|
995
|
+
return out;
|
|
996
|
+
} catch (error) {
|
|
997
|
+
this.noteRefusal(error);
|
|
998
|
+
if (signal?.aborted) {
|
|
999
|
+
return null;
|
|
1000
|
+
} else if (error instanceof BadReplyError) {
|
|
1001
|
+
this.analyticsCircuitBreaker.recordFailure();
|
|
1002
|
+
this.logger.debug("Analytics reply was not JSON:", error);
|
|
1003
|
+
return null;
|
|
1004
|
+
} else if (isOutage(error)) {
|
|
1005
|
+
this.analyticsCircuitBreaker.recordFailure();
|
|
1006
|
+
} else if (error instanceof ApiError) {
|
|
1007
|
+
if (error.status === 429) {
|
|
1008
|
+
const hinted = error.retryAfterSec;
|
|
1009
|
+
const waitSec = typeof hinted === "number" && Number.isFinite(hinted) && hinted > 0 ? Math.min(Math.max(hinted, 1), 3600) : ANALYTICS_RATE_LIMIT_PAUSE_SEC;
|
|
1010
|
+
return { pauseUntil: Date.now() + waitSec * 1e3, retry: true };
|
|
1011
|
+
} else if (TERMINAL_ANALYTICS_STATUSES.has(error.status)) {
|
|
1012
|
+
this.logger.debug("Analytics batch refused:", error);
|
|
1013
|
+
return { drop: true };
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
this.logger.debug("Analytics events post failed:", error);
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
/** The resolved scraper name (valid option, else env var); undefined = default memory. */
|
|
1021
|
+
getScraperName() {
|
|
1022
|
+
return this.scraperName;
|
|
1023
|
+
}
|
|
1024
|
+
/** Fetch the analytics config for this key. Never throws: failure returns null. */
|
|
1025
|
+
async getAnalyticsConfig() {
|
|
1026
|
+
if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
|
|
1027
|
+
try {
|
|
1028
|
+
const r = await this.makeRequest("/v1/analytics/config", { method: "GET" });
|
|
1029
|
+
this.analyticsCircuitBreaker.recordSuccess();
|
|
1030
|
+
if (!r || typeof r.enabled !== "boolean") return null;
|
|
1031
|
+
const salt = typeof r.salt === "string" ? r.salt : "";
|
|
1032
|
+
if (!r.enabled) return { enabled: false, salt, sampleRate: 1 };
|
|
1033
|
+
return {
|
|
1034
|
+
salt,
|
|
1035
|
+
sampleRate: typeof r.sampleRate === "number" ? r.sampleRate : 1,
|
|
1036
|
+
...typeof r.pauseUntil === "number" ? { pauseUntil: r.pauseUntil } : {},
|
|
1037
|
+
enabled: true
|
|
1038
|
+
};
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
this.noteRefusal(error);
|
|
1041
|
+
if (isOutage(error)) this.analyticsCircuitBreaker.recordFailure();
|
|
1042
|
+
this.logger.debug("Analytics config fetch failed:", error);
|
|
1043
|
+
return null;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
907
1046
|
/**
|
|
908
1047
|
* Make an HTTP request to the API
|
|
909
1048
|
*/
|
|
910
|
-
async makeRequest(path, options, timeout) {
|
|
1049
|
+
async makeRequest(path, options, timeout, extra) {
|
|
911
1050
|
const url = `${this.config.baseUrl}${path}`;
|
|
912
1051
|
const controller = new AbortController();
|
|
1052
|
+
const external = extra?.signal;
|
|
1053
|
+
const onExternalAbort = () => controller.abort();
|
|
1054
|
+
if (external) {
|
|
1055
|
+
if (external.aborted) controller.abort();
|
|
1056
|
+
else external.addEventListener("abort", onExternalAbort, { once: true });
|
|
1057
|
+
}
|
|
913
1058
|
const timeoutId = setTimeout(
|
|
914
1059
|
() => controller.abort(),
|
|
915
1060
|
timeout ?? this.config.timeout
|
|
@@ -973,9 +1118,24 @@ var FetchBrainClient = class {
|
|
|
973
1118
|
parseRetryAfter(response.headers.get("Retry-After"))
|
|
974
1119
|
);
|
|
975
1120
|
}
|
|
1121
|
+
if (extra?.lenientBody) {
|
|
1122
|
+
const text = await readBody(response, (r) => r.text());
|
|
1123
|
+
if (response.status === 204 || text.length === 0) return {};
|
|
1124
|
+
let parsed;
|
|
1125
|
+
try {
|
|
1126
|
+
parsed = JSON.parse(text);
|
|
1127
|
+
} catch {
|
|
1128
|
+
throw new BadReplyError("Unexpected non-JSON reply");
|
|
1129
|
+
}
|
|
1130
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1131
|
+
throw new BadReplyError("Unexpected reply shape");
|
|
1132
|
+
}
|
|
1133
|
+
return parsed;
|
|
1134
|
+
}
|
|
976
1135
|
return await readBody(response, (r) => r.json());
|
|
977
1136
|
} finally {
|
|
978
1137
|
clearTimeout(timeoutId);
|
|
1138
|
+
external?.removeEventListener("abort", onExternalAbort);
|
|
979
1139
|
}
|
|
980
1140
|
}
|
|
981
1141
|
/**
|
|
@@ -1017,181 +1177,42 @@ var FetchBrainClient = class {
|
|
|
1017
1177
|
async flushLearnBatch() {
|
|
1018
1178
|
await this.learnBatcher.forceFlush();
|
|
1019
1179
|
}
|
|
1020
|
-
/**
|
|
1021
|
-
* Send telemetry data to the API
|
|
1022
|
-
* This is fire-and-forget - failures are silently ignored
|
|
1023
|
-
*/
|
|
1024
|
-
async sendTelemetry(entries) {
|
|
1025
|
-
if (!this.config.telemetry?.enabled || entries.length === 0) {
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
|
-
try {
|
|
1029
|
-
await this.makeRequest("/v1/telemetry", {
|
|
1030
|
-
method: "POST",
|
|
1031
|
-
body: JSON.stringify({ entries })
|
|
1032
|
-
});
|
|
1033
|
-
} catch {
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
/**
|
|
1037
|
-
* Check if telemetry is enabled
|
|
1038
|
-
*/
|
|
1039
|
-
isTelemetryEnabled() {
|
|
1040
|
-
return this.config.telemetry?.enabled ?? false;
|
|
1041
|
-
}
|
|
1042
|
-
/**
|
|
1043
|
-
* Get telemetry config
|
|
1044
|
-
*/
|
|
1045
|
-
getTelemetryConfig() {
|
|
1046
|
-
return this.config.telemetry;
|
|
1047
|
-
}
|
|
1048
1180
|
};
|
|
1049
1181
|
|
|
1050
|
-
// src/
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
}
|
|
1058
|
-
function extractDomain(url) {
|
|
1059
|
-
try {
|
|
1060
|
-
return new URL(url).hostname;
|
|
1061
|
-
} catch {
|
|
1062
|
-
return "unknown";
|
|
1063
|
-
}
|
|
1182
|
+
// src/enhance.ts
|
|
1183
|
+
var collectorModule;
|
|
1184
|
+
function loadCollector() {
|
|
1185
|
+
return collectorModule ?? (collectorModule = import('./collector-3OZRBCM4.mjs').catch(() => {
|
|
1186
|
+
collectorModule = void 0;
|
|
1187
|
+
return void 0;
|
|
1188
|
+
}));
|
|
1064
1189
|
}
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1190
|
+
var MAX_TALLY_LABELS = 50;
|
|
1191
|
+
var DEFAULT_CHILD_LABEL = "_nolabel";
|
|
1192
|
+
var ANALYTICS_CONFIG_TIMEOUT_MS = 500;
|
|
1193
|
+
var MAX_BLOCKED_TRACKED = 1e4;
|
|
1194
|
+
var msSince = (t0) => Math.round(performance.now() - t0);
|
|
1195
|
+
function statusFrom(response) {
|
|
1196
|
+
const r = response;
|
|
1197
|
+
if (!r) return void 0;
|
|
1198
|
+
if (typeof r.statusCode === "number") return r.statusCode;
|
|
1199
|
+
if (typeof r.status === "function") {
|
|
1200
|
+
const s = r.status.call(r);
|
|
1201
|
+
return typeof s === "number" ? s : void 0;
|
|
1072
1202
|
}
|
|
1203
|
+
return void 0;
|
|
1073
1204
|
}
|
|
1074
|
-
function
|
|
1075
|
-
|
|
1076
|
-
if (
|
|
1077
|
-
if (
|
|
1078
|
-
if (statusCode === 503) return "503";
|
|
1079
|
-
if (statusCode && statusCode >= 400) return `${statusCode}`;
|
|
1080
|
-
const msg = errorMessage?.toLowerCase() || "";
|
|
1081
|
-
if (msg.includes("captcha")) return "captcha";
|
|
1082
|
-
if (msg.includes("timeout")) return "timeout";
|
|
1083
|
-
if (msg.includes("blocked")) return "blocked";
|
|
1084
|
-
if (msg.includes("rate limit")) return "429";
|
|
1205
|
+
function bodyBytes(context) {
|
|
1206
|
+
const body = context.body;
|
|
1207
|
+
if (Buffer.isBuffer(body)) return body.length;
|
|
1208
|
+
if (typeof body === "string") return Buffer.byteLength(body);
|
|
1085
1209
|
return void 0;
|
|
1086
1210
|
}
|
|
1087
|
-
function
|
|
1088
|
-
|
|
1089
|
-
const
|
|
1090
|
-
|
|
1091
|
-
if (url.includes("mobile")) return "mobile";
|
|
1092
|
-
if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
|
|
1093
|
-
if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
|
|
1094
|
-
return "residential";
|
|
1095
|
-
}
|
|
1096
|
-
return "datacenter";
|
|
1211
|
+
function headerBytes(response) {
|
|
1212
|
+
const headers = response?.headers;
|
|
1213
|
+
const len = headers && typeof headers === "object" ? Number(headers["content-length"]) : NaN;
|
|
1214
|
+
return Number.isFinite(len) && len >= 0 ? len : void 0;
|
|
1097
1215
|
}
|
|
1098
|
-
async function collectTelemetry(context, timing, config, error) {
|
|
1099
|
-
if (!config?.enabled) {
|
|
1100
|
-
return null;
|
|
1101
|
-
}
|
|
1102
|
-
const url = context.request.url;
|
|
1103
|
-
const statusCode = context.response?.status || context.response?.statusCode;
|
|
1104
|
-
const telemetry = {
|
|
1105
|
-
domain: extractDomain(url),
|
|
1106
|
-
urlHash: await hashString(url),
|
|
1107
|
-
urlPattern: generalizeUrlPath(url),
|
|
1108
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1109
|
-
};
|
|
1110
|
-
if (config.sharePerformance !== false) {
|
|
1111
|
-
telemetry.statusCode = statusCode;
|
|
1112
|
-
telemetry.retryCount = context.request.retryCount;
|
|
1113
|
-
if (timing) {
|
|
1114
|
-
telemetry.responseTimeMs = timing.responseTime;
|
|
1115
|
-
telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
|
|
1116
|
-
telemetry.contentSize = timing.contentSize;
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
if (config.shareProxyInfo !== false && context.proxyInfo) {
|
|
1120
|
-
telemetry.proxyCountry = context.proxyInfo.countryCode;
|
|
1121
|
-
telemetry.proxyType = extractProxyType(context.proxyInfo.url);
|
|
1122
|
-
telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
|
|
1123
|
-
}
|
|
1124
|
-
if (config.shareSitePatterns !== false) {
|
|
1125
|
-
const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
|
|
1126
|
-
telemetry.blocked = isBlocked || !!error;
|
|
1127
|
-
telemetry.blockType = detectBlockType(statusCode, error?.message);
|
|
1128
|
-
}
|
|
1129
|
-
if (context.session) {
|
|
1130
|
-
telemetry.sessionAge = context.session.usageCount;
|
|
1131
|
-
telemetry.sessionErrorScore = context.session.errorScore;
|
|
1132
|
-
}
|
|
1133
|
-
telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
|
|
1134
|
-
telemetry.requestLabel = context.request.label;
|
|
1135
|
-
return telemetry;
|
|
1136
|
-
}
|
|
1137
|
-
var TelemetryBuffer = class {
|
|
1138
|
-
constructor(options = {}) {
|
|
1139
|
-
this.buffer = [];
|
|
1140
|
-
this.maxSize = options.maxSize ?? 50;
|
|
1141
|
-
this.flushInterval = options.flushInterval ?? 3e4;
|
|
1142
|
-
this.flushCallback = options.onFlush;
|
|
1143
|
-
this.startFlushTimer();
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Add telemetry entry to buffer
|
|
1147
|
-
*/
|
|
1148
|
-
add(entry) {
|
|
1149
|
-
if (!entry) return;
|
|
1150
|
-
this.buffer.push(entry);
|
|
1151
|
-
if (this.buffer.length >= this.maxSize) {
|
|
1152
|
-
this.flush();
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
/**
|
|
1156
|
-
* Flush buffer and send telemetry
|
|
1157
|
-
*/
|
|
1158
|
-
async flush() {
|
|
1159
|
-
if (this.buffer.length === 0) return [];
|
|
1160
|
-
const entries = [...this.buffer];
|
|
1161
|
-
this.buffer = [];
|
|
1162
|
-
if (this.flushCallback) {
|
|
1163
|
-
try {
|
|
1164
|
-
await this.flushCallback(entries);
|
|
1165
|
-
} catch (err) {
|
|
1166
|
-
console.debug("Telemetry flush failed:", err);
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
return entries;
|
|
1170
|
-
}
|
|
1171
|
-
/**
|
|
1172
|
-
* Get current buffer size
|
|
1173
|
-
*/
|
|
1174
|
-
get size() {
|
|
1175
|
-
return this.buffer.length;
|
|
1176
|
-
}
|
|
1177
|
-
startFlushTimer() {
|
|
1178
|
-
this.flushTimer = setInterval(() => {
|
|
1179
|
-
this.flush();
|
|
1180
|
-
}, this.flushInterval);
|
|
1181
|
-
this.flushTimer.unref?.();
|
|
1182
|
-
}
|
|
1183
|
-
/**
|
|
1184
|
-
* Stop the flush timer and flush remaining entries
|
|
1185
|
-
*/
|
|
1186
|
-
async stop() {
|
|
1187
|
-
if (this.flushTimer) {
|
|
1188
|
-
clearInterval(this.flushTimer);
|
|
1189
|
-
}
|
|
1190
|
-
await this.flush();
|
|
1191
|
-
}
|
|
1192
|
-
};
|
|
1193
|
-
|
|
1194
|
-
// src/enhance.ts
|
|
1195
1216
|
var REPORT_MAX_LABELS = 50;
|
|
1196
1217
|
var REPORT_LABEL_MAX_CHARS = 64;
|
|
1197
1218
|
var RUN_ID_MAX_CHARS = 128;
|
|
@@ -1206,7 +1227,7 @@ function nextRunId() {
|
|
|
1206
1227
|
return n === 1 ? id : `${id}-${n}`;
|
|
1207
1228
|
}
|
|
1208
1229
|
function labelText(label) {
|
|
1209
|
-
if (typeof label === "string") return label;
|
|
1230
|
+
if (typeof label === "string") return label.replace(/^[\s~]+/, "");
|
|
1210
1231
|
if (typeof label === "number" || typeof label === "boolean") return String(label);
|
|
1211
1232
|
return void 0;
|
|
1212
1233
|
}
|
|
@@ -1219,6 +1240,25 @@ function describeDrift(d) {
|
|
|
1219
1240
|
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))}`;
|
|
1220
1241
|
return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
|
|
1221
1242
|
}
|
|
1243
|
+
function safeBeginRun(client) {
|
|
1244
|
+
try {
|
|
1245
|
+
client.beginRun();
|
|
1246
|
+
} catch {
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function safeQuotaState(client) {
|
|
1250
|
+
try {
|
|
1251
|
+
return client.quotaState();
|
|
1252
|
+
} catch {
|
|
1253
|
+
return "ok";
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
function safeOnQuotaReached(client, listener) {
|
|
1257
|
+
try {
|
|
1258
|
+
client.onQuotaReached(listener);
|
|
1259
|
+
} catch {
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1222
1262
|
function safeChangeStats(client) {
|
|
1223
1263
|
try {
|
|
1224
1264
|
return client.getChangeStats();
|
|
@@ -1300,9 +1340,53 @@ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
|
|
|
1300
1340
|
}
|
|
1301
1341
|
}
|
|
1302
1342
|
var asyncContext = new AsyncLocalStorage();
|
|
1343
|
+
var noopCapture = () => {
|
|
1344
|
+
};
|
|
1345
|
+
var recordCount = (data) => Array.isArray(data) ? data.length : 1;
|
|
1346
|
+
function childLabelOf(r) {
|
|
1347
|
+
if (!r || typeof r !== "object") return DEFAULT_CHILD_LABEL;
|
|
1348
|
+
try {
|
|
1349
|
+
const o = r;
|
|
1350
|
+
const text = labelText(o.label ?? o.userData?.label)?.trim().slice(0, REPORT_LABEL_MAX_CHARS);
|
|
1351
|
+
return text || DEFAULT_CHILD_LABEL;
|
|
1352
|
+
} catch {
|
|
1353
|
+
return DEFAULT_CHILD_LABEL;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
function tallyAdd(t, label, added, already) {
|
|
1357
|
+
const key = t.has(label) || t.size < MAX_TALLY_LABELS ? label : "~other";
|
|
1358
|
+
const cur = t.get(key);
|
|
1359
|
+
if (cur) {
|
|
1360
|
+
cur[0] += added;
|
|
1361
|
+
cur[1] += already;
|
|
1362
|
+
} else {
|
|
1363
|
+
t.set(key, [added, already]);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
function userDataForCallback(userData) {
|
|
1367
|
+
if (!userData) return {};
|
|
1368
|
+
let hasSdkKey = false;
|
|
1369
|
+
for (const k of SDK_USERDATA_KEYS) if (k in userData) hasSdkKey = true;
|
|
1370
|
+
if (!hasSdkKey) return userData;
|
|
1371
|
+
const out = {};
|
|
1372
|
+
for (const [k, v] of Object.entries(userData)) if (!SDK_USERDATA_KEYS.has(k)) out[k] = v;
|
|
1373
|
+
return out;
|
|
1374
|
+
}
|
|
1303
1375
|
function getCurrentContext() {
|
|
1304
1376
|
return asyncContext.getStore();
|
|
1305
1377
|
}
|
|
1378
|
+
async function fetchAnalyticsConfig(client) {
|
|
1379
|
+
let timer;
|
|
1380
|
+
const timeout = new Promise((resolve) => {
|
|
1381
|
+
timer = setTimeout(() => resolve(null), ANALYTICS_CONFIG_TIMEOUT_MS);
|
|
1382
|
+
timer.unref?.();
|
|
1383
|
+
});
|
|
1384
|
+
try {
|
|
1385
|
+
return await Promise.race([client.getAnalyticsConfig().catch(() => null), timeout]);
|
|
1386
|
+
} finally {
|
|
1387
|
+
if (timer) clearTimeout(timer);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1306
1390
|
function shouldRunHandler(alwaysRun, label) {
|
|
1307
1391
|
if (alwaysRun === void 0 || alwaysRun === false) {
|
|
1308
1392
|
return false;
|
|
@@ -1353,19 +1437,9 @@ var FetchBrain = class {
|
|
|
1353
1437
|
* @returns Enhanced crawler with same interface
|
|
1354
1438
|
*/
|
|
1355
1439
|
static enhance(crawler, config) {
|
|
1356
|
-
const client = new FetchBrainClient(config);
|
|
1440
|
+
const client = Object.assign(new FetchBrainClient(config), { capture: noopCapture });
|
|
1357
1441
|
const logger = createLogger(config.debug ? "debug" : "info", true);
|
|
1358
|
-
const
|
|
1359
|
-
const telemetryBuffer = new TelemetryBuffer({
|
|
1360
|
-
maxSize: 50,
|
|
1361
|
-
flushInterval: 3e4,
|
|
1362
|
-
onFlush: async (entries) => {
|
|
1363
|
-
if (telemetryConfig.enabled) {
|
|
1364
|
-
await client.sendTelemetry(entries);
|
|
1365
|
-
logger.debug(`Telemetry: sent ${entries.length} entries`);
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
});
|
|
1442
|
+
const observe = config.recall === false;
|
|
1369
1443
|
const runStats = {
|
|
1370
1444
|
totalRequests: 0,
|
|
1371
1445
|
recalled: 0,
|
|
@@ -1444,19 +1518,302 @@ var FetchBrain = class {
|
|
|
1444
1518
|
return void 0;
|
|
1445
1519
|
};
|
|
1446
1520
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
1521
|
+
const analyticsOn = config.analytics?.enabled === true;
|
|
1522
|
+
if (analyticsOn) void loadCollector();
|
|
1523
|
+
let collector;
|
|
1524
|
+
const attempts = /* @__PURE__ */ new WeakMap();
|
|
1525
|
+
const blockedByRequest = /* @__PURE__ */ new Map();
|
|
1526
|
+
const emittedThenFailed = /* @__PURE__ */ new Set();
|
|
1527
|
+
const attemptOf = (ctx) => {
|
|
1528
|
+
let a = attempts.get(ctx);
|
|
1529
|
+
if (!a) {
|
|
1530
|
+
a = {};
|
|
1531
|
+
attempts.set(ctx, a);
|
|
1532
|
+
}
|
|
1533
|
+
return a;
|
|
1534
|
+
};
|
|
1535
|
+
const requestKey = (r) => String(r.id ?? r.uniqueKey ?? r.url);
|
|
1536
|
+
const emitRequest = (c, ctx, a, outcome, blockType) => {
|
|
1537
|
+
if (a.emitted) return;
|
|
1538
|
+
a.emitted = true;
|
|
1539
|
+
const request = ctx.request;
|
|
1540
|
+
const key = requestKey(request);
|
|
1541
|
+
if (emittedThenFailed.size > 0 && emittedThenFailed.has(key)) return;
|
|
1542
|
+
const blockedAttempts = blockedByRequest.get(key) ?? 0;
|
|
1543
|
+
if (blockedAttempts) blockedByRequest.delete(key);
|
|
1544
|
+
c.request({
|
|
1545
|
+
label: reportLabel(request.label),
|
|
1546
|
+
outcome,
|
|
1547
|
+
retries: typeof request.retryCount === "number" ? request.retryCount : 0,
|
|
1548
|
+
url: request.url,
|
|
1549
|
+
statusCode: a.statusCode,
|
|
1550
|
+
navMs: a.navMs,
|
|
1551
|
+
handlerMs: a.handlerMs,
|
|
1552
|
+
recallMs: a.recallMs,
|
|
1553
|
+
bytes: a.bytes,
|
|
1554
|
+
blockType,
|
|
1555
|
+
blockedAttempts,
|
|
1556
|
+
// Evaluated only if the event survives sampling.
|
|
1557
|
+
context: () => contextFor(c, a, request)
|
|
1558
|
+
});
|
|
1559
|
+
};
|
|
1560
|
+
const recordSuccess = (context, outcome, handlerMs, recallMs) => {
|
|
1561
|
+
const c = collector;
|
|
1562
|
+
if (!c) return;
|
|
1563
|
+
try {
|
|
1564
|
+
const a = attemptOf(context);
|
|
1565
|
+
if (a.failed) return;
|
|
1566
|
+
a.handlerMs = handlerMs;
|
|
1567
|
+
a.recallMs = recallMs;
|
|
1568
|
+
a.bytes = bodyBytes(context) ?? a.bytes;
|
|
1569
|
+
emitRequest(c, context, a, outcome);
|
|
1570
|
+
} catch (analyticsErr) {
|
|
1571
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1572
|
+
}
|
|
1573
|
+
};
|
|
1574
|
+
const noteFailure = (c, ctx, err) => {
|
|
1575
|
+
const a = attemptOf(ctx);
|
|
1576
|
+
a.failed = true;
|
|
1577
|
+
if (a.emitted && emittedThenFailed.size < MAX_BLOCKED_TRACKED) {
|
|
1578
|
+
emittedThenFailed.add(requestKey(ctx.request));
|
|
1579
|
+
}
|
|
1580
|
+
a.statusCode ?? (a.statusCode = statusFrom(ctx.response));
|
|
1581
|
+
const message = err instanceof Error ? err.message : typeof err === "string" ? err : void 0;
|
|
1582
|
+
const blockType = c.blockType(a.statusCode, message);
|
|
1583
|
+
if (blockType && !a.blockCounted) {
|
|
1584
|
+
a.blockCounted = true;
|
|
1585
|
+
const key = requestKey(ctx.request);
|
|
1586
|
+
const n = blockedByRequest.get(key);
|
|
1587
|
+
if (n !== void 0 || blockedByRequest.size < MAX_BLOCKED_TRACKED) blockedByRequest.set(key, (n ?? 0) + 1);
|
|
1588
|
+
}
|
|
1589
|
+
return { a, blockType };
|
|
1590
|
+
};
|
|
1591
|
+
const contextFn = config.analytics?.context;
|
|
1592
|
+
const contextFor = (c, a, request) => {
|
|
1593
|
+
if (!contextFn) return void 0;
|
|
1594
|
+
if (a.ctxDone) return a.ctx;
|
|
1595
|
+
a.ctxDone = true;
|
|
1596
|
+
try {
|
|
1597
|
+
const raw = contextFn({
|
|
1598
|
+
url: request.url,
|
|
1599
|
+
label: labelText(request.label),
|
|
1600
|
+
userData: userDataForCallback(request.userData)
|
|
1601
|
+
});
|
|
1602
|
+
if (raw && typeof raw.then === "function") {
|
|
1603
|
+
Promise.resolve(raw).catch(() => {
|
|
1604
|
+
});
|
|
1605
|
+
return void 0;
|
|
1606
|
+
}
|
|
1607
|
+
a.ctx = c.sanitizeContext(raw);
|
|
1608
|
+
} catch {
|
|
1609
|
+
a.ctx = void 0;
|
|
1610
|
+
}
|
|
1611
|
+
return a.ctx;
|
|
1612
|
+
};
|
|
1613
|
+
const noteRecords = (label, n) => {
|
|
1614
|
+
const c = collector;
|
|
1615
|
+
if (!c) return;
|
|
1616
|
+
try {
|
|
1617
|
+
c.records(label, n);
|
|
1618
|
+
} catch (analyticsErr) {
|
|
1619
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1620
|
+
}
|
|
1621
|
+
};
|
|
1622
|
+
const captureFor = (context, request, label) => (name, props) => {
|
|
1623
|
+
const c = collector;
|
|
1624
|
+
if (!c) return;
|
|
1625
|
+
try {
|
|
1626
|
+
c.capture(name, props, label, contextFor(c, attemptOf(context), request));
|
|
1627
|
+
} catch (analyticsErr) {
|
|
1628
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1629
|
+
}
|
|
1630
|
+
};
|
|
1631
|
+
const emitTally = (parentLabel, t) => {
|
|
1632
|
+
const c = collector;
|
|
1633
|
+
if (!c) return;
|
|
1634
|
+
for (const [child, [added, already]] of t) c.enqueued(parentLabel, child, added, already);
|
|
1635
|
+
};
|
|
1636
|
+
const wrapFanOut = (context, parentLabel) => {
|
|
1637
|
+
const handlerTally = /* @__PURE__ */ new Map();
|
|
1638
|
+
let late;
|
|
1639
|
+
let flushed = false;
|
|
1640
|
+
const merge = (t) => {
|
|
1641
|
+
const into = flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally;
|
|
1642
|
+
for (const [label, [added, already]] of t) tallyAdd(into, label, added, already);
|
|
1643
|
+
};
|
|
1644
|
+
const settle = () => {
|
|
1645
|
+
if (flushed && late && late.size > 0) {
|
|
1646
|
+
const t = late;
|
|
1647
|
+
late = void 0;
|
|
1648
|
+
emitTally(parentLabel, t);
|
|
1649
|
+
}
|
|
1650
|
+
};
|
|
1651
|
+
const flush = () => {
|
|
1652
|
+
if (flushed) return;
|
|
1653
|
+
flushed = true;
|
|
1654
|
+
try {
|
|
1655
|
+
emitTally(parentLabel, handlerTally);
|
|
1656
|
+
} catch (analyticsErr) {
|
|
1657
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1658
|
+
}
|
|
1659
|
+
};
|
|
1660
|
+
const origLinks = context.enqueueLinks;
|
|
1661
|
+
if (typeof origLinks === "function") {
|
|
1662
|
+
context.enqueueLinks = async function(options) {
|
|
1663
|
+
const tally = /* @__PURE__ */ new Map();
|
|
1664
|
+
let viewUsed = false;
|
|
1665
|
+
let opts = options;
|
|
1666
|
+
if (collector) {
|
|
1667
|
+
try {
|
|
1668
|
+
const crawlerRef = context.crawler;
|
|
1669
|
+
const rq = options?.requestQueue ?? (typeof crawlerRef?.getRequestQueue === "function" ? await crawlerRef.getRequestQueue() : void 0);
|
|
1670
|
+
const addBatched = rq?.addRequestsBatched;
|
|
1671
|
+
if (rq && typeof addBatched === "function") {
|
|
1672
|
+
const view = Object.create(rq);
|
|
1673
|
+
view.addRequestsBatched = async (reqs, o) => {
|
|
1674
|
+
const res2 = await addBatched.call(rq, reqs, o);
|
|
1675
|
+
try {
|
|
1676
|
+
viewUsed = true;
|
|
1677
|
+
if (Array.isArray(reqs)) {
|
|
1678
|
+
const present = /* @__PURE__ */ new Set();
|
|
1679
|
+
const added = res2?.addedRequests;
|
|
1680
|
+
if (Array.isArray(added)) {
|
|
1681
|
+
for (const pr of added) {
|
|
1682
|
+
if (pr && pr.wasAlreadyPresent === true) present.add(pr.uniqueKey);
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
for (const r of reqs) {
|
|
1686
|
+
const already = present.has(r?.uniqueKey);
|
|
1687
|
+
tallyAdd(tally, childLabelOf(r), already ? 0 : 1, already ? 1 : 0);
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
} catch {
|
|
1691
|
+
}
|
|
1692
|
+
return res2;
|
|
1693
|
+
};
|
|
1694
|
+
opts = { ...options ?? {}, requestQueue: view };
|
|
1695
|
+
}
|
|
1696
|
+
} catch {
|
|
1697
|
+
opts = options;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
const res = await origLinks.call(this, opts);
|
|
1701
|
+
try {
|
|
1702
|
+
if (collector) {
|
|
1703
|
+
if (!viewUsed) {
|
|
1704
|
+
const label = childLabelOf(options);
|
|
1705
|
+
const processed = res?.processedRequests;
|
|
1706
|
+
if (Array.isArray(processed)) {
|
|
1707
|
+
for (const pr of processed) {
|
|
1708
|
+
const already = pr?.wasAlreadyPresent === true;
|
|
1709
|
+
tallyAdd(tally, label, already ? 0 : 1, already ? 1 : 0);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
merge(tally);
|
|
1714
|
+
settle();
|
|
1715
|
+
}
|
|
1716
|
+
} catch (analyticsErr) {
|
|
1717
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1718
|
+
}
|
|
1719
|
+
return res;
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
const origAdd = context.addRequests;
|
|
1723
|
+
if (typeof origAdd === "function") {
|
|
1724
|
+
context.addRequests = async function(requests, options) {
|
|
1725
|
+
if (!collector) return origAdd.call(this, requests, options);
|
|
1726
|
+
if (Array.isArray(requests)) {
|
|
1727
|
+
const res = await origAdd.call(this, requests, options);
|
|
1728
|
+
try {
|
|
1729
|
+
const tally = /* @__PURE__ */ new Map();
|
|
1730
|
+
for (const r of requests) tallyAdd(tally, childLabelOf(r), 1, 0);
|
|
1731
|
+
merge(tally);
|
|
1732
|
+
settle();
|
|
1733
|
+
} catch (analyticsErr) {
|
|
1734
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1735
|
+
}
|
|
1736
|
+
return res;
|
|
1737
|
+
}
|
|
1738
|
+
const iterable = requests;
|
|
1739
|
+
if (!iterable || typeof iterable !== "object" || typeof iterable[Symbol.iterator] !== "function" && typeof iterable[Symbol.asyncIterator] !== "function") {
|
|
1740
|
+
return origAdd.call(this, requests, options);
|
|
1741
|
+
}
|
|
1742
|
+
async function* counted() {
|
|
1743
|
+
try {
|
|
1744
|
+
for await (const r of requests) {
|
|
1745
|
+
try {
|
|
1746
|
+
tallyAdd(flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally, childLabelOf(r), 1, 0);
|
|
1747
|
+
} catch {
|
|
1748
|
+
}
|
|
1749
|
+
yield r;
|
|
1750
|
+
}
|
|
1751
|
+
} finally {
|
|
1752
|
+
try {
|
|
1753
|
+
settle();
|
|
1754
|
+
} catch {
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
return origAdd.call(this, counted(), options);
|
|
1759
|
+
};
|
|
1760
|
+
}
|
|
1761
|
+
return flush;
|
|
1762
|
+
};
|
|
1763
|
+
const clientCapture = (name, props) => {
|
|
1764
|
+
try {
|
|
1765
|
+
const store = asyncContext.getStore();
|
|
1766
|
+
if (store?.capture && store.client === client) return store.capture(name, props);
|
|
1767
|
+
collector?.capture(name, props, NO_LABEL);
|
|
1768
|
+
} catch (analyticsErr) {
|
|
1769
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
client.capture = clientCapture;
|
|
1447
1773
|
const wrappedHandler = async (context) => {
|
|
1448
1774
|
crawlStarted = true;
|
|
1449
1775
|
const { request } = context;
|
|
1450
1776
|
const url = request.url;
|
|
1451
1777
|
const label = request.label;
|
|
1452
|
-
const startTime = Date.now();
|
|
1453
1778
|
runStats.totalRequests++;
|
|
1779
|
+
const aLabel = collector ? reportLabel(label) : NO_LABEL;
|
|
1454
1780
|
if (skipLabels && skipLabels.has(label || "default")) {
|
|
1455
1781
|
runStats.bypassed++;
|
|
1456
1782
|
if (config.debug) {
|
|
1457
1783
|
logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
|
|
1458
1784
|
}
|
|
1459
|
-
|
|
1785
|
+
const b0 = analyticsOn ? performance.now() : 0;
|
|
1786
|
+
if (collector) {
|
|
1787
|
+
const bypassPush = context.pushData;
|
|
1788
|
+
if (bypassPush) {
|
|
1789
|
+
context.pushData = async (data) => {
|
|
1790
|
+
const res = await bypassPush.call(context, data);
|
|
1791
|
+
noteRecords(aLabel, recordCount(data));
|
|
1792
|
+
return res;
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
const flushFanOut = wrapFanOut(context, aLabel);
|
|
1796
|
+
const bypassContext = {
|
|
1797
|
+
request: buildRawRequest(request),
|
|
1798
|
+
client,
|
|
1799
|
+
learning: false,
|
|
1800
|
+
aiKnown: false,
|
|
1801
|
+
relearn: false,
|
|
1802
|
+
items: [],
|
|
1803
|
+
capture: captureFor(context, request, aLabel),
|
|
1804
|
+
records: (n) => noteRecords(aLabel, n)
|
|
1805
|
+
};
|
|
1806
|
+
try {
|
|
1807
|
+
await asyncContext.run(bypassContext, async () => {
|
|
1808
|
+
await originalHandler.call(crawler, context);
|
|
1809
|
+
});
|
|
1810
|
+
} finally {
|
|
1811
|
+
flushFanOut();
|
|
1812
|
+
}
|
|
1813
|
+
} else {
|
|
1814
|
+
await originalHandler.call(crawler, context);
|
|
1815
|
+
}
|
|
1816
|
+
if (analyticsOn) recordSuccess(context, "bypassed", msSince(b0), void 0);
|
|
1460
1817
|
return;
|
|
1461
1818
|
}
|
|
1462
1819
|
setScrapeContext({
|
|
@@ -1469,6 +1826,8 @@ var FetchBrain = class {
|
|
|
1469
1826
|
const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
|
|
1470
1827
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
|
|
1471
1828
|
let consumedStash;
|
|
1829
|
+
let recallMs;
|
|
1830
|
+
let handlerMs;
|
|
1472
1831
|
try {
|
|
1473
1832
|
const preRecalled = request.userData?.__fetchBrainResult;
|
|
1474
1833
|
let aiResult;
|
|
@@ -1478,12 +1837,18 @@ var FetchBrain = class {
|
|
|
1478
1837
|
consumedStash = stashedData;
|
|
1479
1838
|
aiResult = { known: true, data: stashedData };
|
|
1480
1839
|
} else {
|
|
1840
|
+
const r0 = analyticsOn ? performance.now() : 0;
|
|
1481
1841
|
aiResult = await client.recall(rawRequest);
|
|
1842
|
+
if (analyticsOn) recallMs = msSince(r0);
|
|
1482
1843
|
}
|
|
1483
1844
|
} else if (preRecalled) {
|
|
1484
1845
|
aiResult = preRecalled;
|
|
1846
|
+
} else if (observe) {
|
|
1847
|
+
aiResult = { known: false };
|
|
1485
1848
|
} else {
|
|
1849
|
+
const r0 = analyticsOn ? performance.now() : 0;
|
|
1486
1850
|
aiResult = await client.recall(rawRequest);
|
|
1851
|
+
if (analyticsOn) recallMs = msSince(r0);
|
|
1487
1852
|
}
|
|
1488
1853
|
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1489
1854
|
if (aiResult.fallback) {
|
|
@@ -1520,10 +1885,13 @@ var FetchBrain = class {
|
|
|
1520
1885
|
if (aiResult.known && aiResult.data && originalPushData) {
|
|
1521
1886
|
usedAIData = true;
|
|
1522
1887
|
await originalPushData.call(context, aiResult.data);
|
|
1888
|
+
noteRecords(aLabel, recordCount(aiResult.data));
|
|
1523
1889
|
if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
|
|
1524
1890
|
await fireOnRecalled(aiResult.data);
|
|
1525
1891
|
}
|
|
1526
|
-
}
|
|
1892
|
+
},
|
|
1893
|
+
// Custom analytics event for this request; a no-op when analytics is off. Never throws.
|
|
1894
|
+
capture: clientCapture
|
|
1527
1895
|
};
|
|
1528
1896
|
request.userData = {
|
|
1529
1897
|
...request.userData,
|
|
@@ -1536,6 +1904,7 @@ var FetchBrain = class {
|
|
|
1536
1904
|
if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
|
|
1537
1905
|
if (originalPushData) {
|
|
1538
1906
|
await originalPushData.call(context, aiResult.data);
|
|
1907
|
+
noteRecords(aLabel, recordCount(aiResult.data));
|
|
1539
1908
|
}
|
|
1540
1909
|
try {
|
|
1541
1910
|
if (!request.userData?.__fetchBrainCounted) {
|
|
@@ -1553,6 +1922,10 @@ var FetchBrain = class {
|
|
|
1553
1922
|
logger.debug(`Run stats skipped: ${countErr}`);
|
|
1554
1923
|
}
|
|
1555
1924
|
await fireOnRecalled(aiResult.data);
|
|
1925
|
+
if (analyticsOn) {
|
|
1926
|
+
const fetchSkipped = request.skipNavigation === true;
|
|
1927
|
+
recordSuccess(context, fetchSkipped ? "skipped" : "recalled", void 0, recallMs);
|
|
1928
|
+
}
|
|
1556
1929
|
return;
|
|
1557
1930
|
}
|
|
1558
1931
|
const counts = labelCounts(request.label);
|
|
@@ -1565,22 +1938,27 @@ var FetchBrain = class {
|
|
|
1565
1938
|
logger.debug(`Learning${urlSuffix(shownUrl())}`);
|
|
1566
1939
|
}
|
|
1567
1940
|
const learnItems = [];
|
|
1568
|
-
if (originalPushData && config.learning !== false) {
|
|
1941
|
+
if (originalPushData && (config.learning !== false || collector)) {
|
|
1569
1942
|
context.pushData = async (data) => {
|
|
1570
|
-
if (!usedAIData && (!aiResult.known || relearn)) {
|
|
1943
|
+
if (config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
|
|
1571
1944
|
learnItems.push(...Array.isArray(data) ? data : [data]);
|
|
1572
1945
|
}
|
|
1573
|
-
|
|
1946
|
+
const res = await originalPushData.call(context, data);
|
|
1947
|
+
noteRecords(aLabel, recordCount(data));
|
|
1948
|
+
return res;
|
|
1574
1949
|
};
|
|
1575
1950
|
}
|
|
1951
|
+
const flushFanOut = collector ? wrapFanOut(context, aLabel) : void 0;
|
|
1576
1952
|
const requestContext = {
|
|
1577
1953
|
request: rawRequest,
|
|
1578
1954
|
client,
|
|
1579
1955
|
learning: config.learning !== false,
|
|
1580
1956
|
aiKnown: aiResult.known,
|
|
1581
1957
|
relearn,
|
|
1582
|
-
items: learnItems
|
|
1958
|
+
items: learnItems,
|
|
1959
|
+
...collector ? { capture: captureFor(context, request, aLabel), records: (n) => noteRecords(aLabel, n) } : {}
|
|
1583
1960
|
};
|
|
1961
|
+
const h0 = analyticsOn ? performance.now() : 0;
|
|
1584
1962
|
try {
|
|
1585
1963
|
await asyncContext.run(requestContext, async () => {
|
|
1586
1964
|
await originalHandler.call(crawler, context);
|
|
@@ -1588,6 +1966,9 @@ var FetchBrain = class {
|
|
|
1588
1966
|
} catch (handlerErr) {
|
|
1589
1967
|
if (counts) counts.failed++;
|
|
1590
1968
|
throw handlerErr;
|
|
1969
|
+
} finally {
|
|
1970
|
+
if (analyticsOn) handlerMs = msSince(h0);
|
|
1971
|
+
flushFanOut?.();
|
|
1591
1972
|
}
|
|
1592
1973
|
try {
|
|
1593
1974
|
if (!request.userData?.__fetchBrainCounted) {
|
|
@@ -1609,75 +1990,16 @@ var FetchBrain = class {
|
|
|
1609
1990
|
pendingLearns.add(pending);
|
|
1610
1991
|
void pending.finally(() => pendingLearns.delete(pending));
|
|
1611
1992
|
}
|
|
1612
|
-
if (
|
|
1613
|
-
try {
|
|
1614
|
-
const telemetry = await collectTelemetry(
|
|
1615
|
-
{
|
|
1616
|
-
request: {
|
|
1617
|
-
url,
|
|
1618
|
-
retryCount: request.retryCount,
|
|
1619
|
-
label,
|
|
1620
|
-
userData: request.userData
|
|
1621
|
-
},
|
|
1622
|
-
response: {
|
|
1623
|
-
statusCode: context.response?.statusCode || context.response?.status
|
|
1624
|
-
},
|
|
1625
|
-
proxyInfo: context.proxyInfo ? {
|
|
1626
|
-
url: context.proxyInfo.url,
|
|
1627
|
-
hostname: context.proxyInfo.hostname,
|
|
1628
|
-
countryCode: context.proxyInfo.countryCode
|
|
1629
|
-
} : void 0,
|
|
1630
|
-
session: context.session ? {
|
|
1631
|
-
errorScore: context.session.errorScore,
|
|
1632
|
-
usageCount: context.session.usageCount
|
|
1633
|
-
} : void 0,
|
|
1634
|
-
crawler: {
|
|
1635
|
-
constructor: { name: crawlerType }
|
|
1636
|
-
}
|
|
1637
|
-
},
|
|
1638
|
-
{
|
|
1639
|
-
startTime,
|
|
1640
|
-
endTime: Date.now(),
|
|
1641
|
-
responseTime: Date.now() - startTime,
|
|
1642
|
-
contentSize: context.response?.body?.length
|
|
1643
|
-
},
|
|
1644
|
-
telemetryConfig
|
|
1645
|
-
);
|
|
1646
|
-
if (telemetry) {
|
|
1647
|
-
telemetryBuffer.add(telemetry);
|
|
1648
|
-
}
|
|
1649
|
-
} catch (err) {
|
|
1650
|
-
logger.debug(`Telemetry collection error: ${err}`);
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1993
|
+
if (analyticsOn) recordSuccess(context, "scraped", handlerMs, recallMs);
|
|
1653
1994
|
} catch (err) {
|
|
1654
1995
|
if (consumedStash) {
|
|
1655
1996
|
stashSet(stashKey(rawRequest), consumedStash);
|
|
1656
1997
|
}
|
|
1657
|
-
if (
|
|
1998
|
+
if (analyticsOn && collector) {
|
|
1658
1999
|
try {
|
|
1659
|
-
const
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
url,
|
|
1663
|
-
retryCount: request.retryCount,
|
|
1664
|
-
label
|
|
1665
|
-
},
|
|
1666
|
-
crawler: {
|
|
1667
|
-
constructor: { name: crawlerType }
|
|
1668
|
-
}
|
|
1669
|
-
},
|
|
1670
|
-
{
|
|
1671
|
-
startTime,
|
|
1672
|
-
endTime: Date.now(),
|
|
1673
|
-
responseTime: Date.now() - startTime
|
|
1674
|
-
},
|
|
1675
|
-
telemetryConfig,
|
|
1676
|
-
err instanceof Error ? err : new Error(String(err))
|
|
1677
|
-
);
|
|
1678
|
-
if (telemetry) {
|
|
1679
|
-
telemetryBuffer.add(telemetry);
|
|
1680
|
-
}
|
|
2000
|
+
const a = attemptOf(context);
|
|
2001
|
+
a.handlerMs = handlerMs;
|
|
2002
|
+
a.recallMs = recallMs;
|
|
1681
2003
|
} catch {
|
|
1682
2004
|
}
|
|
1683
2005
|
}
|
|
@@ -1689,10 +2011,64 @@ var FetchBrain = class {
|
|
|
1689
2011
|
const crawlerAny = crawler;
|
|
1690
2012
|
crawlerAny[handlerKey] = wrappedHandler;
|
|
1691
2013
|
logger.debug(`Wrapped ${handlerKey}`);
|
|
2014
|
+
if (analyticsOn) {
|
|
2015
|
+
const preNav = (ctx) => {
|
|
2016
|
+
if (!collector) return;
|
|
2017
|
+
try {
|
|
2018
|
+
attemptOf(ctx).navStart = performance.now();
|
|
2019
|
+
} catch {
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
const postNav = (ctx) => {
|
|
2023
|
+
if (!collector) return;
|
|
2024
|
+
try {
|
|
2025
|
+
const a = attemptOf(ctx);
|
|
2026
|
+
if (a.navStart !== void 0) a.navMs = msSince(a.navStart);
|
|
2027
|
+
a.statusCode = statusFrom(ctx.response);
|
|
2028
|
+
a.bytes = headerBytes(ctx.response);
|
|
2029
|
+
} catch {
|
|
2030
|
+
}
|
|
2031
|
+
};
|
|
2032
|
+
if (Array.isArray(crawlerAny.preNavigationHooks)) {
|
|
2033
|
+
crawlerAny.preNavigationHooks = [...crawlerAny.preNavigationHooks, preNav];
|
|
2034
|
+
}
|
|
2035
|
+
if (Array.isArray(crawlerAny.postNavigationHooks)) {
|
|
2036
|
+
crawlerAny.postNavigationHooks = [postNav, ...crawlerAny.postNavigationHooks];
|
|
2037
|
+
}
|
|
2038
|
+
const userErrorHandler = crawlerAny.errorHandler;
|
|
2039
|
+
crawlerAny.errorHandler = function(...args) {
|
|
2040
|
+
const c = collector;
|
|
2041
|
+
if (c) {
|
|
2042
|
+
try {
|
|
2043
|
+
noteFailure(c, args[0], args[1]);
|
|
2044
|
+
} catch (analyticsErr) {
|
|
2045
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
return typeof userErrorHandler === "function" ? userErrorHandler.apply(this, args) : void 0;
|
|
2049
|
+
};
|
|
2050
|
+
const userFailedHandler = crawlerAny.failedRequestHandler;
|
|
2051
|
+
crawlerAny.failedRequestHandler = function(...args) {
|
|
2052
|
+
const c = collector;
|
|
2053
|
+
if (c) {
|
|
2054
|
+
try {
|
|
2055
|
+
const ctx = args[0];
|
|
2056
|
+
const { a, blockType } = noteFailure(c, ctx, args[1]);
|
|
2057
|
+
const req = ctx.request;
|
|
2058
|
+
c.error(reportLabel(req.label), args[1], contextFor(c, a, req));
|
|
2059
|
+
emitRequest(c, ctx, a, blockType ? "blocked" : "failed", blockType);
|
|
2060
|
+
} catch (analyticsErr) {
|
|
2061
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
return typeof userFailedHandler === "function" ? userFailedHandler.apply(this, args) : void 0;
|
|
2065
|
+
};
|
|
2066
|
+
}
|
|
1692
2067
|
if (typeof crawlerAny.run === "function") {
|
|
1693
2068
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
1694
2069
|
crawlerAny.run = async (...args) => {
|
|
1695
2070
|
runStats.startTime = Date.now();
|
|
2071
|
+
safeBeginRun(client);
|
|
1696
2072
|
const runStartedAt = new Date(runStats.startTime).toISOString();
|
|
1697
2073
|
labelStats.clear();
|
|
1698
2074
|
const runBase = {
|
|
@@ -1708,94 +2084,190 @@ var FetchBrain = class {
|
|
|
1708
2084
|
};
|
|
1709
2085
|
const changeBase = safeChangeStats(client);
|
|
1710
2086
|
const runId = nextRunId();
|
|
2087
|
+
let analyticsQueue;
|
|
2088
|
+
let reportClient;
|
|
2089
|
+
let reportAnalytics;
|
|
2090
|
+
if (analyticsOn) {
|
|
2091
|
+
try {
|
|
2092
|
+
const [mod, cfg] = await Promise.all([loadCollector(), fetchAnalyticsConfig(client)]);
|
|
2093
|
+
if (mod && cfg?.enabled !== false) {
|
|
2094
|
+
const analyticsRunId = runId;
|
|
2095
|
+
const scraper = client.getScraperName();
|
|
2096
|
+
const batchStartSeq = mod.startSeqFromEnv();
|
|
2097
|
+
analyticsQueue = new mod.AnalyticsQueue(
|
|
2098
|
+
(gz, signal) => client.postAnalyticsEvents(gz, analyticsRunId, signal),
|
|
2099
|
+
{
|
|
2100
|
+
wrap: (events, seq) => ({ runId: analyticsRunId, scraper, seq, events }),
|
|
2101
|
+
// Unique across Apify migrations: a restarted process must not reuse the earlier seqs.
|
|
2102
|
+
startSeq: batchStartSeq
|
|
2103
|
+
}
|
|
2104
|
+
);
|
|
2105
|
+
if (cfg) {
|
|
2106
|
+
if (Number.isFinite(cfg.sampleRate) && cfg.sampleRate > 0 && cfg.sampleRate <= 1) {
|
|
2107
|
+
analyticsQueue.sampleRate = cfg.sampleRate;
|
|
2108
|
+
}
|
|
2109
|
+
if (typeof cfg.pauseUntil === "number") analyticsQueue.pause(cfg.pauseUntil);
|
|
2110
|
+
}
|
|
2111
|
+
const apifyUserId = process.env.APIFY_USER_ID;
|
|
2112
|
+
const clientHash = apifyUserId && cfg?.salt ? mod.Collector.hashClient(apifyUserId, cfg.salt) : void 0;
|
|
2113
|
+
collector = new mod.Collector(
|
|
2114
|
+
analyticsQueue,
|
|
2115
|
+
{
|
|
2116
|
+
runId: analyticsRunId,
|
|
2117
|
+
scraper,
|
|
2118
|
+
...clientHash ? { client: clientHash } : {},
|
|
2119
|
+
crawlerType,
|
|
2120
|
+
sdkVersion: mod.SDK_VERSION,
|
|
2121
|
+
platform: process.env.APIFY_IS_AT_HOME || process.env.APIFY_ACTOR_ID ? "apify" : "other"
|
|
2122
|
+
},
|
|
2123
|
+
{
|
|
2124
|
+
debug: (msg) => logger.debug(msg),
|
|
2125
|
+
// Event seqs after a migration start above the earlier process's (batch seq
|
|
2126
|
+
// is whole seconds x 1000, so x 1000 again leaves 1e6 events per second of run).
|
|
2127
|
+
startSeq: batchStartSeq * 1e3
|
|
2128
|
+
}
|
|
2129
|
+
);
|
|
2130
|
+
reportClient = clientHash;
|
|
2131
|
+
const quotaSeen = /* @__PURE__ */ new Set();
|
|
2132
|
+
safeOnQuotaReached(client, (cap) => {
|
|
2133
|
+
if (quotaSeen.has(cap)) return;
|
|
2134
|
+
quotaSeen.add(cap);
|
|
2135
|
+
collector?.quotaReached(cap);
|
|
2136
|
+
});
|
|
2137
|
+
blockedByRequest.clear();
|
|
2138
|
+
emittedThenFailed.clear();
|
|
2139
|
+
const memoryMb = Number(process.env.APIFY_MEMORY_MBYTES);
|
|
2140
|
+
const maxConcurrency = crawlerAny.autoscaledPoolOptions?.maxConcurrency;
|
|
2141
|
+
collector.runStarted({
|
|
2142
|
+
memoryMb: Number.isFinite(memoryMb) && memoryMb > 0 ? memoryMb : void 0,
|
|
2143
|
+
maxConcurrency: typeof maxConcurrency === "number" ? maxConcurrency : void 0
|
|
2144
|
+
});
|
|
2145
|
+
analyticsQueue.start();
|
|
2146
|
+
}
|
|
2147
|
+
} catch (analyticsErr) {
|
|
2148
|
+
collector = void 0;
|
|
2149
|
+
analyticsQueue = void 0;
|
|
2150
|
+
reportClient = void 0;
|
|
2151
|
+
safeOnQuotaReached(client, void 0);
|
|
2152
|
+
logger.debug(`Analytics off for this run: ${analyticsErr}`);
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
1711
2155
|
try {
|
|
1712
2156
|
const result = await originalRun(...args);
|
|
1713
2157
|
return result;
|
|
1714
2158
|
} finally {
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
2159
|
+
let analyticsStop;
|
|
2160
|
+
if (analyticsQueue) {
|
|
2161
|
+
try {
|
|
2162
|
+
collector?.runFinished({ durationMs: Date.now() - runStats.startTime });
|
|
2163
|
+
if (collector) reportAnalytics = { labels: collector.labelStats(), ...collector.aggregateReport() };
|
|
2164
|
+
} catch (analyticsErr) {
|
|
2165
|
+
logger.debug(`Analytics skipped: ${analyticsErr}`);
|
|
2166
|
+
}
|
|
2167
|
+
analyticsStop = analyticsQueue.stop().catch((analyticsErr) => {
|
|
2168
|
+
logger.debug(`Analytics flush skipped: ${analyticsErr}`);
|
|
2169
|
+
});
|
|
2170
|
+
collector = void 0;
|
|
1721
2171
|
}
|
|
1722
|
-
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1723
|
-
1
|
|
1724
|
-
);
|
|
1725
|
-
const run = {
|
|
1726
|
-
totalRequests: runStats.totalRequests - runBase.totalRequests,
|
|
1727
|
-
bypassed: runStats.bypassed - runBase.bypassed,
|
|
1728
|
-
dropped: runStats.dropped - runBase.dropped,
|
|
1729
|
-
scraped: runStats.scraped - runBase.scraped,
|
|
1730
|
-
learned: runStats.learned - runBase.learned,
|
|
1731
|
-
recalled: runStats.recalled - runBase.recalled,
|
|
1732
|
-
aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
|
|
1733
|
-
requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
|
|
1734
|
-
lateRecalls: runStats.lateRecalls - runBase.lateRecalls
|
|
1735
|
-
};
|
|
1736
|
-
const managedRequests = run.totalRequests - run.bypassed;
|
|
1737
|
-
const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
1738
|
-
let changes = { changed: 0, drift: [] };
|
|
1739
2172
|
try {
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
};
|
|
1747
|
-
} catch (diffErr) {
|
|
1748
|
-
logger.debug(`Change summary skipped: ${diffErr}`);
|
|
1749
|
-
}
|
|
1750
|
-
const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
|
|
1751
|
-
logger.info(
|
|
1752
|
-
`\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`
|
|
1753
|
-
);
|
|
1754
|
-
if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
|
|
1755
|
-
logger.info(
|
|
1756
|
-
`${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).`
|
|
2173
|
+
safeOnQuotaReached(client, void 0);
|
|
2174
|
+
logger.debug("Flushing pending learn requests on crawl complete");
|
|
2175
|
+
await client.flushLearnBatch();
|
|
2176
|
+
await Promise.allSettled([...pendingLearns]);
|
|
2177
|
+
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
2178
|
+
1
|
|
1757
2179
|
);
|
|
1758
|
-
|
|
1759
|
-
|
|
2180
|
+
const run = {
|
|
2181
|
+
totalRequests: runStats.totalRequests - runBase.totalRequests,
|
|
2182
|
+
bypassed: runStats.bypassed - runBase.bypassed,
|
|
2183
|
+
dropped: runStats.dropped - runBase.dropped,
|
|
2184
|
+
scraped: runStats.scraped - runBase.scraped,
|
|
2185
|
+
learned: runStats.learned - runBase.learned,
|
|
2186
|
+
recalled: runStats.recalled - runBase.recalled,
|
|
2187
|
+
aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
|
|
2188
|
+
requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
|
|
2189
|
+
lateRecalls: runStats.lateRecalls - runBase.lateRecalls
|
|
2190
|
+
};
|
|
2191
|
+
const managedRequests = run.totalRequests - run.bypassed;
|
|
2192
|
+
const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
2193
|
+
let changes = { changed: 0, drift: [], known: 0 };
|
|
1760
2194
|
try {
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
2195
|
+
const now = safeChangeStats(client);
|
|
2196
|
+
const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
|
|
2197
|
+
const seen = new Set(changeBase.drift.map(key));
|
|
2198
|
+
changes = {
|
|
2199
|
+
changed: Math.max(0, now.changed - changeBase.changed) || 0,
|
|
2200
|
+
drift: now.drift.filter((d) => !seen.has(key(d))),
|
|
2201
|
+
known: Math.max(0, (now.known ?? 0) - (changeBase.known ?? 0)) || 0
|
|
2202
|
+
};
|
|
2203
|
+
} catch (diffErr) {
|
|
2204
|
+
logger.debug(`Change summary skipped: ${diffErr}`);
|
|
1764
2205
|
}
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1774
|
-
scraped: run.scraped,
|
|
1775
|
-
learned: run.learned,
|
|
1776
|
-
recalled: run.recalled,
|
|
1777
|
-
requestsSkipped: run.requestsSkipped,
|
|
1778
|
-
lateRecalls: run.lateRecalls,
|
|
1779
|
-
bypassed: run.bypassed,
|
|
1780
|
-
labels
|
|
1781
|
-
});
|
|
1782
|
-
for (const flag of Array.isArray(flags) ? flags : []) {
|
|
1783
|
-
if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
|
|
1784
|
-
continue;
|
|
1785
|
-
}
|
|
1786
|
-
const label = clipText(flag.label, 64);
|
|
1787
|
-
logger.warn(
|
|
1788
|
-
flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
|
|
2206
|
+
const showChanged = observe || config.changeDetection?.enabled === true || changes.changed > 0;
|
|
2207
|
+
if (observe) {
|
|
2208
|
+
logger.info(
|
|
2209
|
+
`\u{1F440} Observe run finished: learned: ${run.learned}, scraped: ${run.scraped}, changed: ${changes.changed}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + `, duration: ${duration}s`
|
|
2210
|
+
);
|
|
2211
|
+
if (changes.known > 0) {
|
|
2212
|
+
logger.info(
|
|
2213
|
+
`${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"}.`
|
|
1789
2214
|
);
|
|
1790
2215
|
}
|
|
1791
|
-
}
|
|
1792
|
-
|
|
2216
|
+
} else logger.info(
|
|
2217
|
+
`\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`
|
|
2218
|
+
);
|
|
2219
|
+
if (!observe && run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
|
|
2220
|
+
logger.info(
|
|
2221
|
+
`${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).`
|
|
2222
|
+
);
|
|
2223
|
+
}
|
|
2224
|
+
for (const item of changes.drift) {
|
|
2225
|
+
try {
|
|
2226
|
+
logger.warn(describeDrift(item));
|
|
2227
|
+
} catch (warnErr) {
|
|
2228
|
+
logger.debug(`Drift warning skipped: ${warnErr}`);
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
if (config.reportRuns !== false) {
|
|
2232
|
+
try {
|
|
2233
|
+
const labels = Object.fromEntries(labelStats);
|
|
2234
|
+
const flags = await client.reportRun({
|
|
2235
|
+
runId,
|
|
2236
|
+
build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
|
|
2237
|
+
startedAt: runStartedAt,
|
|
2238
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2239
|
+
scraped: run.scraped,
|
|
2240
|
+
learned: run.learned,
|
|
2241
|
+
recalled: run.recalled,
|
|
2242
|
+
requestsSkipped: run.requestsSkipped,
|
|
2243
|
+
// recall:false: pages memory already knew were fetched anyway —
|
|
2244
|
+
// the same untapped savings late recalls report.
|
|
2245
|
+
lateRecalls: observe ? changes.known : run.lateRecalls,
|
|
2246
|
+
bypassed: run.bypassed,
|
|
2247
|
+
labels,
|
|
2248
|
+
...reportClient ? { client: reportClient } : {},
|
|
2249
|
+
...reportAnalytics ? { analytics: reportAnalytics } : {}
|
|
2250
|
+
});
|
|
2251
|
+
for (const flag of Array.isArray(flags) ? flags : []) {
|
|
2252
|
+
if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
const label = clipText(flag.label, 64);
|
|
2256
|
+
logger.warn(
|
|
2257
|
+
flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
} catch (reportErr) {
|
|
2261
|
+
logger.debug(`Run report skipped: ${reportErr}`);
|
|
2262
|
+
}
|
|
1793
2263
|
}
|
|
2264
|
+
} finally {
|
|
2265
|
+
await analyticsStop;
|
|
1794
2266
|
}
|
|
1795
2267
|
}
|
|
1796
2268
|
};
|
|
1797
2269
|
}
|
|
1798
|
-
if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
2270
|
+
if (!observe && config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
1799
2271
|
const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
|
|
1800
2272
|
if (crawlerAny.retryOnBlocked) {
|
|
1801
2273
|
logger.info(
|
|
@@ -1924,8 +2396,18 @@ async function pushData(data, dataset, datasetName) {
|
|
|
1924
2396
|
} else {
|
|
1925
2397
|
await dataset.pushData(data);
|
|
1926
2398
|
}
|
|
2399
|
+
try {
|
|
2400
|
+
ctx?.records?.(Array.isArray(data) ? data.length : 1);
|
|
2401
|
+
} catch {
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
function capture(name, props) {
|
|
2405
|
+
try {
|
|
2406
|
+
asyncContext.getStore()?.capture?.(name, props);
|
|
2407
|
+
} catch {
|
|
2408
|
+
}
|
|
1927
2409
|
}
|
|
1928
2410
|
|
|
1929
|
-
export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher,
|
|
2411
|
+
export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, capture, createFetchBrain, createLogger, getCurrentContext, pushData };
|
|
1930
2412
|
//# sourceMappingURL=index.mjs.map
|
|
1931
2413
|
//# sourceMappingURL=index.mjs.map
|