@fetchbrain.com/sdk 0.5.1 → 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 +73 -23
- package/dist/index.d.mts +38 -6
- package/dist/index.d.ts +38 -6
- package/dist/index.js +289 -64
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +289 -64
- 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-BMwfPE5J.d.mts → types-CSG4BekA.d.mts} +22 -7
- package/dist/{types-BMwfPE5J.d.ts → types-CSG4BekA.d.ts} +22 -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
|
/**
|
|
@@ -321,16 +383,38 @@ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
|
|
|
321
383
|
var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
|
|
322
384
|
var MAX_VALUE_LENGTH = 256;
|
|
323
385
|
var MAX_HEADER_LENGTH = 2048;
|
|
324
|
-
|
|
386
|
+
var SCRAPER_NAME_VAR = "FETCHBRAIN_SCRAPER_ID";
|
|
387
|
+
var SCRAPER_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
388
|
+
function normalizeScraperName(raw) {
|
|
389
|
+
const name = raw?.trim().toLowerCase();
|
|
390
|
+
return name && SCRAPER_NAME.test(name) ? name : void 0;
|
|
391
|
+
}
|
|
392
|
+
function resolveScraperName(option, env = process.env) {
|
|
393
|
+
const rejected = [];
|
|
394
|
+
const candidates = [
|
|
395
|
+
["option", option],
|
|
396
|
+
[SCRAPER_NAME_VAR, env[SCRAPER_NAME_VAR]]
|
|
397
|
+
];
|
|
398
|
+
for (const [source, raw] of candidates) {
|
|
399
|
+
if (raw === void 0 || raw.trim() === "") continue;
|
|
400
|
+
const name = normalizeScraperName(raw);
|
|
401
|
+
if (name) return { name, rejected };
|
|
402
|
+
rejected.push(source);
|
|
403
|
+
}
|
|
404
|
+
return { rejected };
|
|
405
|
+
}
|
|
406
|
+
function buildNativeContext(env = process.env, scraper) {
|
|
325
407
|
const context = {};
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
408
|
+
const name = normalizeScraperName(scraper);
|
|
409
|
+
if (name) context[SCRAPER_NAME_VAR] = name;
|
|
410
|
+
const names = Object.keys(env).filter((n) => n !== SCRAPER_NAME_VAR && ALLOWED_NAME.test(n) && !DENYLIST.test(n)).sort();
|
|
411
|
+
for (const varName of names) {
|
|
412
|
+
const value = env[varName];
|
|
329
413
|
if (!value || value.length > MAX_VALUE_LENGTH) continue;
|
|
330
414
|
if (CREDENTIAL_VALUE.test(value)) continue;
|
|
331
|
-
const candidate = { ...context, [
|
|
415
|
+
const candidate = { ...context, [varName]: value };
|
|
332
416
|
if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
|
|
333
|
-
context[
|
|
417
|
+
context[varName] = value;
|
|
334
418
|
}
|
|
335
419
|
if (Object.keys(context).length === 0) return void 0;
|
|
336
420
|
return JSON.stringify(context);
|
|
@@ -342,12 +426,17 @@ function getPlatformBuildId(env = process.env) {
|
|
|
342
426
|
|
|
343
427
|
// src/client.ts
|
|
344
428
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
345
|
-
var DEFAULT_TIMEOUT =
|
|
429
|
+
var DEFAULT_TIMEOUT = 1500;
|
|
346
430
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
347
431
|
var BULK_RECALL_TIMEOUT = 3e3;
|
|
348
|
-
var MAX_BULK_ITEMS =
|
|
432
|
+
var MAX_BULK_ITEMS = 90;
|
|
433
|
+
var KEY_REJECTED_PAUSE_MS = 6e4;
|
|
349
434
|
var BULK_RECALL_CONCURRENCY = 5;
|
|
350
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
|
+
}
|
|
351
440
|
var ASK_TIMEOUT = 1e4;
|
|
352
441
|
function clampBatch(batch, cap) {
|
|
353
442
|
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
@@ -385,6 +474,16 @@ var FetchBrainClient = class {
|
|
|
385
474
|
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
386
475
|
*/
|
|
387
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;
|
|
388
487
|
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
389
488
|
this.learnCapWarnedUntil = 0;
|
|
390
489
|
this.config = {
|
|
@@ -406,10 +505,18 @@ var FetchBrainClient = class {
|
|
|
406
505
|
// enhance-only; stored so getConfig() round-trips
|
|
407
506
|
preRecall: config.preRecall,
|
|
408
507
|
// enhance-only; stored so getConfig() round-trips
|
|
409
|
-
onRecalled: config.onRecalled
|
|
508
|
+
onRecalled: config.onRecalled,
|
|
410
509
|
// enhance-only; stored so getConfig() round-trips
|
|
510
|
+
scraper: config.scraper
|
|
411
511
|
};
|
|
412
512
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
513
|
+
const scraper = resolveScraperName(config.scraper);
|
|
514
|
+
this.scraperName = scraper.name;
|
|
515
|
+
for (const source of scraper.rejected) {
|
|
516
|
+
this.logger.warn(
|
|
517
|
+
`ignoring invalid scraper name from ${source === "option" ? "the scraper option" : source}; use 1-64 lowercase letters, digits, '.', '_' or '-', starting with a letter or digit. ` + (scraper.name ? `Using "${scraper.name}" instead.` : "This scraper uses the shared default memory.")
|
|
518
|
+
);
|
|
519
|
+
}
|
|
413
520
|
this.circuitBreaker = new CircuitBreaker(
|
|
414
521
|
this.config.circuitBreaker,
|
|
415
522
|
this.logger
|
|
@@ -425,11 +532,35 @@ var FetchBrainClient = class {
|
|
|
425
532
|
this.logger
|
|
426
533
|
);
|
|
427
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
|
+
}
|
|
428
559
|
/**
|
|
429
560
|
* Recall if FetchBrain "knows" a request
|
|
430
561
|
*/
|
|
431
562
|
async recall(request) {
|
|
432
|
-
if (this.
|
|
563
|
+
if (this.recallBlocked()) {
|
|
433
564
|
return { known: false, fallback: true };
|
|
434
565
|
}
|
|
435
566
|
try {
|
|
@@ -441,7 +572,7 @@ var FetchBrainClient = class {
|
|
|
441
572
|
}
|
|
442
573
|
/**
|
|
443
574
|
* Recall multiple requests at once — returns ordered array matching input order.
|
|
444
|
-
* 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
|
|
445
576
|
* failed chunk degrades to fallback results for its own items only.
|
|
446
577
|
*/
|
|
447
578
|
async recallBulk(requests) {
|
|
@@ -455,7 +586,7 @@ var FetchBrainClient = class {
|
|
|
455
586
|
while (next < chunks.length) {
|
|
456
587
|
const idx = next++;
|
|
457
588
|
const chunk = chunks[idx];
|
|
458
|
-
if (this.
|
|
589
|
+
if (this.recallBlocked()) {
|
|
459
590
|
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
460
591
|
continue;
|
|
461
592
|
}
|
|
@@ -480,11 +611,19 @@ var FetchBrainClient = class {
|
|
|
480
611
|
if (!this.config.learning) {
|
|
481
612
|
return { status: "rejected", learned: 0 };
|
|
482
613
|
}
|
|
483
|
-
if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
614
|
+
if (this.isKeyRejected() || Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
484
615
|
return { status: "rejected", learned: 0 };
|
|
485
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
|
+
}
|
|
486
625
|
try {
|
|
487
|
-
return await this.learnBatcher.learn(request,
|
|
626
|
+
return await this.learnBatcher.learn(request, processed);
|
|
488
627
|
} catch (error) {
|
|
489
628
|
if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
|
|
490
629
|
return { status: "rejected", learned: 0 };
|
|
@@ -507,7 +646,7 @@ var FetchBrainClient = class {
|
|
|
507
646
|
this.circuitBreaker.recordSuccess();
|
|
508
647
|
return response;
|
|
509
648
|
} catch (error) {
|
|
510
|
-
this.circuitBreaker.recordFailure();
|
|
649
|
+
if (isOutage(error)) this.circuitBreaker.recordFailure();
|
|
511
650
|
this.logger.warn("Stats request failed:", error);
|
|
512
651
|
return null;
|
|
513
652
|
}
|
|
@@ -590,19 +729,23 @@ var FetchBrainClient = class {
|
|
|
590
729
|
}
|
|
591
730
|
return results;
|
|
592
731
|
} catch (error) {
|
|
593
|
-
this.circuitBreaker.recordFailure();
|
|
732
|
+
if (isOutage(error)) this.circuitBreaker.recordFailure();
|
|
733
|
+
else this.noteRefusal(error);
|
|
594
734
|
throw error;
|
|
595
735
|
}
|
|
596
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
|
+
}
|
|
597
743
|
/**
|
|
598
744
|
* Execute a batch learn against the API
|
|
599
745
|
*/
|
|
600
746
|
async executeBatchLearn(entries) {
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
|
|
604
|
-
}));
|
|
605
|
-
const request = { entries: processed };
|
|
747
|
+
if (entries.length === 0) return { status: "rejected", learned: 0 };
|
|
748
|
+
const request = { entries };
|
|
606
749
|
const platformBuildId = getPlatformBuildId();
|
|
607
750
|
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
608
751
|
request.build = platformBuildId;
|
|
@@ -620,6 +763,7 @@ var FetchBrainClient = class {
|
|
|
620
763
|
return response;
|
|
621
764
|
} catch (error) {
|
|
622
765
|
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
766
|
+
this.noteRefusal(error);
|
|
623
767
|
if (error.code === "LEARN_CAP_EXCEEDED") {
|
|
624
768
|
const now = /* @__PURE__ */ new Date();
|
|
625
769
|
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
@@ -659,7 +803,7 @@ var FetchBrainClient = class {
|
|
|
659
803
|
if (process.env.NODE_ENV) {
|
|
660
804
|
contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
|
|
661
805
|
}
|
|
662
|
-
const nativeContext = buildNativeContext();
|
|
806
|
+
const nativeContext = buildNativeContext(process.env, this.scraperName);
|
|
663
807
|
if (nativeContext) {
|
|
664
808
|
contextHeaders["X-FB-Context"] = nativeContext;
|
|
665
809
|
}
|
|
@@ -731,6 +875,13 @@ var FetchBrainClient = class {
|
|
|
731
875
|
/**
|
|
732
876
|
* Flush pending learn requests (call before shutdown)
|
|
733
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
|
+
}
|
|
734
885
|
async flushLearnBatch() {
|
|
735
886
|
await this.learnBatcher.forceFlush();
|
|
736
887
|
}
|
|
@@ -895,6 +1046,7 @@ var TelemetryBuffer = class {
|
|
|
895
1046
|
this.flushTimer = setInterval(() => {
|
|
896
1047
|
this.flush();
|
|
897
1048
|
}, this.flushInterval);
|
|
1049
|
+
this.flushTimer.unref?.();
|
|
898
1050
|
}
|
|
899
1051
|
/**
|
|
900
1052
|
* Stop the flush timer and flush remaining entries
|
|
@@ -911,6 +1063,16 @@ var TelemetryBuffer = class {
|
|
|
911
1063
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
912
1064
|
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
913
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
|
+
}
|
|
914
1076
|
function buildRawRequest(request) {
|
|
915
1077
|
const r = request;
|
|
916
1078
|
let headers;
|
|
@@ -1020,6 +1182,7 @@ var FetchBrain = class {
|
|
|
1020
1182
|
// enqueue-time fetch skipped, but remembered data gone by execution
|
|
1021
1183
|
startTime: 0
|
|
1022
1184
|
};
|
|
1185
|
+
const pendingLearns = /* @__PURE__ */ new Set();
|
|
1023
1186
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
1024
1187
|
if (!originalHandler) {
|
|
1025
1188
|
logger.warn("No request handler found on crawler, returning unmodified");
|
|
@@ -1028,26 +1191,40 @@ var FetchBrain = class {
|
|
|
1028
1191
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
1029
1192
|
const warnedKeys = /* @__PURE__ */ new Set();
|
|
1030
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
|
+
};
|
|
1031
1203
|
const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
|
|
1032
1204
|
const stashSet = (key, data) => {
|
|
1033
|
-
|
|
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)) {
|
|
1034
1208
|
const oldest = preRecalledData.keys().next().value;
|
|
1035
|
-
if (oldest
|
|
1209
|
+
if (oldest === void 0) break;
|
|
1210
|
+
stashDelete(oldest);
|
|
1036
1211
|
}
|
|
1037
|
-
preRecalledData.set(key, data);
|
|
1212
|
+
preRecalledData.set(key, { data, bytes });
|
|
1213
|
+
stashBytes += bytes;
|
|
1038
1214
|
};
|
|
1039
1215
|
const stashTake = (r) => {
|
|
1040
1216
|
for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
|
|
1041
|
-
const
|
|
1042
|
-
if (
|
|
1043
|
-
|
|
1044
|
-
return data;
|
|
1217
|
+
const entry = preRecalledData.get(key);
|
|
1218
|
+
if (entry) {
|
|
1219
|
+
stashDelete(key);
|
|
1220
|
+
return entry.data;
|
|
1045
1221
|
}
|
|
1046
1222
|
}
|
|
1047
1223
|
return void 0;
|
|
1048
1224
|
};
|
|
1049
1225
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
1050
1226
|
const wrappedHandler = async (context) => {
|
|
1227
|
+
crawlStarted = true;
|
|
1051
1228
|
const { request } = context;
|
|
1052
1229
|
const url = request.url;
|
|
1053
1230
|
const label = request.label;
|
|
@@ -1148,12 +1325,11 @@ var FetchBrain = class {
|
|
|
1148
1325
|
} else {
|
|
1149
1326
|
logger.debug(`Learning: ${url}`);
|
|
1150
1327
|
}
|
|
1328
|
+
const learnItems = [];
|
|
1151
1329
|
if (originalPushData && config.learning !== false) {
|
|
1152
1330
|
context.pushData = async (data) => {
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
runStats.learned++;
|
|
1156
|
-
await client.learn(rawRequest, data);
|
|
1331
|
+
if (!usedAIData && !aiResult.known) {
|
|
1332
|
+
learnItems.push(...Array.isArray(data) ? data : [data]);
|
|
1157
1333
|
}
|
|
1158
1334
|
return originalPushData.call(context, data);
|
|
1159
1335
|
};
|
|
@@ -1162,11 +1338,20 @@ var FetchBrain = class {
|
|
|
1162
1338
|
request: rawRequest,
|
|
1163
1339
|
client,
|
|
1164
1340
|
learning: config.learning !== false,
|
|
1165
|
-
aiKnown: aiResult.known
|
|
1341
|
+
aiKnown: aiResult.known,
|
|
1342
|
+
items: learnItems
|
|
1166
1343
|
};
|
|
1167
1344
|
await asyncContext.run(requestContext, async () => {
|
|
1168
1345
|
await originalHandler.call(crawler, context);
|
|
1169
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
|
+
}
|
|
1170
1355
|
if (telemetryConfig.enabled) {
|
|
1171
1356
|
try {
|
|
1172
1357
|
const telemetry = await collectTelemetry(
|
|
@@ -1261,6 +1446,7 @@ var FetchBrain = class {
|
|
|
1261
1446
|
} finally {
|
|
1262
1447
|
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1263
1448
|
await client.flushLearnBatch();
|
|
1449
|
+
await Promise.allSettled([...pendingLearns]);
|
|
1264
1450
|
if (telemetryConfig.enabled) {
|
|
1265
1451
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
1266
1452
|
await telemetryBuffer.stop();
|
|
@@ -1283,24 +1469,11 @@ var FetchBrain = class {
|
|
|
1283
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."
|
|
1284
1470
|
);
|
|
1285
1471
|
}
|
|
1286
|
-
|
|
1287
|
-
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1288
|
-
return originalAddRequests(requests, options);
|
|
1289
|
-
}
|
|
1290
|
-
const retryOnBlocked = Boolean(
|
|
1291
|
-
crawlerAny.retryOnBlocked
|
|
1292
|
-
);
|
|
1293
|
-
const batch = requests.map((r) => {
|
|
1294
|
-
if (typeof r === "string") return { url: r };
|
|
1295
|
-
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1296
|
-
return { ...r };
|
|
1297
|
-
}
|
|
1298
|
-
return r;
|
|
1299
|
-
});
|
|
1472
|
+
const preRecallSlice = async (slice, retryOnBlocked) => {
|
|
1300
1473
|
try {
|
|
1301
1474
|
const candidateIdx = [];
|
|
1302
|
-
for (let i = 0; i <
|
|
1303
|
-
const r =
|
|
1475
|
+
for (let i = 0; i < slice.length; i++) {
|
|
1476
|
+
const r = slice[i];
|
|
1304
1477
|
if (!r || typeof r.url !== "string") continue;
|
|
1305
1478
|
const prior = r.userData?.__fetchBrainResult;
|
|
1306
1479
|
if (prior) {
|
|
@@ -1316,14 +1489,14 @@ var FetchBrain = class {
|
|
|
1316
1489
|
}
|
|
1317
1490
|
if (candidateIdx.length > 0) {
|
|
1318
1491
|
const rawRequests = candidateIdx.map(
|
|
1319
|
-
(i) => buildRawRequest(
|
|
1492
|
+
(i) => buildRawRequest(slice[i])
|
|
1320
1493
|
);
|
|
1321
1494
|
const results = await client.recallBulk(rawRequests);
|
|
1322
1495
|
let known = 0;
|
|
1323
1496
|
candidateIdx.forEach((reqIdx, j) => {
|
|
1324
1497
|
const result = results[j];
|
|
1325
1498
|
if (!result || result.fallback) return;
|
|
1326
|
-
const r =
|
|
1499
|
+
const r = slice[reqIdx];
|
|
1327
1500
|
if (result.known && result.data) {
|
|
1328
1501
|
r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
|
|
1329
1502
|
stashSet(stashKey(rawRequests[j]), result.data);
|
|
@@ -1342,7 +1515,62 @@ var FetchBrain = class {
|
|
|
1342
1515
|
} catch (err) {
|
|
1343
1516
|
logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
|
|
1344
1517
|
}
|
|
1345
|
-
|
|
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
|
+
}
|
|
1346
1574
|
};
|
|
1347
1575
|
}
|
|
1348
1576
|
return Object.assign(crawler, { fetchBrain: client });
|
|
@@ -1354,10 +1582,7 @@ function createFetchBrain(config) {
|
|
|
1354
1582
|
async function pushData(data, dataset, datasetName) {
|
|
1355
1583
|
const ctx = getCurrentContext();
|
|
1356
1584
|
if (ctx && ctx.learning && !ctx.aiKnown) {
|
|
1357
|
-
|
|
1358
|
-
for (const item of items) {
|
|
1359
|
-
await ctx.client.learn(ctx.request, item);
|
|
1360
|
-
}
|
|
1585
|
+
ctx.items.push(...Array.isArray(data) ? data : [data]);
|
|
1361
1586
|
}
|
|
1362
1587
|
if (datasetName && dataset.open) {
|
|
1363
1588
|
const namedDataset = await dataset.open(datasetName);
|