@fetchbrain.com/sdk 0.8.0 → 0.10.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 +95 -11
- package/dist/index.d.mts +27 -3
- package/dist/index.d.ts +27 -3
- package/dist/index.js +206 -55
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +206 -55
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +2 -1
- package/dist/mock/index.d.ts +2 -1
- package/dist/mock/index.js +1 -1
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +1 -1
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-B579TMo9.d.mts → types-BCbMwaYW.d.mts} +32 -2
- package/dist/{types-B579TMo9.d.ts → types-BCbMwaYW.d.ts} +32 -2
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -13,13 +13,21 @@ var DEFAULT_CONFIG = {
|
|
|
13
13
|
successThreshold: 1
|
|
14
14
|
};
|
|
15
15
|
var CircuitBreaker = class {
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* `name` labels this breaker's log lines when a client runs more than one
|
|
18
|
+
* (the ask breaker opening must not read as if recall and learn stopped).
|
|
19
|
+
*/
|
|
20
|
+
constructor(config = {}, logger, name) {
|
|
17
21
|
this.state = "closed";
|
|
18
22
|
this.failures = 0;
|
|
19
23
|
this.successes = 0;
|
|
20
24
|
this.lastFailureTime = 0;
|
|
21
25
|
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
22
26
|
this.logger = logger;
|
|
27
|
+
this.name = name;
|
|
28
|
+
}
|
|
29
|
+
label(message) {
|
|
30
|
+
return this.name ? `${this.name} circuit: ${message}` : message;
|
|
23
31
|
}
|
|
24
32
|
/**
|
|
25
33
|
* Check if requests should be allowed through
|
|
@@ -31,7 +39,7 @@ var CircuitBreaker = class {
|
|
|
31
39
|
if (this.state === "open") {
|
|
32
40
|
const now = Date.now();
|
|
33
41
|
if (now - this.lastFailureTime >= this.config.resetTimeout) {
|
|
34
|
-
this.logger.info("Circuit transitioning to half-open, testing API...");
|
|
42
|
+
this.logger.info(this.label("Circuit transitioning to half-open, testing API..."));
|
|
35
43
|
this.state = "half-open";
|
|
36
44
|
this.successes = 0;
|
|
37
45
|
return false;
|
|
@@ -47,7 +55,7 @@ var CircuitBreaker = class {
|
|
|
47
55
|
if (this.state === "half-open") {
|
|
48
56
|
this.successes++;
|
|
49
57
|
if (this.successes >= this.config.successThreshold) {
|
|
50
|
-
this.logger.info("API recovered, circuit closed");
|
|
58
|
+
this.logger.info(this.label("API recovered, circuit closed"));
|
|
51
59
|
this.reset();
|
|
52
60
|
}
|
|
53
61
|
} else if (this.state === "closed") {
|
|
@@ -61,13 +69,13 @@ var CircuitBreaker = class {
|
|
|
61
69
|
this.failures++;
|
|
62
70
|
this.lastFailureTime = Date.now();
|
|
63
71
|
if (this.state === "half-open") {
|
|
64
|
-
this.logger.warn("API still failing, circuit reopened");
|
|
72
|
+
this.logger.warn(this.label("API still failing, circuit reopened"));
|
|
65
73
|
this.state = "open";
|
|
66
74
|
return;
|
|
67
75
|
}
|
|
68
76
|
if (this.failures >= this.config.failureThreshold) {
|
|
69
77
|
this.logger.warn(
|
|
70
|
-
`Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
|
|
78
|
+
this.name ? `${this.name} circuit opened after ${this.failures} failures. ${this.name} calls are paused; recall and learn are unaffected.` : `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
|
|
71
79
|
);
|
|
72
80
|
this.state = "open";
|
|
73
81
|
}
|
|
@@ -432,7 +440,7 @@ var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
|
432
440
|
var DEFAULT_TIMEOUT = 1500;
|
|
433
441
|
var REPORT_RUN_TIMEOUT = 3e3;
|
|
434
442
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
435
|
-
var BULK_RECALL_TIMEOUT =
|
|
443
|
+
var BULK_RECALL_TIMEOUT = 1e4;
|
|
436
444
|
var MAX_BULK_ITEMS = 90;
|
|
437
445
|
var KEY_REJECTED_PAUSE_MS = 6e4;
|
|
438
446
|
var BULK_RECALL_CONCURRENCY = 5;
|
|
@@ -441,7 +449,23 @@ var MAX_LEARN_DATA_BYTES = 100 * 1024;
|
|
|
441
449
|
function isOutage(error) {
|
|
442
450
|
return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
|
|
443
451
|
}
|
|
444
|
-
var
|
|
452
|
+
var LEARN_RETRY_BASE_MS = 1e3;
|
|
453
|
+
var LEARN_RETRY_MAX_MS = 5e3;
|
|
454
|
+
function learnRetryDelayMs(error, random = Math.random) {
|
|
455
|
+
const hinted = error instanceof ApiError && error.retryAfterSec !== void 0 ? error.retryAfterSec * 1e3 : LEARN_RETRY_BASE_MS;
|
|
456
|
+
const base = Math.min(Math.max(hinted, 0), LEARN_RETRY_MAX_MS);
|
|
457
|
+
return base / 2 + random() * (base / 2);
|
|
458
|
+
}
|
|
459
|
+
var DEFAULT_ASK_TIMEOUT = 6e4;
|
|
460
|
+
var MAX_TIMER_MS = 2147483647;
|
|
461
|
+
function resolveTimeout(value, fallback, name, logger) {
|
|
462
|
+
if (value === void 0 || value === null) return fallback;
|
|
463
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && value <= MAX_TIMER_MS) {
|
|
464
|
+
return value;
|
|
465
|
+
}
|
|
466
|
+
logger.debug(`ignoring invalid ${name} (${String(value)}); using ${fallback}ms. Use 1-${MAX_TIMER_MS} ms.`);
|
|
467
|
+
return fallback;
|
|
468
|
+
}
|
|
445
469
|
function clampBatch(batch, cap) {
|
|
446
470
|
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
447
471
|
}
|
|
@@ -495,6 +519,7 @@ var FetchBrainClient = class {
|
|
|
495
519
|
this.learnCapWarnedUntil = 0;
|
|
496
520
|
/** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
|
|
497
521
|
this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
|
|
522
|
+
this.logger = createLogger(config.debug ? "debug" : "info", true);
|
|
498
523
|
this.config = {
|
|
499
524
|
apiKey: config.apiKey,
|
|
500
525
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
@@ -502,7 +527,8 @@ var FetchBrainClient = class {
|
|
|
502
527
|
learning: config.learning ?? true,
|
|
503
528
|
alwaysRun: config.alwaysRun ?? false,
|
|
504
529
|
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
505
|
-
timeout: config.timeout
|
|
530
|
+
timeout: resolveTimeout(config.timeout, DEFAULT_TIMEOUT, "timeout", this.logger),
|
|
531
|
+
askTimeout: resolveTimeout(config.askTimeout, DEFAULT_ASK_TIMEOUT, "askTimeout", this.logger),
|
|
506
532
|
debug: config.debug || false,
|
|
507
533
|
extractForLearning: config.extractForLearning,
|
|
508
534
|
learnUrlField: config.learnUrlField,
|
|
@@ -516,11 +542,12 @@ var FetchBrainClient = class {
|
|
|
516
542
|
// enhance-only; stored so getConfig() round-trips
|
|
517
543
|
onRecalled: config.onRecalled,
|
|
518
544
|
// enhance-only; stored so getConfig() round-trips
|
|
545
|
+
logUrl: config.logUrl,
|
|
546
|
+
// enhance-only; stored so getConfig() round-trips
|
|
519
547
|
scraper: config.scraper,
|
|
520
548
|
changeDetection: config.changeDetection,
|
|
521
549
|
reportRuns: config.reportRuns ?? true
|
|
522
550
|
};
|
|
523
|
-
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
524
551
|
const scraper = resolveScraperName(config.scraper);
|
|
525
552
|
this.scraperName = scraper.name;
|
|
526
553
|
for (const source of scraper.rejected) {
|
|
@@ -532,6 +559,11 @@ var FetchBrainClient = class {
|
|
|
532
559
|
this.config.circuitBreaker,
|
|
533
560
|
this.logger
|
|
534
561
|
);
|
|
562
|
+
this.askCircuitBreaker = new CircuitBreaker(
|
|
563
|
+
this.config.circuitBreaker,
|
|
564
|
+
this.logger,
|
|
565
|
+
"Ask"
|
|
566
|
+
);
|
|
535
567
|
this.batcher = new RequestBatcher(
|
|
536
568
|
(items) => this.executeBatchQuery(items),
|
|
537
569
|
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
@@ -592,6 +624,7 @@ var FetchBrainClient = class {
|
|
|
592
624
|
chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
|
|
593
625
|
}
|
|
594
626
|
const chunkResults = new Array(chunks.length);
|
|
627
|
+
const outcome = { outage: false, success: false };
|
|
595
628
|
let next = 0;
|
|
596
629
|
const worker = async () => {
|
|
597
630
|
while (next < chunks.length) {
|
|
@@ -603,7 +636,7 @@ var FetchBrainClient = class {
|
|
|
603
636
|
}
|
|
604
637
|
try {
|
|
605
638
|
const items = chunk.map((request, i) => ({ ref: String(i), request }));
|
|
606
|
-
const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
|
|
639
|
+
const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT, outcome);
|
|
607
640
|
chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
|
|
608
641
|
} catch {
|
|
609
642
|
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
@@ -613,6 +646,8 @@ var FetchBrainClient = class {
|
|
|
613
646
|
await Promise.all(
|
|
614
647
|
Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
|
|
615
648
|
);
|
|
649
|
+
if (outcome.outage) this.circuitBreaker.recordFailure();
|
|
650
|
+
else if (outcome.success) this.circuitBreaker.recordSuccess();
|
|
616
651
|
return chunkResults.flat();
|
|
617
652
|
}
|
|
618
653
|
/**
|
|
@@ -669,9 +704,12 @@ var FetchBrainClient = class {
|
|
|
669
704
|
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
670
705
|
* credits), or "byok" to answer with your own linked provider model.
|
|
671
706
|
* Omit it for the default model.
|
|
707
|
+
*
|
|
708
|
+
* `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
|
|
709
|
+
* an invalid value falls back to `askTimeout`.
|
|
672
710
|
*/
|
|
673
711
|
async ask(question, opts) {
|
|
674
|
-
if (this.
|
|
712
|
+
if (this.isKeyRejected() || this.askCircuitBreaker.isOpen()) {
|
|
675
713
|
return { sources: [], status: "unavailable" };
|
|
676
714
|
}
|
|
677
715
|
const askBody = {
|
|
@@ -691,9 +729,9 @@ var FetchBrainClient = class {
|
|
|
691
729
|
method: "POST",
|
|
692
730
|
body: JSON.stringify(askBody)
|
|
693
731
|
},
|
|
694
|
-
|
|
732
|
+
resolveTimeout(opts?.timeout, this.config.askTimeout, "ask timeout", this.logger)
|
|
695
733
|
);
|
|
696
|
-
this.
|
|
734
|
+
this.askCircuitBreaker.recordSuccess();
|
|
697
735
|
return response;
|
|
698
736
|
} catch (error) {
|
|
699
737
|
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
@@ -704,7 +742,7 @@ var FetchBrainClient = class {
|
|
|
704
742
|
error: error.serverError ?? error.message
|
|
705
743
|
};
|
|
706
744
|
}
|
|
707
|
-
this.
|
|
745
|
+
this.askCircuitBreaker.recordFailure();
|
|
708
746
|
this.logger.debug("Ask request failed:", error);
|
|
709
747
|
return { sources: [], status: "unavailable" };
|
|
710
748
|
}
|
|
@@ -712,7 +750,7 @@ var FetchBrainClient = class {
|
|
|
712
750
|
/**
|
|
713
751
|
* Execute a batch query against the API
|
|
714
752
|
*/
|
|
715
|
-
async executeBatchQuery(items, timeout) {
|
|
753
|
+
async executeBatchQuery(items, timeout, outcome) {
|
|
716
754
|
const results = /* @__PURE__ */ new Map();
|
|
717
755
|
const request = {
|
|
718
756
|
items,
|
|
@@ -731,7 +769,8 @@ var FetchBrainClient = class {
|
|
|
731
769
|
},
|
|
732
770
|
timeout
|
|
733
771
|
);
|
|
734
|
-
|
|
772
|
+
if (outcome) outcome.success = true;
|
|
773
|
+
else this.circuitBreaker.recordSuccess();
|
|
735
774
|
for (const item of response.known) {
|
|
736
775
|
results.set(item.ref, { known: true, data: item.data });
|
|
737
776
|
}
|
|
@@ -740,8 +779,9 @@ var FetchBrainClient = class {
|
|
|
740
779
|
}
|
|
741
780
|
return results;
|
|
742
781
|
} catch (error) {
|
|
743
|
-
if (isOutage(error)) this.
|
|
744
|
-
else
|
|
782
|
+
if (!isOutage(error)) this.noteRefusal(error);
|
|
783
|
+
else if (outcome) outcome.outage = true;
|
|
784
|
+
else this.circuitBreaker.recordFailure();
|
|
745
785
|
throw error;
|
|
746
786
|
}
|
|
747
787
|
}
|
|
@@ -764,14 +804,7 @@ var FetchBrainClient = class {
|
|
|
764
804
|
request.build = platformBuildId;
|
|
765
805
|
}
|
|
766
806
|
try {
|
|
767
|
-
const response = await this.
|
|
768
|
-
"/v1/learn",
|
|
769
|
-
{
|
|
770
|
-
method: "POST",
|
|
771
|
-
body: JSON.stringify(request)
|
|
772
|
-
},
|
|
773
|
-
DEFAULT_LEARN_TIMEOUT
|
|
774
|
-
);
|
|
807
|
+
const response = await this.sendLearnWithRetry(request);
|
|
775
808
|
this.circuitBreaker.recordSuccess();
|
|
776
809
|
try {
|
|
777
810
|
this.accumulateChanges(response);
|
|
@@ -803,6 +836,28 @@ var FetchBrainClient = class {
|
|
|
803
836
|
throw error;
|
|
804
837
|
}
|
|
805
838
|
}
|
|
839
|
+
/**
|
|
840
|
+
* POST one learn batch, retrying once after a jittered wait on a timeout,
|
|
841
|
+
* network error or 5xx. Learns run off the crawl's hot path, so a short
|
|
842
|
+
* stall is not an outage: in the 2026-11-28 load test one storage shard
|
|
843
|
+
* paused for ~5 s, the ~3 learns a run keeps in flight all timed out
|
|
844
|
+
* together, and that opened the breaker shared with recall. Only a batch
|
|
845
|
+
* that fails twice reaches executeBatchLearn's breaker accounting.
|
|
846
|
+
*/
|
|
847
|
+
async sendLearnWithRetry(request) {
|
|
848
|
+
const send = () => this.makeRequest(
|
|
849
|
+
"/v1/learn",
|
|
850
|
+
{ method: "POST", body: JSON.stringify(request) },
|
|
851
|
+
DEFAULT_LEARN_TIMEOUT
|
|
852
|
+
);
|
|
853
|
+
try {
|
|
854
|
+
return await send();
|
|
855
|
+
} catch (error) {
|
|
856
|
+
if (!isOutage(error)) throw error;
|
|
857
|
+
await new Promise((resolve) => setTimeout(resolve, learnRetryDelayMs(error)));
|
|
858
|
+
return send();
|
|
859
|
+
}
|
|
860
|
+
}
|
|
806
861
|
/** Fold one batch response into the change totals (called once per HTTP batch). */
|
|
807
862
|
accumulateChanges(response) {
|
|
808
863
|
const stats = this.changeStats;
|
|
@@ -861,6 +916,18 @@ var FetchBrainClient = class {
|
|
|
861
916
|
() => controller.abort(),
|
|
862
917
|
timeout ?? this.config.timeout
|
|
863
918
|
);
|
|
919
|
+
const aborted = new Promise((_, reject) => {
|
|
920
|
+
const fail = () => reject(new DOMException("FetchBrain request timed out", "AbortError"));
|
|
921
|
+
if (controller.signal.aborted) fail();
|
|
922
|
+
else controller.signal.addEventListener("abort", fail, { once: true });
|
|
923
|
+
});
|
|
924
|
+
aborted.catch(() => {
|
|
925
|
+
});
|
|
926
|
+
const readBody = (response, read) => Promise.race([read(response), aborted]).catch((err) => {
|
|
927
|
+
response.body?.cancel().catch(() => {
|
|
928
|
+
});
|
|
929
|
+
throw err;
|
|
930
|
+
});
|
|
864
931
|
const contextHeaders = {
|
|
865
932
|
"X-FB-SDK": "js",
|
|
866
933
|
"X-FB-Node": process.version || "unknown",
|
|
@@ -894,7 +961,7 @@ var FetchBrainClient = class {
|
|
|
894
961
|
let serverError;
|
|
895
962
|
let code;
|
|
896
963
|
try {
|
|
897
|
-
const errBody = await response.json();
|
|
964
|
+
const errBody = await readBody(response, (r) => r.json());
|
|
898
965
|
if (typeof errBody.error === "string") serverError = errBody.error;
|
|
899
966
|
const specific = errBody.details?.code ?? errBody.code;
|
|
900
967
|
if (typeof specific === "string") code = specific;
|
|
@@ -908,7 +975,7 @@ var FetchBrainClient = class {
|
|
|
908
975
|
parseRetryAfter(response.headers.get("Retry-After"))
|
|
909
976
|
);
|
|
910
977
|
}
|
|
911
|
-
return await response.json();
|
|
978
|
+
return await readBody(response, (r) => r.json());
|
|
912
979
|
} finally {
|
|
913
980
|
clearTimeout(timeoutId);
|
|
914
981
|
}
|
|
@@ -930,6 +997,7 @@ var FetchBrainClient = class {
|
|
|
930
997
|
*/
|
|
931
998
|
resetCircuit() {
|
|
932
999
|
this.circuitBreaker.reset();
|
|
1000
|
+
this.askCircuitBreaker.reset();
|
|
933
1001
|
}
|
|
934
1002
|
/**
|
|
935
1003
|
* Clear pending batched requests
|
|
@@ -1161,7 +1229,12 @@ function safeChangeStats(client) {
|
|
|
1161
1229
|
}
|
|
1162
1230
|
}
|
|
1163
1231
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
1164
|
-
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set([
|
|
1232
|
+
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set([
|
|
1233
|
+
"fetchBrainRecalled",
|
|
1234
|
+
"fetchBrainData",
|
|
1235
|
+
"__fetchBrainResult",
|
|
1236
|
+
"__fetchBrainCounted"
|
|
1237
|
+
]);
|
|
1165
1238
|
var MAX_STASH_ENTRIES = 5e3;
|
|
1166
1239
|
var MAX_STASH_BYTES = 256 * 1024 * 1024;
|
|
1167
1240
|
var stashBytesCap = MAX_STASH_BYTES;
|
|
@@ -1200,12 +1273,32 @@ function buildRawRequest(request) {
|
|
|
1200
1273
|
if (typeof r.payload === "string") body = r.payload;
|
|
1201
1274
|
return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
|
|
1202
1275
|
}
|
|
1203
|
-
function
|
|
1276
|
+
function logUrlFor(request, logUrl) {
|
|
1277
|
+
if (!logUrl) return request.url;
|
|
1278
|
+
try {
|
|
1279
|
+
const shown = logUrl({
|
|
1280
|
+
url: request.url,
|
|
1281
|
+
uniqueKey: request.uniqueKey ?? request.url,
|
|
1282
|
+
label: labelText(request.label),
|
|
1283
|
+
userData: request.userData ?? {}
|
|
1284
|
+
});
|
|
1285
|
+
if (shown && typeof shown.then === "function") {
|
|
1286
|
+
Promise.resolve(shown).catch(() => {
|
|
1287
|
+
});
|
|
1288
|
+
return void 0;
|
|
1289
|
+
}
|
|
1290
|
+
return typeof shown === "string" && shown !== "" ? shown : void 0;
|
|
1291
|
+
} catch {
|
|
1292
|
+
return void 0;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
var urlSuffix = (shown) => shown ? `: ${shown}` : "";
|
|
1296
|
+
function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
|
|
1204
1297
|
const method = (request.method ?? "GET").toUpperCase();
|
|
1205
1298
|
const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
|
|
1206
1299
|
if (method !== "GET" && isDefault && !warned.has(request.url)) {
|
|
1207
1300
|
warned.add(request.url);
|
|
1208
|
-
logger.warn(`FetchBrain: ${method} ${request
|
|
1301
|
+
logger.warn(`FetchBrain: ${method} ${shownUrl() ?? "request"} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't get their own memory.`);
|
|
1209
1302
|
}
|
|
1210
1303
|
}
|
|
1211
1304
|
var asyncContext = new async_hooks.AsyncLocalStorage();
|
|
@@ -1280,6 +1373,10 @@ var FetchBrain = class {
|
|
|
1280
1373
|
recalled: 0,
|
|
1281
1374
|
aiSkipped: 0,
|
|
1282
1375
|
// brain knew + skipped scraping
|
|
1376
|
+
requestsSkipped: 0,
|
|
1377
|
+
// recalled without a fetch (pre-recalled at enqueue + skipNavigation)
|
|
1378
|
+
lateRecalls: 0,
|
|
1379
|
+
// recalled after the page was already fetched
|
|
1283
1380
|
learned: 0,
|
|
1284
1381
|
scraped: 0,
|
|
1285
1382
|
// Actually ran handler
|
|
@@ -1358,7 +1455,9 @@ var FetchBrain = class {
|
|
|
1358
1455
|
runStats.totalRequests++;
|
|
1359
1456
|
if (skipLabels && skipLabels.has(label || "default")) {
|
|
1360
1457
|
runStats.bypassed++;
|
|
1361
|
-
|
|
1458
|
+
if (config.debug) {
|
|
1459
|
+
logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
|
|
1460
|
+
}
|
|
1362
1461
|
await originalHandler.call(crawler, context);
|
|
1363
1462
|
return;
|
|
1364
1463
|
}
|
|
@@ -1368,7 +1467,9 @@ var FetchBrain = class {
|
|
|
1368
1467
|
url
|
|
1369
1468
|
});
|
|
1370
1469
|
const rawRequest = buildRawRequest(request);
|
|
1371
|
-
|
|
1470
|
+
let shown;
|
|
1471
|
+
const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
|
|
1472
|
+
warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
|
|
1372
1473
|
let consumedStash;
|
|
1373
1474
|
try {
|
|
1374
1475
|
const preRecalled = request.userData?.__fetchBrainResult;
|
|
@@ -1389,13 +1490,13 @@ var FetchBrain = class {
|
|
|
1389
1490
|
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1390
1491
|
if (aiResult.fallback) {
|
|
1391
1492
|
throw new Error(
|
|
1392
|
-
`FetchBrain: ${
|
|
1493
|
+
`FetchBrain: ${shownUrl() ?? "a request"} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
|
|
1393
1494
|
);
|
|
1394
1495
|
}
|
|
1395
1496
|
runStats.dropped++;
|
|
1396
1497
|
request.noRetry = true;
|
|
1397
1498
|
throw new Error(
|
|
1398
|
-
`FetchBrain: ${
|
|
1499
|
+
`FetchBrain: ${shownUrl() ?? "a request"} skipped its fetch at enqueue time but its remembered data is no longer available \u2014 failing without retries; it will be re-scraped on a future run.`
|
|
1399
1500
|
);
|
|
1400
1501
|
}
|
|
1401
1502
|
let usedAIData = false;
|
|
@@ -1421,7 +1522,7 @@ var FetchBrain = class {
|
|
|
1421
1522
|
if (aiResult.known && aiResult.data && originalPushData) {
|
|
1422
1523
|
usedAIData = true;
|
|
1423
1524
|
await originalPushData.call(context, aiResult.data);
|
|
1424
|
-
logger.
|
|
1525
|
+
if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
|
|
1425
1526
|
await fireOnRecalled(aiResult.data);
|
|
1426
1527
|
}
|
|
1427
1528
|
}
|
|
@@ -1434,25 +1535,36 @@ var FetchBrain = class {
|
|
|
1434
1535
|
const handlerLabel = request.label;
|
|
1435
1536
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
1436
1537
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
1437
|
-
|
|
1438
|
-
runStats.aiSkipped++;
|
|
1439
|
-
logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
|
|
1538
|
+
if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
|
|
1440
1539
|
if (originalPushData) {
|
|
1441
1540
|
await originalPushData.call(context, aiResult.data);
|
|
1442
1541
|
}
|
|
1542
|
+
try {
|
|
1543
|
+
if (!request.userData?.__fetchBrainCounted) {
|
|
1544
|
+
request.userData = { ...request.userData, __fetchBrainCounted: true };
|
|
1545
|
+
runStats.recalled++;
|
|
1546
|
+
runStats.aiSkipped++;
|
|
1547
|
+
const skippedNav = request.skipNavigation === true;
|
|
1548
|
+
if (preRecalled?.known && skippedNav) {
|
|
1549
|
+
runStats.requestsSkipped++;
|
|
1550
|
+
} else if (!skippedNav) {
|
|
1551
|
+
runStats.lateRecalls++;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
} catch (countErr) {
|
|
1555
|
+
logger.debug(`Run stats skipped: ${countErr}`);
|
|
1556
|
+
}
|
|
1443
1557
|
await fireOnRecalled(aiResult.data);
|
|
1444
1558
|
return;
|
|
1445
1559
|
}
|
|
1446
|
-
runStats.scraped++;
|
|
1447
1560
|
const counts = labelCounts(request.label);
|
|
1448
1561
|
if (counts) counts.scraped++;
|
|
1449
1562
|
if (aiResult.known) {
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
logger.debug(`Learning: ${url}`);
|
|
1563
|
+
if (config.debug) {
|
|
1564
|
+
logger.debug(`Running handler [${handlerLabel || "default"}] with recalled data available${urlSuffix(shownUrl())}`);
|
|
1565
|
+
}
|
|
1566
|
+
} else if (config.debug) {
|
|
1567
|
+
logger.debug(`Learning${urlSuffix(shownUrl())}`);
|
|
1456
1568
|
}
|
|
1457
1569
|
const learnItems = [];
|
|
1458
1570
|
if (originalPushData && config.learning !== false) {
|
|
@@ -1479,6 +1591,15 @@ var FetchBrain = class {
|
|
|
1479
1591
|
if (counts) counts.failed++;
|
|
1480
1592
|
throw handlerErr;
|
|
1481
1593
|
}
|
|
1594
|
+
try {
|
|
1595
|
+
if (!request.userData?.__fetchBrainCounted) {
|
|
1596
|
+
request.userData = { ...request.userData, __fetchBrainCounted: true };
|
|
1597
|
+
runStats.scraped++;
|
|
1598
|
+
if (aiResult.known) runStats.recalled++;
|
|
1599
|
+
}
|
|
1600
|
+
} catch (countErr) {
|
|
1601
|
+
logger.debug(`Run stats skipped: ${countErr}`);
|
|
1602
|
+
}
|
|
1482
1603
|
if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
|
|
1483
1604
|
counts.empty++;
|
|
1484
1605
|
}
|
|
@@ -1576,7 +1697,17 @@ var FetchBrain = class {
|
|
|
1576
1697
|
runStats.startTime = Date.now();
|
|
1577
1698
|
const runStartedAt = new Date(runStats.startTime).toISOString();
|
|
1578
1699
|
labelStats.clear();
|
|
1579
|
-
const runBase = {
|
|
1700
|
+
const runBase = {
|
|
1701
|
+
totalRequests: runStats.totalRequests,
|
|
1702
|
+
bypassed: runStats.bypassed,
|
|
1703
|
+
dropped: runStats.dropped,
|
|
1704
|
+
scraped: runStats.scraped,
|
|
1705
|
+
learned: runStats.learned,
|
|
1706
|
+
recalled: runStats.recalled,
|
|
1707
|
+
aiSkipped: runStats.aiSkipped,
|
|
1708
|
+
requestsSkipped: runStats.requestsSkipped,
|
|
1709
|
+
lateRecalls: runStats.lateRecalls
|
|
1710
|
+
};
|
|
1580
1711
|
const changeBase = safeChangeStats(client);
|
|
1581
1712
|
const runId = nextRunId();
|
|
1582
1713
|
try {
|
|
@@ -1593,8 +1724,19 @@ var FetchBrain = class {
|
|
|
1593
1724
|
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1594
1725
|
1
|
|
1595
1726
|
);
|
|
1596
|
-
const
|
|
1597
|
-
|
|
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";
|
|
1598
1740
|
let changes = { changed: 0, drift: [] };
|
|
1599
1741
|
try {
|
|
1600
1742
|
const now = safeChangeStats(client);
|
|
@@ -1609,8 +1751,13 @@ var FetchBrain = class {
|
|
|
1609
1751
|
}
|
|
1610
1752
|
const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
|
|
1611
1753
|
logger.info(
|
|
1612
|
-
`\u{1F9E0} Finished! recalled: ${
|
|
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`
|
|
1613
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).`
|
|
1759
|
+
);
|
|
1760
|
+
}
|
|
1614
1761
|
for (const item of changes.drift) {
|
|
1615
1762
|
try {
|
|
1616
1763
|
logger.warn(describeDrift(item));
|
|
@@ -1626,9 +1773,12 @@ var FetchBrain = class {
|
|
|
1626
1773
|
build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
|
|
1627
1774
|
startedAt: runStartedAt,
|
|
1628
1775
|
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1629
|
-
scraped:
|
|
1630
|
-
learned:
|
|
1631
|
-
recalled:
|
|
1776
|
+
scraped: run.scraped,
|
|
1777
|
+
learned: run.learned,
|
|
1778
|
+
recalled: run.recalled,
|
|
1779
|
+
requestsSkipped: run.requestsSkipped,
|
|
1780
|
+
lateRecalls: run.lateRecalls,
|
|
1781
|
+
bypassed: run.bypassed,
|
|
1632
1782
|
labels
|
|
1633
1783
|
});
|
|
1634
1784
|
for (const flag of Array.isArray(flags) ? flags : []) {
|
|
@@ -1661,10 +1811,11 @@ var FetchBrain = class {
|
|
|
1661
1811
|
const r = slice[i];
|
|
1662
1812
|
if (!r || typeof r.url !== "string") continue;
|
|
1663
1813
|
const prior = r.userData?.__fetchBrainResult;
|
|
1664
|
-
if (prior) {
|
|
1665
|
-
if (prior
|
|
1814
|
+
if (prior || r.userData?.__fetchBrainCounted) {
|
|
1815
|
+
if (prior?.known && r.skipNavigation) r.skipNavigation = false;
|
|
1666
1816
|
const rest = { ...r.userData };
|
|
1667
1817
|
delete rest.__fetchBrainResult;
|
|
1818
|
+
delete rest.__fetchBrainCounted;
|
|
1668
1819
|
r.userData = rest;
|
|
1669
1820
|
}
|
|
1670
1821
|
if (r.skipNavigation) continue;
|