@fetchbrain.com/sdk 0.4.0 → 0.5.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 CHANGED
@@ -215,11 +215,70 @@ interface FetchBrainConfig {
215
215
  learning?: boolean; // Enable AI learning (default: true)
216
216
  alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
217
217
  skipLabels?: string[]; // Labels that bypass FetchBrain entirely (default: none)
218
+ preRecall?: boolean; // Recall requests in bulk as they're enqueued (default: true)
219
+ onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when known data is delivered
218
220
  timeout?: number; // Request timeout in ms (default: 500)
219
221
  debug?: boolean; // Enable debug logging
220
222
  }
221
223
  ```
222
224
 
225
+ ### Recall at enqueue time (`preRecall`)
226
+
227
+ In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
228
+ your request handler runs — so a recall inside the handler is too late to
229
+ save the fetch. With `preRecall` (on by default), the SDK checks the brain
230
+ the moment requests enter the queue: each `crawler.addRequests()` array
231
+ becomes a single bulk recall, known requests are enqueued with Crawlee's
232
+ `skipNavigation` so their fetch never happens, and unknown requests carry
233
+ their recall result with them so the handler doesn't ask twice. Enqueue in
234
+ batches (one `addRequests` call per page of discovered items) to get the
235
+ most out of it. If the brain is unreachable, requests are enqueued unchanged
236
+ and your crawl proceeds at native speed — same graceful degradation as
237
+ everywhere else.
238
+
239
+ Things to know:
240
+
241
+ - **Scope** — pre-recall applies to arrays passed to `crawler.addRequests()`
242
+ or `crawler.run(requests)`. Crawlee's context-level `enqueueLinks()` and
243
+ context `addRequests()` reach the queue by other paths and are not
244
+ pre-recalled (they still get handler-time recall). Inside a handler,
245
+ enqueue follow-ups with `context.crawler.addRequests([...])` to keep the
246
+ benefit — as in the example above.
247
+ - **Metering** — recall queries are counted when requests are enqueued, so
248
+ duplicates the queue later drops still count as queries.
249
+ - **Snapshot semantics** — the recall result is as of enqueue time. Anything
250
+ learned between enqueue and execution isn't picked up; the request is
251
+ simply scraped and re-learned.
252
+ - **Expired memory** — if a request skipped its fetch at enqueue but its
253
+ remembered data genuinely expired before it executed (e.g. across a process
254
+ restart), it fails once without retries and lands in your
255
+ `failedRequestHandler`, so the missing record is visible to your error
256
+ tooling. It will be re-scraped on a future run. (If the data merely couldn't
257
+ be restored because the API was briefly unreachable, the request fails
258
+ retryable and the next attempt restores it.)
259
+ - **`retryOnBlocked` crawlers** — Crawlee's blocked-request detection needs a
260
+ fetched response, so on these crawlers known requests keep their fetch;
261
+ recalled data still replaces the handler (no second recall, no re-scrape).
262
+
263
+ ### Reacting to recalled records (`onRecalled`)
264
+
265
+ When the brain knows a request, your handler is skipped and the remembered
266
+ data is pushed for you — which also skips any per-record bookkeeping living
267
+ in that handler (billing events, counters, follow-up enqueues). `onRecalled`
268
+ runs once per recalled record with `{ url, label, userData, data }` — both
269
+ when the handler is auto-skipped and when your own handler calls
270
+ `context.brain.use()`:
271
+
272
+ ```typescript
273
+ FetchBrain.enhance(crawler, {
274
+ onRecalled: async ({ userData }) => {
275
+ await Actor.charge({ eventName: "product-detail", count: 1 });
276
+ },
277
+ });
278
+ ```
279
+
280
+ Hook errors are swallowed (logged at debug) — they never break the crawl.
281
+
223
282
  Fine-grained routing control with `alwaysRun` — run every handler, none, or
224
283
  only specific labels when a request is known:
225
284
 
@@ -307,11 +366,11 @@ const crawler = FetchBrain.enhance(
307
366
 
308
367
  ### `context.brain` Properties
309
368
 
310
- | Property | Type | Description |
311
- | --------- | -------- | ---------------------------------- |
312
- | `known` | boolean | Whether the brain knows this URL |
313
- | `data` | object | Brain data (if known) |
314
- | `use()` | function | Push brain data and skip scraping |
369
+ | Property | Type | Description |
370
+ | -------- | -------- | --------------------------------- |
371
+ | `known` | boolean | Whether the brain knows this URL |
372
+ | `data` | object | Brain data (if known) |
373
+ | `use()` | function | Push brain data and skip scraping |
315
374
 
316
375
  ## Using Dataset.pushData
317
376
 
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-D8djjVGS.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-D8djjVGS.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BbLgy1no.mjs';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BbLgy1no.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -21,7 +21,9 @@ declare class FetchBrainClient {
21
21
  */
22
22
  recall(request: RawRequest): Promise<RecallResult>;
23
23
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
24
+ * Recall multiple requests at once — returns ordered array matching input order.
25
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
26
+ * failed chunk degrades to fallback results for its own items only.
25
27
  */
26
28
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
29
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-D8djjVGS.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-D8djjVGS.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BbLgy1no.js';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BbLgy1no.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -21,7 +21,9 @@ declare class FetchBrainClient {
21
21
  */
22
22
  recall(request: RawRequest): Promise<RecallResult>;
23
23
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
24
+ * Recall multiple requests at once — returns ordered array matching input order.
25
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
26
+ * failed chunk degrades to fallback results for its own items only.
25
27
  */
26
28
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
29
  /**
package/dist/index.js CHANGED
@@ -346,7 +346,14 @@ function getPlatformBuildId(env = process.env) {
346
346
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
347
347
  var DEFAULT_TIMEOUT = 500;
348
348
  var DEFAULT_LEARN_TIMEOUT = 5e3;
349
+ var BULK_RECALL_TIMEOUT = 3e3;
350
+ var MAX_BULK_ITEMS = 100;
351
+ var BULK_RECALL_CONCURRENCY = 5;
352
+ var MAX_LEARN_ENTRIES = 50;
349
353
  var ASK_TIMEOUT = 1e4;
354
+ function clampBatch(batch, cap) {
355
+ return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
356
+ }
350
357
  var ApiError = class extends Error {
351
358
  constructor(status, statusText, serverError) {
352
359
  super(`API error: ${status} ${statusText}`);
@@ -379,7 +386,11 @@ var FetchBrainClient = class {
379
386
  // opt-in
380
387
  batch: config.batch,
381
388
  circuitBreaker: config.circuitBreaker,
382
- skipLabels: config.skipLabels
389
+ skipLabels: config.skipLabels,
390
+ // enhance-only; stored so getConfig() round-trips
391
+ preRecall: config.preRecall,
392
+ // enhance-only; stored so getConfig() round-trips
393
+ onRecalled: config.onRecalled
383
394
  // enhance-only; stored so getConfig() round-trips
384
395
  };
385
396
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
@@ -389,12 +400,12 @@ var FetchBrainClient = class {
389
400
  );
390
401
  this.batcher = new RequestBatcher(
391
402
  (items) => this.executeBatchQuery(items),
392
- this.config.batch,
403
+ clampBatch(this.config.batch, MAX_BULK_ITEMS),
393
404
  this.logger
394
405
  );
395
406
  this.learnBatcher = new LearnBatcher(
396
407
  (entries) => this.executeBatchLearn(entries),
397
- this.config.batch,
408
+ clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
398
409
  this.logger
399
410
  );
400
411
  }
@@ -413,19 +424,38 @@ var FetchBrainClient = class {
413
424
  }
414
425
  }
415
426
  /**
416
- * Recall multiple requests at once — returns ordered array matching input order
427
+ * Recall multiple requests at once — returns ordered array matching input order.
428
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
429
+ * failed chunk degrades to fallback results for its own items only.
417
430
  */
418
431
  async recallBulk(requests) {
419
- if (this.circuitBreaker.isOpen()) {
420
- return requests.map(() => ({ known: false, fallback: true }));
421
- }
422
- try {
423
- const items = requests.map((request, i) => ({ ref: String(i), request }));
424
- const results = await this.executeBatchQuery(items);
425
- return items.map((i) => results.get(i.ref) ?? { known: false });
426
- } catch {
427
- return requests.map(() => ({ known: false, fallback: true }));
432
+ const chunks = [];
433
+ for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
434
+ chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
428
435
  }
436
+ const chunkResults = new Array(chunks.length);
437
+ let next = 0;
438
+ const worker = async () => {
439
+ while (next < chunks.length) {
440
+ const idx = next++;
441
+ const chunk = chunks[idx];
442
+ if (this.circuitBreaker.isOpen()) {
443
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
444
+ continue;
445
+ }
446
+ try {
447
+ const items = chunk.map((request, i) => ({ ref: String(i), request }));
448
+ const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
449
+ chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
450
+ } catch {
451
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
452
+ }
453
+ }
454
+ };
455
+ await Promise.all(
456
+ Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
457
+ );
458
+ return chunkResults.flat();
429
459
  }
430
460
  /**
431
461
  * "Teach" FetchBrain new data (batched for high-concurrency)
@@ -513,7 +543,7 @@ var FetchBrainClient = class {
513
543
  /**
514
544
  * Execute a batch query against the API
515
545
  */
516
- async executeBatchQuery(items) {
546
+ async executeBatchQuery(items, timeout) {
517
547
  const results = /* @__PURE__ */ new Map();
518
548
  const request = {
519
549
  items,
@@ -524,10 +554,14 @@ var FetchBrainClient = class {
524
554
  request.build = platformBuildId;
525
555
  }
526
556
  try {
527
- const response = await this.makeRequest("/v1/recall", {
528
- method: "POST",
529
- body: JSON.stringify(request)
530
- });
557
+ const response = await this.makeRequest(
558
+ "/v1/recall",
559
+ {
560
+ method: "POST",
561
+ body: JSON.stringify(request)
562
+ },
563
+ timeout
564
+ );
531
565
  this.circuitBreaker.recordSuccess();
532
566
  for (const item of response.known) {
533
567
  results.set(item.ref, { known: true, data: item.data });
@@ -830,6 +864,7 @@ var TelemetryBuffer = class {
830
864
  // src/enhance.ts
831
865
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
832
866
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
867
+ var MAX_STASH_ENTRIES = 5e3;
833
868
  function buildRawRequest(request) {
834
869
  const r = request;
835
870
  let headers;
@@ -935,6 +970,8 @@ var FetchBrain = class {
935
970
  // Actually ran handler
936
971
  bypassed: 0,
937
972
  // skipLabels match — ran handler outside FetchBrain
973
+ dropped: 0,
974
+ // enqueue-time fetch skipped, but remembered data gone by execution
938
975
  startTime: 0
939
976
  };
940
977
  const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
@@ -944,6 +981,25 @@ var FetchBrain = class {
944
981
  }
945
982
  const crawlerType = crawler.constructor?.name || "Unknown";
946
983
  const warnedKeys = /* @__PURE__ */ new Set();
984
+ const preRecalledData = /* @__PURE__ */ new Map();
985
+ const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
986
+ const stashSet = (key, data) => {
987
+ if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
988
+ const oldest = preRecalledData.keys().next().value;
989
+ if (oldest !== void 0) preRecalledData.delete(oldest);
990
+ }
991
+ preRecalledData.set(key, data);
992
+ };
993
+ const stashTake = (r) => {
994
+ for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
995
+ const data = preRecalledData.get(key);
996
+ if (data) {
997
+ preRecalledData.delete(key);
998
+ return data;
999
+ }
1000
+ }
1001
+ return void 0;
1002
+ };
947
1003
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
948
1004
  const wrappedHandler = async (context) => {
949
1005
  const { request } = context;
@@ -964,10 +1020,50 @@ var FetchBrain = class {
964
1020
  });
965
1021
  const rawRequest = buildRawRequest(request);
966
1022
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1023
+ let consumedStash;
967
1024
  try {
968
- const aiResult = await client.recall(rawRequest);
1025
+ const preRecalled = request.userData?.__fetchBrainResult;
1026
+ let aiResult;
1027
+ if (preRecalled?.known) {
1028
+ const stashedData = stashTake(rawRequest);
1029
+ if (stashedData) {
1030
+ consumedStash = stashedData;
1031
+ aiResult = { known: true, data: stashedData };
1032
+ } else {
1033
+ aiResult = await client.recall(rawRequest);
1034
+ }
1035
+ } else if (preRecalled) {
1036
+ aiResult = preRecalled;
1037
+ } else {
1038
+ aiResult = await client.recall(rawRequest);
1039
+ }
1040
+ if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1041
+ if (aiResult.fallback) {
1042
+ throw new Error(
1043
+ `FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1044
+ );
1045
+ }
1046
+ runStats.dropped++;
1047
+ request.noRetry = true;
1048
+ throw new Error(
1049
+ `FetchBrain: ${url} 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.`
1050
+ );
1051
+ }
969
1052
  let usedAIData = false;
