@fetchbrain.com/sdk 0.8.0 → 0.9.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
@@ -575,9 +575,42 @@ never relearned.
575
575
 
576
576
  When a run finishes, the SDK sends a small report containing exactly: the run
577
577
  id, start and end timestamps, totals for scraped, learned and recalled pages,
578
- per request label how many pages were scraped, came back empty or failed, and
579
- your build id only when `refreshOnRebuild` is on. It contains no URLs and no
580
- scraped data. A page counts as "pushed no data" when your handler pushed nothing
578
+ requests skipped, late recalls and bypassed pages, per request label how many
579
+ pages were scraped, came back empty or failed, and your build id only when
580
+ `refreshOnRebuild` is on. It contains no URLs and no scraped data.
581
+
582
+ | Field | Meaning |
583
+ | --- | --- |
584
+ | `scraped` | pages whose handler ran to completion (unknown pages, and known pages matched by `alwaysRun`) |
585
+ | `learned` | records the brain accepted from this run |
586
+ | `recalled` | known pages served from memory, whether or not their handler also ran |
587
+ | `requestsSkipped` | known pages served from memory **without a fetch**: pre-recalled when they were enqueued, so Crawlee never requested them |
588
+ | `lateRecalls` | known pages served from memory **after** they were fetched: the recall happened in your handler, so the request was already spent |
589
+ | `bypassed` | pages handled outside FetchBrain because of `skipLabels` |
590
+
591
+ Every count covers one `run()` call. A request is counted once, after it
592
+ succeeded (its handler finished, or its recalled data was pushed), so a retry
593
+ never counts it twice and a request that finally fails is not counted. The
594
+ per-label counts are the exception: they count every attempt, so failure and
595
+ empty rates see each retry. Each `run()` call gets its own run id: on a platform that sets
596
+ a run id, the first call uses it as-is and later calls in the same process
597
+ (another `run()`, or a second crawler) add `-2`, `-3` and so on.
598
+
599
+ Requests skipped is what saves you requests. Late recalls are pages that came
600
+ from the queue without a [pre-recall](#recall-at-enqueue-time-prerecall):
601
+ links from `enqueueLinks()` or the context `addRequests()`, and every known page
602
+ on a `retryOnBlocked` crawler, plus non-GET requests without an explicit
603
+ `uniqueKey` (pre-recall can't identify them at enqueue time; set one to let it).
604
+ Known requests you marked `skipNavigation` yourself count only as `recalled`,
605
+ never as late recalls: they were never fetched.
606
+ When a run has late recalls, the summary line is followed by a tip such as:
607
+
608
+ ```
609
+ 3 pages were recalled after they were fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).
610
+ ```
611
+
612
+ The tip is not shown on `retryOnBlocked` crawlers (their blocked-check needs
613
+ the fetch, so those pages can't skip it) or when `preRecall` is `false`. A page counts as "pushed no data" when your handler pushed nothing
581
614
  through `context.pushData` or the SDK's `pushData` export (pages written
582
615
  straight to Crawlee's static `Dataset.pushData` are counted that way too), and
583
616
  retries count once per attempt. The report is sent with the same standard
@@ -634,7 +667,7 @@ or route those requests through `skipLabels`, which sends nothing for them.
634
667
  `ask()` sends your question and options. Telemetry sends nothing unless you
635
668
  [opt in](#telemetry-opt-in). At the end of a run the SDK also sends a small
636
669
  [run report](#run-report): run id, start/end timestamps, scraped/learned/recalled
637
- counts, per-label page counts, and a build id only with `refreshOnRebuild`
670
+ counts, requests skipped, late recalls and bypassed counts, per-label page counts, and a build id only with `refreshOnRebuild`
638
671
  (`reportRuns: false` turns it off).
639
672
 
640
673
  ## Telemetry (opt-in)
@@ -655,6 +688,16 @@ so they're linked to your account. They're used to improve FetchBrain's
655
688
  recommendations (proxy recommendations, block detection, configuration
656
689
  tuning); aggregated statistics may inform recommendations for other users.
657
690
 
691
+ **How long it's kept:** raw entries are deleted about 30 days after they're
692
+ received (a daily cleanup), and all of your entries are deleted when you
693
+ delete your account (a very large history may take the daily cleanup a few
694
+ days to finish, never longer than the 30 days above).
695
+ Per-domain aggregate counts (requests, successes, blocks and block rate for a
696
+ hostname, with no URLs and no account link) are kept. Per-domain statistics
697
+ are aggregated per domain, not per account: entries from every account that
698
+ scraped a hostname add to the same counts, and they are not deleted with your
699
+ account.
700
+
658
701
  **When it's collected:** one entry per request FetchBrain handles
659
702
  (`skipLabels` requests are excluded), after your handler finishes — or
660
703
  whenever the request fails inside the SDK's wrapper, including failures
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-B579TMo9.mjs';
2
- export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-B579TMo9.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.mjs';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.mjs';
3
3
 
4
4
  declare class FetchBrainClient {
5
5
  private config;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-B579TMo9.js';
2
- export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-B579TMo9.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.js';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.js';
3
3
 
4
4
  declare class FetchBrainClient {
5
5
  private config;
package/dist/index.js CHANGED
@@ -1161,7 +1161,12 @@ function safeChangeStats(client) {
1161
1161
  }
1162
1162
  }
1163
1163
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
1164
- var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
1164
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set([
1165
+ "fetchBrainRecalled",
1166
+ "fetchBrainData",
1167
+ "__fetchBrainResult",
1168
+ "__fetchBrainCounted"
1169
+ ]);
1165
1170
  var MAX_STASH_ENTRIES = 5e3;
1166
1171
  var MAX_STASH_BYTES = 256 * 1024 * 1024;
1167
1172
  var stashBytesCap = MAX_STASH_BYTES;
@@ -1280,6 +1285,10 @@ var FetchBrain = class {
1280
1285
  recalled: 0,
1281
1286
  aiSkipped: 0,
1282
1287
  // brain knew + skipped scraping
1288
+ requestsSkipped: 0,
1289
+ // recalled without a fetch (pre-recalled at enqueue + skipNavigation)
1290
+ lateRecalls: 0,
1291
+ // recalled after the page was already fetched
1283
1292
  learned: 0,
1284
1293
  scraped: 0,
1285
1294
  // Actually ran handler
@@ -1434,20 +1443,31 @@ var FetchBrain = class {
1434
1443
  const handlerLabel = request.label;
1435
1444
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
1436
1445
  if (aiResult.known && aiResult.data && !runHandler) {
1437
- runStats.recalled++;
1438
- runStats.aiSkipped++;
1439
1446
  logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
1440
1447
  if (originalPushData) {
1441
1448
  await originalPushData.call(context, aiResult.data);
1442
1449
  }
1450
+ try {
1451
+ if (!request.userData?.__fetchBrainCounted) {
1452
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1453
+ runStats.recalled++;
1454
+ runStats.aiSkipped++;
1455
+ const skippedNav = request.skipNavigation === true;
1456
+ if (preRecalled?.known && skippedNav) {
1457
+ runStats.requestsSkipped++;
1458
+ } else if (!skippedNav) {
1459
+ runStats.lateRecalls++;
1460
+ }
1461
+ }
1462
+ } catch (countErr) {
1463
+ logger.debug(`Run stats skipped: ${countErr}`);
1464
+ }
1443
1465
  await fireOnRecalled(aiResult.data);
1444
1466
  return;
1445
1467
  }
1446
- runStats.scraped++;
1447
1468
  const counts = labelCounts(request.label);
1448
1469
  if (counts) counts.scraped++;
1449
1470
  if (aiResult.known) {
1450
- runStats.recalled++;
1451
1471
  logger.info(
1452
1472
  `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
1453
1473
  );
@@ -1479,6 +1499,15 @@ var FetchBrain = class {
1479
1499
  if (counts) counts.failed++;
1480
1500
  throw handlerErr;
1481
1501
  }
1502
+ try {
1503
+ if (!request.userData?.__fetchBrainCounted) {
1504
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1505
+ runStats.scraped++;
1506
+ if (aiResult.known) runStats.recalled++;
1507
+ }
1508
+ } catch (countErr) {
1509
+ logger.debug(`Run stats skipped: ${countErr}`);
1510
+ }
1482
1511
  if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1483
1512
  counts.empty++;
1484
1513
  }
@@ -1576,7 +1605,17 @@ var FetchBrain = class {
1576
1605
  runStats.startTime = Date.now();
1577
1606
  const runStartedAt = new Date(runStats.startTime).toISOString();
1578
1607
  labelStats.clear();
1579
- const runBase = { scraped: runStats.scraped, learned: runStats.learned, recalled: runStats.recalled };
1608
+ const runBase = {
1609
+ totalRequests: runStats.totalRequests,
1610
+ bypassed: runStats.bypassed,
1611
+ dropped: runStats.dropped,
1612
+ scraped: runStats.scraped,
1613
+ learned: runStats.learned,
1614
+ recalled: runStats.recalled,
1615
+ aiSkipped: runStats.aiSkipped,
1616
+ requestsSkipped: runStats.requestsSkipped,
1617
+ lateRecalls: runStats.lateRecalls
1618
+ };
1580
1619
  const changeBase = safeChangeStats(client);
1581
1620
  const runId = nextRunId();
1582
1621
  try {
@@ -1593,8 +1632,19 @@ var FetchBrain = class {
1593
1632
  const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1594
1633
  1
1595
1634
  );
1596
- const managedRequests = runStats.totalRequests - runStats.bypassed;
1597
- const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1635
+ const run = {
1636
+ totalRequests: runStats.totalRequests - runBase.totalRequests,
1637
+ bypassed: runStats.bypassed - runBase.bypassed,
1638
+ dropped: runStats.dropped - runBase.dropped,
1639
+ scraped: runStats.scraped - runBase.scraped,
1640
+ learned: runStats.learned - runBase.learned,
1641
+ recalled: runStats.recalled - runBase.recalled,
1642
+ aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
1643
+ requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
1644
+ lateRecalls: runStats.lateRecalls - runBase.lateRecalls
1645
+ };
1646
+ const managedRequests = run.totalRequests - run.bypassed;
1647
+ const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1598
1648
  let changes = { changed: 0, drift: [] };
1599
1649
  try {
1600
1650
  const now = safeChangeStats(client);
@@ -1609,8 +1659,13 @@ var FetchBrain = class {
1609
1659
  }
1610
1660
  const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1611
1661
  logger.info(
1612
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1662
+ `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} (${savingsPercent}%), requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1613
1663
  );
1664
+ if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
1665
+ logger.info(
1666
+ `${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
1667
+ );
1668
+ }
1614
1669
  for (const item of changes.drift) {
1615
1670
  try {
1616
1671
  logger.warn(describeDrift(item));
@@ -1626,9 +1681,12 @@ var FetchBrain = class {
1626
1681
  build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1627
1682
  startedAt: runStartedAt,
1628
1683
  endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1629
- scraped: runStats.scraped - runBase.scraped,
1630
- learned: runStats.learned - runBase.learned,
1631
- recalled: runStats.recalled - runBase.recalled,
1684
+ scraped: run.scraped,
1685
+ learned: run.learned,
1686
+ recalled: run.recalled,
1687
+ requestsSkipped: run.requestsSkipped,
1688
+ lateRecalls: run.lateRecalls,
1689
+ bypassed: run.bypassed,
1632
1690
  labels
1633
1691
  });
1634
1692
  for (const flag of Array.isArray(flags) ? flags : []) {
@@ -1661,10 +1719,11 @@ var FetchBrain = class {
1661
1719
  const r = slice[i];
1662
1720
  if (!r || typeof r.url !== "string") continue;
1663
1721
  const prior = r.userData?.__fetchBrainResult;
1664
- if (prior) {
1665
- if (prior.known && r.skipNavigation) r.skipNavigation = false;
1722
+ if (prior || r.userData?.__fetchBrainCounted) {
1723
+ if (prior?.known && r.skipNavigation) r.skipNavigation = false;
1666
1724
  const rest = { ...r.userData };
1667
1725
  delete rest.__fetchBrainResult;
1726
+ delete rest.__fetchBrainCounted;
1668
1727
  r.userData = rest;
1669
1728
  }
1670
1729
  if (r.skipNavigation) continue;