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