970
1053
  const originalPushData = context.pushData;
1054
+ const fireOnRecalled = async (data) => {
1055
+ if (!config.onRecalled) return;
1056
+ try {
1057
+ await config.onRecalled({
1058
+ url,
1059
+ label: request.label,
1060
+ userData: rawRequest.userData,
1061
+ data
1062
+ });
1063
+ } catch (hookErr) {
1064
+ logger.debug(`onRecalled hook error: ${hookErr}`);
1065
+ }
1066
+ };
971
1067
  context.brain = {
972
1068
  known: aiResult.known,
973
1069
  data: aiResult.data,
@@ -976,6 +1072,7 @@ var FetchBrain = class {
976
1072
  usedAIData = true;
977
1073
  await originalPushData.call(context, aiResult.data);
978
1074
  logger.info(`Used brain data: ${url}`);
1075
+ await fireOnRecalled(aiResult.data);
979
1076
  }
980
1077
  }
981
1078
  };
@@ -993,6 +1090,7 @@ var FetchBrain = class {
993
1090
  if (originalPushData) {
994
1091
  await originalPushData.call(context, aiResult.data);
995
1092
  }
1093
+ await fireOnRecalled(aiResult.data);
996
1094
  return;
997
1095
  }
998
1096
  runStats.scraped++;
