@fetchbrain.com/sdk 0.6.0 → 0.7.1
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 +42 -19
- package/dist/index.d.mts +36 -6
- package/dist/index.d.ts +36 -6
- package/dist/index.js +268 -63
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +268 -63
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +1 -1
- package/dist/mock/index.d.ts +1 -1
- package/dist/{types-B1MFygnZ.d.mts → types-CSG4BekA.d.mts} +13 -7
- package/dist/{types-B1MFygnZ.d.ts → types-CSG4BekA.d.ts} +13 -7
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -99,6 +99,8 @@ var CircuitBreaker = class {
|
|
|
99
99
|
};
|
|
100
100
|
|
|
101
101
|
// src/batch.ts
|
|
102
|
+
var MAX_CONCURRENT_LEARN_FLUSHES = 3;
|
|
103
|
+
var MAX_QUEUED_LEARNS = 500;
|
|
102
104
|
var DEFAULT_CONFIG2 = {
|
|
103
105
|
maxSize: 50,
|
|
104
106
|
maxWait: 50
|
|
@@ -180,6 +182,14 @@ var LearnBatcher = class {
|
|
|
180
182
|
constructor(executor, config = {}, logger) {
|
|
181
183
|
this.queue = [];
|
|
182
184
|
this.flushTimeout = null;
|
|
185
|
+
/** Flushes whose API call has not settled yet (awaited by forceFlush). */
|
|
186
|
+
this.inFlight = /* @__PURE__ */ new Set();
|
|
187
|
+
/**
|
|
188
|
+
* Callers of waitForRoom(), oldest first. A settling flush wakes only as many
|
|
189
|
+
* as there are free backlog slots: waking all of them would tell each one
|
|
190
|
+
* "room" when only some fit, and the rest would then be dropped.
|
|
191
|
+
*/
|
|
192
|
+
this.roomWaiters = [];
|
|
183
193
|
this.executor = executor;
|
|
184
194
|
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
185
195
|
this.logger = logger;
|
|
@@ -188,6 +198,10 @@ var LearnBatcher = class {
|
|
|
188
198
|
* Add a learn entry to the batch queue
|
|
189
199
|
*/
|
|
190
200
|
async learn(request, data) {
|
|
201
|
+
if (this.queue.length >= MAX_QUEUED_LEARNS) {
|
|
202
|
+
this.logger.debug("Learn backlog full; not learning this entry");
|
|
203
|
+
return { status: "rejected", learned: 0, errors: ["backlog_full"] };
|
|
204
|
+
}
|
|
191
205
|
return new Promise((resolve, reject) => {
|
|
192
206
|
this.queue.push({ entry: { request, data }, resolve, reject });
|
|
193
207
|
if (this.queue.length >= this.config.maxSize) {
|
|
@@ -199,10 +213,60 @@ var LearnBatcher = class {
|
|
|
199
213
|
}
|
|
200
214
|
});
|
|
201
215
|
}
|
|
216
|
+
/** True when another learn() would be dropped for lack of backlog room. */
|
|
217
|
+
isBacklogFull() {
|
|
218
|
+
return this.queue.length >= MAX_QUEUED_LEARNS;
|
|
219
|
+
}
|
|
202
220
|
/**
|
|
203
|
-
*
|
|
221
|
+
* Wait until the backlog has room, at most `timeoutMs`. Resolves true when
|
|
222
|
+
* there is room. Bounded so a slow API slows the crawl but never stalls it.
|
|
204
223
|
*/
|
|
205
|
-
async
|
|
224
|
+
async waitForRoom(timeoutMs) {
|
|
225
|
+
const deadline = Date.now() + timeoutMs;
|
|
226
|
+
while (this.isBacklogFull()) {
|
|
227
|
+
const remaining = deadline - Date.now();
|
|
228
|
+
if (remaining <= 0) return false;
|
|
229
|
+
await new Promise((resolve) => {
|
|
230
|
+
const wake = () => {
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
resolve();
|
|
233
|
+
};
|
|
234
|
+
const timer = setTimeout(() => {
|
|
235
|
+
const i = this.roomWaiters.indexOf(wake);
|
|
236
|
+
if (i !== -1) this.roomWaiters.splice(i, 1);
|
|
237
|
+
resolve();
|
|
238
|
+
}, remaining);
|
|
239
|
+
this.roomWaiters.push(wake);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Start sending the next batch, unless MAX_CONCURRENT_LEARN_FLUSHES are
|
|
246
|
+
* already in flight — a settling flush starts the next one.
|
|
247
|
+
*/
|
|
248
|
+
flush() {
|
|
249
|
+
if (this.inFlight.size >= MAX_CONCURRENT_LEARN_FLUSHES) {
|
|
250
|
+
if (this.flushTimeout) {
|
|
251
|
+
clearTimeout(this.flushTimeout);
|
|
252
|
+
this.flushTimeout = null;
|
|
253
|
+
}
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const run = this.flushOnce();
|
|
257
|
+
this.inFlight.add(run);
|
|
258
|
+
void run.finally(() => {
|
|
259
|
+
this.inFlight.delete(run);
|
|
260
|
+
if (this.queue.length >= this.config.maxSize) {
|
|
261
|
+
this.flush();
|
|
262
|
+
} else if (this.queue.length > 0 && !this.flushTimeout) {
|
|
263
|
+
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
264
|
+
}
|
|
265
|
+
const free = MAX_QUEUED_LEARNS - this.queue.length;
|
|
266
|
+
for (const wake of this.roomWaiters.splice(0, Math.max(0, free))) wake();
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
async flushOnce() {
|
|
206
270
|
if (this.flushTimeout) {
|
|
207
271
|
clearTimeout(this.flushTimeout);
|
|
208
272
|
this.flushTimeout = null;
|
|
@@ -223,16 +287,14 @@ var LearnBatcher = class {
|
|
|
223
287
|
r.reject(error);
|
|
224
288
|
}
|
|
225
289
|
}
|
|
226
|
-
if (this.queue.length > 0) {
|
|
227
|
-
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
228
|
-
}
|
|
229
290
|
}
|
|
230
291
|
/**
|
|
231
292
|
* Force flush and wait for completion (for cleanup/shutdown)
|
|
232
293
|
*/
|
|
233
294
|
async forceFlush() {
|
|
234
|
-
|
|
235
|
-
|
|
295
|
+
while (this.queue.length > 0 || this.inFlight.size > 0) {
|
|
296
|
+
if (this.queue.length > 0) this.flush();
|
|
297
|
+
await Promise.allSettled([...this.inFlight]);
|
|
236
298
|
}
|
|
237
299
|
}
|
|
238
300
|
/**
|
|
@@ -366,12 +428,17 @@ function getPlatformBuildId(env = process.env) {
|
|
|
366
428
|
|
|
367
429
|
// src/client.ts
|
|
368
430
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
369
|
-
var DEFAULT_TIMEOUT =
|
|
431
|
+
var DEFAULT_TIMEOUT = 1500;
|
|
370
432
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
371
433
|
var BULK_RECALL_TIMEOUT = 3e3;
|
|
372
|
-
var MAX_BULK_ITEMS =
|
|
434
|
+
var MAX_BULK_ITEMS = 90;
|
|
435
|
+
var KEY_REJECTED_PAUSE_MS = 6e4;
|
|
373
436
|
var BULK_RECALL_CONCURRENCY = 5;
|
|
374
437
|
var MAX_LEARN_ENTRIES = 50;
|
|
438
|
+
var MAX_LEARN_DATA_BYTES = 100 * 1024;
|
|
439
|
+
function isOutage(error) {
|
|
440
|
+
return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
|
|
441
|
+
}
|
|
375
442
|
var ASK_TIMEOUT = 1e4;
|
|
376
443
|
function clampBatch(batch, cap) {
|
|
377
444
|
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
@@ -409,6 +476,16 @@ var FetchBrainClient = class {
|
|
|
409
476
|
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
410
477
|
*/
|
|
411
478
|
this.learnPausedUntil = 0;
|
|
479
|
+
/**
|
|
480
|
+
* Set by a 401 (key invalid or revoked): calls answer locally until then
|
|
481
|
+
* instead of each paying a failing round-trip. A pause, not a permanent stop:
|
|
482
|
+
* a key used right after it is created can see a brief 401 while the key
|
|
483
|
+
* propagates, and that must not switch FetchBrain off for a whole run.
|
|
484
|
+
*/
|
|
485
|
+
this.keyRejectedUntil = 0;
|
|
486
|
+
this.keyRejectedWarned = false;
|
|
487
|
+
/** The oversized-page warning is shown once per client, then logged at debug. */
|
|
488
|
+
this.warnedOversizeLearn = false;
|
|
412
489
|
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
413
490
|
this.learnCapWarnedUntil = 0;
|
|
414
491
|
this.config = {
|
|
@@ -457,11 +534,35 @@ var FetchBrainClient = class {
|
|
|
457
534
|
this.logger
|
|
458
535
|
);
|
|
459
536
|
}
|
|
537
|
+
/** True when recalls must not reach the API right now (crawl continues without). */
|
|
538
|
+
recallBlocked() {
|
|
539
|
+
return this.isKeyRejected() || this.circuitBreaker.isOpen();
|
|
540
|
+
}
|
|
541
|
+
isKeyRejected() {
|
|
542
|
+
return Date.now() < this.keyRejectedUntil;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* React to a 4xx the API returned. These are not outages (they don't open the
|
|
546
|
+
* shared breaker). A 401 means the next calls would fail the same way, so all
|
|
547
|
+
* calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
|
|
548
|
+
* pause recalls locally: a locally refused handler-time recall fails a
|
|
549
|
+
* fetch-skipped request, whereas the API's own answer can still succeed.)
|
|
550
|
+
*/
|
|
551
|
+
noteRefusal(error) {
|
|
552
|
+
if (!(error instanceof ApiError) || error.status !== 401) return;
|
|
553
|
+
this.keyRejectedUntil = Date.now() + KEY_REJECTED_PAUSE_MS;
|
|
554
|
+
if (!this.keyRejectedWarned) {
|
|
555
|
+
this.keyRejectedWarned = true;
|
|
556
|
+
this.logger.warn(
|
|
557
|
+
"FetchBrain API key was rejected (401: invalid or revoked). FetchBrain pauses for 60s at a time while it is; the crawl continues without it."
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
460
561
|
/**
|
|
461
562
|
* Recall if FetchBrain "knows" a request
|
|
462
563
|
*/
|
|
463
564
|
async recall(request) {
|
|
464
|
-
if (this.
|
|
565
|
+
if (this.recallBlocked()) {
|
|
465
566
|
return { known: false, fallback: true };
|
|
466
567
|
}
|
|
467
568
|
try {
|
|
@@ -473,7 +574,7 @@ var FetchBrainClient = class {
|
|
|
473
574
|
}
|
|
474
575
|
/**
|
|
475
576
|
* Recall multiple requests at once — returns ordered array matching input order.
|
|
476
|
-
* Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
|
|
577
|
+
* Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
|
|
477
578
|
* failed chunk degrades to fallback results for its own items only.
|
|
478
579
|
*/
|
|
479
580
|
async recallBulk(requests) {
|
|
@@ -487,7 +588,7 @@ var FetchBrainClient = class {
|
|
|
487
588
|
while (next < chunks.length) {
|
|
488
589
|
const idx = next++;
|
|
489
590
|
const chunk = chunks[idx];
|
|
490
|
-
if (this.
|
|
591
|
+
if (this.recallBlocked()) {
|
|
491
592
|
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
492
593
|
continue;
|
|
493
594
|
}
|
|
@@ -512,11 +613,19 @@ var FetchBrainClient = class {
|
|
|
512
613
|
if (!this.config.learning) {
|
|
513
614
|
return { status: "rejected", learned: 0 };
|
|
514
615
|
}
|
|
515
|
-
if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
616
|
+
if (this.isKeyRejected() || Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
516
617
|
return { status: "rejected", learned: 0 };
|
|
517
618
|
}
|
|
619
|
+
const processed = this.extractForLearning(data);
|
|
620
|
+
if (JSON.stringify(processed).length > MAX_LEARN_DATA_BYTES) {
|
|
621
|
+
const message = `A page's data is over the ${MAX_LEARN_DATA_BYTES / 1024}KB learn limit, so it was not learned and will be fetched again on later runs. Use extractForLearning to keep only the fields you need.`;
|
|
622
|
+
if (this.warnedOversizeLearn) this.logger.debug(message);
|
|
623
|
+
else this.logger.warn(message);
|
|
624
|
+
this.warnedOversizeLearn = true;
|
|
625
|
+
return { status: "rejected", learned: 0, errors: ["too_large"] };
|
|
626
|
+
}
|
|
518
627
|
try {
|
|
519
|
-
return await this.learnBatcher.learn(request,
|
|
628
|
+
return await this.learnBatcher.learn(request, processed);
|
|
520
629
|
} catch (error) {
|
|
521
630
|
if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
|
|
522
631
|
return { status: "rejected", learned: 0 };
|
|
@@ -539,7 +648,7 @@ var FetchBrainClient = class {
|
|
|
539
648
|
this.circuitBreaker.recordSuccess();
|
|
540
649
|
return response;
|
|
541
650
|
} catch (error) {
|
|
542
|
-
this.circuitBreaker.recordFailure();
|
|
651
|
+
if (isOutage(error)) this.circuitBreaker.recordFailure();
|
|
543
652
|
this.logger.warn("Stats request failed:", error);
|
|
544
653
|
return null;
|
|
545
654
|
}
|
|
@@ -622,19 +731,23 @@ var FetchBrainClient = class {
|
|
|
622
731
|
}
|
|
623
732
|
return results;
|
|
624
733
|
} catch (error) {
|
|
625
|
-
this.circuitBreaker.recordFailure();
|
|
734
|
+
if (isOutage(error)) this.circuitBreaker.recordFailure();
|
|
735
|
+
else this.noteRefusal(error);
|
|
626
736
|
throw error;
|
|
627
737
|
}
|
|
628
738
|
}
|
|
739
|
+
/** Apply the user's extractForLearning hook to each learned record. */
|
|
740
|
+
extractForLearning(data) {
|
|
741
|
+
const extract = this.config.extractForLearning;
|
|
742
|
+
if (!extract) return data;
|
|
743
|
+
return Array.isArray(data) ? data.map((d) => extract(d)) : extract(data);
|
|
744
|
+
}
|
|
629
745
|
/**
|
|
630
746
|
* Execute a batch learn against the API
|
|
631
747
|
*/
|
|
632
748
|
async executeBatchLearn(entries) {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
|
|
636
|
-
}));
|
|
637
|
-
const request = { entries: processed };
|
|
749
|
+
if (entries.length === 0) return { status: "rejected", learned: 0 };
|
|
750
|
+
const request = { entries };
|
|
638
751
|
const platformBuildId = getPlatformBuildId();
|
|
639
752
|
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
640
753
|
request.build = platformBuildId;
|
|
@@ -652,6 +765,7 @@ var FetchBrainClient = class {
|
|
|
652
765
|
return response;
|
|
653
766
|
} catch (error) {
|
|
654
767
|
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
768
|
+
this.noteRefusal(error);
|
|
655
769
|
if (error.code === "LEARN_CAP_EXCEEDED") {
|
|
656
770
|
const now = /* @__PURE__ */ new Date();
|
|
657
771
|
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
@@ -763,6 +877,13 @@ var FetchBrainClient = class {
|
|
|
763
877
|
/**
|
|
764
878
|
* Flush pending learn requests (call before shutdown)
|
|
765
879
|
*/
|
|
880
|
+
/**
|
|
881
|
+
* Wait (at most `timeoutMs`) until the background learn backlog has room.
|
|
882
|
+
* Lets the crawler slow to the API's pace instead of queueing without limit.
|
|
883
|
+
*/
|
|
884
|
+
async waitForLearnRoom(timeoutMs) {
|
|
885
|
+
return this.learnBatcher.waitForRoom(timeoutMs);
|
|
886
|
+
}
|
|
766
887
|
async flushLearnBatch() {
|
|
767
888
|
await this.learnBatcher.forceFlush();
|
|
768
889
|
}
|
|
@@ -927,6 +1048,7 @@ var TelemetryBuffer = class {
|
|
|
927
1048
|
this.flushTimer = setInterval(() => {
|
|
928
1049
|
this.flush();
|
|
929
1050
|
}, this.flushInterval);
|
|
1051
|
+
this.flushTimer.unref?.();
|
|
930
1052
|
}
|
|
931
1053
|
/**
|
|
932
1054
|
* Stop the flush timer and flush remaining entries
|
|
@@ -943,6 +1065,23 @@ var TelemetryBuffer = class {
|
|
|
943
1065
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
944
1066
|
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
945
1067
|
var MAX_STASH_ENTRIES = 5e3;
|
|
1068
|
+
var MAX_STASH_BYTES = 256 * 1024 * 1024;
|
|
1069
|
+
var stashBytesCap = MAX_STASH_BYTES;
|
|
1070
|
+
var PRE_RECALL_SLICE = 500;
|
|
1071
|
+
var PRE_RECALL_STASH_WAIT_MS = 3e4;
|
|
1072
|
+
var LEARN_ROOM_WAIT_MS = 5e3;
|
|
1073
|
+
function isIterableInputRejection(err) {
|
|
1074
|
+
if (err instanceof TypeError) return true;
|
|
1075
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1076
|
+
return /iterable|\barray\b/i.test(message);
|
|
1077
|
+
}
|
|
1078
|
+
function resolveHandlerKey(crawler) {
|
|
1079
|
+
const c = crawler;
|
|
1080
|
+
for (const key of ["userProvidedRequestHandler", "requestHandler", "userDefinedRequestHandler"]) {
|
|
1081
|
+
if (typeof c[key] === "function") return key;
|
|
1082
|
+
}
|
|
1083
|
+
return null;
|
|
1084
|
+
}
|
|
946
1085
|
function buildRawRequest(request) {
|
|
947
1086
|
const r = request;
|
|
948
1087
|
let headers;
|
|
@@ -1052,7 +1191,15 @@ var FetchBrain = class {
|
|
|
1052
1191
|
// enqueue-time fetch skipped, but remembered data gone by execution
|
|
1053
1192
|
startTime: 0
|
|
1054
1193
|
};
|
|
1055
|
-
const
|
|
1194
|
+
const pendingLearns = /* @__PURE__ */ new Set();
|
|
1195
|
+
if ("adaptiveRequestHandler" in crawler) {
|
|
1196
|
+
logger.warn(
|
|
1197
|
+
"AdaptivePlaywrightCrawler is not supported yet \u2014 FetchBrain left this crawler unmodified"
|
|
1198
|
+
);
|
|
1199
|
+
return Object.assign(crawler, { fetchBrain: client });
|
|
1200
|
+
}
|
|
1201
|
+
const handlerKey = resolveHandlerKey(crawler);
|
|
1202
|
+
const originalHandler = handlerKey ? crawler[handlerKey] : void 0;
|
|
1056
1203
|
if (!originalHandler) {
|
|
1057
1204
|
logger.warn("No request handler found on crawler, returning unmodified");
|
|
1058
1205
|
return Object.assign(crawler, { fetchBrain: client });
|
|
@@ -1060,26 +1207,40 @@ var FetchBrain = class {
|
|
|
1060
1207
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
1061
1208
|
const warnedKeys = /* @__PURE__ */ new Set();
|
|
1062
1209
|
const preRecalledData = /* @__PURE__ */ new Map();
|
|
1210
|
+
let stashBytes = 0;
|
|
1211
|
+
let crawlStarted = false;
|
|
1212
|
+
const stashDelete = (key) => {
|
|
1213
|
+
const entry = preRecalledData.get(key);
|
|
1214
|
+
if (!entry) return false;
|
|
1215
|
+
preRecalledData.delete(key);
|
|
1216
|
+
stashBytes -= entry.bytes;
|
|
1217
|
+
return true;
|
|
1218
|
+
};
|
|
1063
1219
|
const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
|
|
1064
1220
|
const stashSet = (key, data) => {
|
|
1065
|
-
|
|
1221
|
+
const reStash = stashDelete(key);
|
|
1222
|
+
const bytes = JSON.stringify(data).length;
|
|
1223
|
+
while (preRecalledData.size > 0 && (!reStash && preRecalledData.size >= MAX_STASH_ENTRIES || stashBytes + bytes > stashBytesCap)) {
|
|
1066
1224
|
const oldest = preRecalledData.keys().next().value;
|
|
1067
|
-
if (oldest
|
|
1225
|
+
if (oldest === void 0) break;
|
|
1226
|
+
stashDelete(oldest);
|
|
1068
1227
|
}
|
|
1069
|
-
preRecalledData.set(key, data);
|
|
1228
|
+
preRecalledData.set(key, { data, bytes });
|
|
1229
|
+
stashBytes += bytes;
|
|
1070
1230
|
};
|
|
1071
1231
|
const stashTake = (r) => {
|
|
1072
1232
|
for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
|
|
1073
|
-
const
|
|
1074
|
-
if (
|
|
1075
|
-
|
|
1076
|
-
return data;
|
|
1233
|
+
const entry = preRecalledData.get(key);
|
|
1234
|
+
if (entry) {
|
|
1235
|
+
stashDelete(key);
|
|
1236
|
+
return entry.data;
|
|
1077
1237
|
}
|
|
1078
1238
|
}
|
|
1079
1239
|
return void 0;
|
|
1080
1240
|
};
|
|
1081
1241
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
1082
1242
|
const wrappedHandler = async (context) => {
|
|
1243
|
+
crawlStarted = true;
|
|
1083
1244
|
const { request } = context;
|
|
1084
1245
|
const url = request.url;
|
|
1085
1246
|
const label = request.label;
|
|
@@ -1180,12 +1341,11 @@ var FetchBrain = class {
|
|
|
1180
1341
|
} else {
|
|
1181
1342
|
logger.debug(`Learning: ${url}`);
|
|
1182
1343
|
}
|
|
1344
|
+
const learnItems = [];
|
|
1183
1345
|
if (originalPushData && config.learning !== false) {
|
|
1184
1346
|
context.pushData = async (data) => {
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
runStats.learned++;
|
|
1188
|
-
await client.learn(rawRequest, data);
|
|
1347
|
+
if (!usedAIData && !aiResult.known) {
|
|
1348
|
+
learnItems.push(...Array.isArray(data) ? data : [data]);
|
|
1189
1349
|
}
|
|
1190
1350
|
return originalPushData.call(context, data);
|
|
1191
1351
|
};
|
|
@@ -1194,11 +1354,20 @@ var FetchBrain = class {
|
|
|
1194
1354
|
request: rawRequest,
|
|
1195
1355
|
client,
|
|
1196
1356
|
learning: config.learning !== false,
|
|
1197
|
-
aiKnown: aiResult.known
|
|
1357
|
+
aiKnown: aiResult.known,
|
|
1358
|
+
items: learnItems
|
|
1198
1359
|
};
|
|
1199
1360
|
await asyncContext.run(requestContext, async () => {
|
|
1200
1361
|
await originalHandler.call(crawler, context);
|
|
1201
1362
|
});
|
|
1363
|
+
if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
|
|
1364
|
+
await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
|
|
1365
|
+
const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
|
|
1366
|
+
if (res.status !== "rejected") runStats.learned += learnItems.length;
|
|
1367
|
+
}).catch((learnErr) => logger.debug(`Learn failed: ${learnErr}`));
|
|
1368
|
+
pendingLearns.add(pending);
|
|
1369
|
+
void pending.finally(() => pendingLearns.delete(pending));
|
|
1370
|
+
}
|
|
1202
1371
|
if (telemetryConfig.enabled) {
|
|
1203
1372
|
try {
|
|
1204
1373
|
const telemetry = await collectTelemetry(
|
|
@@ -1277,12 +1446,8 @@ var FetchBrain = class {
|
|
|
1277
1446
|
}
|
|
1278
1447
|
};
|
|
1279
1448
|
const crawlerAny = crawler;
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
}
|
|
1283
|
-
if ("userDefinedRequestHandler" in crawlerAny) {
|
|
1284
|
-
crawlerAny.userDefinedRequestHandler = wrappedHandler;
|
|
1285
|
-
}
|
|
1449
|
+
crawlerAny[handlerKey] = wrappedHandler;
|
|
1450
|
+
logger.debug(`Wrapped ${handlerKey}`);
|
|
1286
1451
|
if (typeof crawlerAny.run === "function") {
|
|
1287
1452
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
1288
1453
|
crawlerAny.run = async (...args) => {
|
|
@@ -1293,6 +1458,7 @@ var FetchBrain = class {
|
|
|
1293
1458
|
} finally {
|
|
1294
1459
|
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1295
1460
|
await client.flushLearnBatch();
|
|
1461
|
+
await Promise.allSettled([...pendingLearns]);
|
|
1296
1462
|
if (telemetryConfig.enabled) {
|
|
1297
1463
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
1298
1464
|
await telemetryBuffer.stop();
|
|
@@ -1315,24 +1481,11 @@ var FetchBrain = class {
|
|
|
1315
1481
|
"preRecall: this crawler uses retryOnBlocked, whose blocked-check needs a fetched response \u2014 known requests will keep their fetch; recalled data still replaces the handler."
|
|
1316
1482
|
);
|
|
1317
1483
|
}
|
|
1318
|
-
|
|
1319
|
-
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1320
|
-
return originalAddRequests(requests, options);
|
|
1321
|
-
}
|
|
1322
|
-
const retryOnBlocked = Boolean(
|
|
1323
|
-
crawlerAny.retryOnBlocked
|
|
1324
|
-
);
|
|
1325
|
-
const batch = requests.map((r) => {
|
|
1326
|
-
if (typeof r === "string") return { url: r };
|
|
1327
|
-
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1328
|
-
return { ...r };
|
|
1329
|
-
}
|
|
1330
|
-
return r;
|
|
1331
|
-
});
|
|
1484
|
+
const preRecallSlice = async (slice, retryOnBlocked) => {
|
|
1332
1485
|
try {
|
|
1333
1486
|
const candidateIdx = [];
|
|
1334
|
-
for (let i = 0; i <
|
|
1335
|
-
const r =
|
|
1487
|
+
for (let i = 0; i < slice.length; i++) {
|
|
1488
|
+
const r = slice[i];
|
|
1336
1489
|
if (!r || typeof r.url !== "string") continue;
|
|
1337
1490
|
const prior = r.userData?.__fetchBrainResult;
|
|
1338
1491
|
if (prior) {
|
|
@@ -1348,14 +1501,14 @@ var FetchBrain = class {
|
|
|
1348
1501
|
}
|
|
1349
1502
|
if (candidateIdx.length > 0) {
|
|
1350
1503
|
const rawRequests = candidateIdx.map(
|
|
1351
|
-
(i) => buildRawRequest(
|
|
1504
|
+
(i) => buildRawRequest(slice[i])
|
|
1352
1505
|
);
|
|
1353
1506
|
const results = await client.recallBulk(rawRequests);
|
|
1354
1507
|
let known = 0;
|
|
1355
1508
|
candidateIdx.forEach((reqIdx, j) => {
|
|
1356
1509
|
const result = results[j];
|
|
1357
1510
|
if (!result || result.fallback) return;
|
|
1358
|
-
const r =
|
|
1511
|
+
const r = slice[reqIdx];
|
|
1359
1512
|
if (result.known && result.data) {
|
|
1360
1513
|
r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
|
|
1361
1514
|
stashSet(stashKey(rawRequests[j]), result.data);
|
|
@@ -1374,7 +1527,62 @@ var FetchBrain = class {
|
|
|
1374
1527
|
} catch (err) {
|
|
1375
1528
|
logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
|
|
1376
1529
|
}
|
|
1377
|
-
|
|
1530
|
+
};
|
|
1531
|
+
const waitForStashRoom = async (needed, state) => {
|
|
1532
|
+
if (!crawlStarted) return;
|
|
1533
|
+
const deadline = Date.now() + PRE_RECALL_STASH_WAIT_MS;
|
|
1534
|
+
const hasRoom = () => preRecalledData.size + needed <= MAX_STASH_ENTRIES && stashBytes < stashBytesCap;
|
|
1535
|
+
while (!state.gaveUp && !hasRoom()) {
|
|
1536
|
+
if (Date.now() >= deadline) {
|
|
1537
|
+
state.gaveUp = true;
|
|
1538
|
+
logger.debug("preRecall: stash still full after waiting; continuing (oldest payloads may be evicted)");
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
crawlerAny.addRequests = async (requests, options) => {
|
|
1545
|
+
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1546
|
+
return originalAddRequests(requests, options);
|
|
1547
|
+
}
|
|
1548
|
+
const retryOnBlocked = Boolean(
|
|
1549
|
+
crawlerAny.retryOnBlocked
|
|
1550
|
+
);
|
|
1551
|
+
const batch = requests.map((r) => {
|
|
1552
|
+
if (typeof r === "string") return { url: r };
|
|
1553
|
+
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1554
|
+
return { ...r };
|
|
1555
|
+
}
|
|
1556
|
+
return r;
|
|
1557
|
+
});
|
|
1558
|
+
if (batch.length <= PRE_RECALL_SLICE) {
|
|
1559
|
+
await preRecallSlice(batch, retryOnBlocked);
|
|
1560
|
+
return originalAddRequests(batch, options);
|
|
1561
|
+
}
|
|
1562
|
+
const state = { gaveUp: false };
|
|
1563
|
+
let started = false;
|
|
1564
|
+
async function* lazilyRecalled() {
|
|
1565
|
+
started = true;
|
|
1566
|
+
for (let i = 0; i < batch.length; i += PRE_RECALL_SLICE) {
|
|
1567
|
+
const slice = batch.slice(i, i + PRE_RECALL_SLICE);
|
|
1568
|
+
await waitForStashRoom(slice.length, state);
|
|
1569
|
+
await preRecallSlice(slice, retryOnBlocked);
|
|
1570
|
+
yield* slice;
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
try {
|
|
1574
|
+
return await originalAddRequests(lazilyRecalled(), options);
|
|
1575
|
+
} catch (err) {
|
|
1576
|
+
if (started || !isIterableInputRejection(err)) throw err;
|
|
1577
|
+
logger.debug(
|
|
1578
|
+
"preRecall: this Crawlee version does not accept lazy request lists; pre-recalling eagerly"
|
|
1579
|
+
);
|
|
1580
|
+
const eager = batch.slice(0, MAX_STASH_ENTRIES);
|
|
1581
|
+
for (let i = 0; i < eager.length && stashBytes < stashBytesCap; i += PRE_RECALL_SLICE) {
|
|
1582
|
+
await preRecallSlice(eager.slice(i, i + PRE_RECALL_SLICE), retryOnBlocked);
|
|
1583
|
+
}
|
|
1584
|
+
return originalAddRequests(batch, options);
|
|
1585
|
+
}
|
|
1378
1586
|
};
|
|
1379
1587
|
}
|
|
1380
1588
|
return Object.assign(crawler, { fetchBrain: client });
|
|
@@ -1386,10 +1594,7 @@ function createFetchBrain(config) {
|
|
|
1386
1594
|
async function pushData(data, dataset, datasetName) {
|
|
1387
1595
|
const ctx = getCurrentContext();
|
|
1388
1596
|
if (ctx && ctx.learning && !ctx.aiKnown) {
|
|
1389
|
-
|
|
1390
|
-
for (const item of items) {
|
|
1391
|
-
await ctx.client.learn(ctx.request, item);
|
|
1392
|
-
}
|
|
1597
|
+
ctx.items.push(...Array.isArray(data) ? data : [data]);
|
|
1393
1598
|
}
|
|
1394
1599
|
if (datasetName && dataset.open) {
|
|
1395
1600
|
const namedDataset = await dataset.open(datasetName);
|