@@ -1065,6 +1163,9 @@ var FetchBrain = class {
1065
1163
  }
1066
1164
  }
1067
1165
  } catch (err) {
1166
+ if (consumedStash) {
1167
+ stashSet(stashKey(rawRequest), consumedStash);
1168
+ }
1068
1169
  if (telemetryConfig.enabled) {
1069
1170
  try {
1070
1171
  const telemetry = await collectTelemetry(
@@ -1124,11 +1225,80 @@ var FetchBrain = class {
1124
1225
  const managedRequests = runStats.totalRequests - runStats.bypassed;
1125
1226
  const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1126
1227
  logger.info(
1127
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + `, duration: ${duration}s`
1228
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + `, duration: ${duration}s`
1128
1229
  );
1129
1230
  }
1130
1231
  };
1131
1232
  }
1233
+ if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
1234
+ const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
1235
+ if (crawlerAny.retryOnBlocked) {
1236
+ logger.info(
1237
+ "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."
1238
+ );
1239
+ }
1240
+ crawlerAny.addRequests = async (requests, options) => {
1241
+ if (!Array.isArray(requests) || requests.length === 0) {
1242
+ return originalAddRequests(requests, options);
1243
+ }
1244
+ const retryOnBlocked = Boolean(
1245
+ crawlerAny.retryOnBlocked
1246
+ );
1247
+ const batch = requests.map((r) => {
1248
+ if (typeof r === "string") return { url: r };
1249
+ if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1250
+ return { ...r };
1251
+ }
1252
+ return r;
1253
+ });
1254
+ try {
1255
+ const candidateIdx = [];
1256
+ for (let i = 0; i < batch.length; i++) {
1257
+ const r = batch[i];
1258
+ if (!r || typeof r.url !== "string") continue;
1259
+ const prior = r.userData?.__fetchBrainResult;
1260
+ if (prior) {
1261
+ if (prior.known && r.skipNavigation) r.skipNavigation = false;
1262
+ const rest = { ...r.userData };
1263
+ delete rest.__fetchBrainResult;
1264
+ r.userData = rest;
1265
+ }
1266
+ if (r.skipNavigation) continue;
1267
+ if (skipLabels && skipLabels.has(r.label || "default")) continue;
1268
+ if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
1269
+ candidateIdx.push(i);
1270
+ }
1271
+ if (candidateIdx.length > 0) {
1272
+ const rawRequests = candidateIdx.map(
1273
+ (i) => buildRawRequest(batch[i])
1274
+ );
1275
+ const results = await client.recallBulk(rawRequests);
1276
+ let known = 0;
1277
+ candidateIdx.forEach((reqIdx, j) => {
1278
+ const result = results[j];
1279
+ if (!result || result.fallback) return;
1280
+ const r = batch[reqIdx];
1281
+ if (result.known && result.data) {
1282
+ r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
1283
+ stashSet(stashKey(rawRequests[j]), result.data);
1284
+ if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
1285
+ r.skipNavigation = true;
1286
+ known++;
1287
+ }
1288
+ } else {
1289
+ r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
1290
+ }
1291
+ });
1292
+ logger.debug(
1293
+ `Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
1294
+ );
1295
+ }
1296
+ } catch (err) {
1297
+ logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
1298
+ }
1299
+ return originalAddRequests(batch, options);
1300
+ };
1301
+ }
1132
1302
  return Object.assign(crawler, { fetchBrain: client });
1133
1303
  }
1134
1304
  };