-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcontent-processor.ts
More file actions
2163 lines (1873 loc) · 97.4 KB
/
content-processor.ts
File metadata and controls
2163 lines (1873 loc) · 97.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Readability } from '@mozilla/readability';
import axios from 'axios';
import { load } from 'cheerio';
import { JSDOM } from 'jsdom';
import puppeteer, { Browser, Page } from 'puppeteer';
import sanitizeHtml from 'sanitize-html';
import TurndownService from 'turndown';
import * as fs from 'fs';
import * as path from 'path';
import { Logger } from './logger';
import { Utils } from './utils';
import {
SourceConfig,
WebsiteSourceConfig,
LocalDirectorySourceConfig,
CodeSourceConfig,
DocumentChunk,
BrokenLink
} from './types';
import type { TokenChunker, Tokenizer } from '@chonkiejs/core';
import { CodeChunker } from './code-chunker';
export class ContentProcessor {
private turndownService: TurndownService;
private logger: Logger;
private tokenChunkerCache: Map<string, Promise<TokenChunker>>;
private codeChunkerCache: Map<string, Promise<CodeChunker>>;
private tokenizerCache: Promise<Tokenizer> | null;
constructor(logger: Logger) {
this.logger = logger;
this.turndownService = new TurndownService({
codeBlockStyle: 'fenced',
headingStyle: 'atx'
});
this.tokenChunkerCache = new Map();
this.codeChunkerCache = new Map();
this.tokenizerCache = null;
this.setupTurndownRules();
}
private setupTurndownRules() {
const logger = this.logger.child('markdown');
logger.debug('Setting up Turndown rules for markdown conversion');
this.turndownService.addRule('codeBlocks', {
filter: (node: Node): boolean => node.nodeName === 'PRE',
replacement: (content: string, node: Node): string => {
const htmlNode = node as HTMLElement;
const code = htmlNode.querySelector('code');
let codeContent;
if (code) {
codeContent = code.textContent || '';
} else {
codeContent = htmlNode.textContent || '';
}
const lines = codeContent.split('\n');
let minIndent = Infinity;
for (const line of lines) {
if (line.trim() === '') continue;
const leadingWhitespace = line.match(/^\s*/)?.[0] || '';
minIndent = Math.min(minIndent, leadingWhitespace.length);
}
const cleanedLines = lines.map(line => {
return line.substring(minIndent);
});
let cleanContent = cleanedLines.join('\n');
cleanContent = cleanContent.replace(/^\s+|\s+$/g, '');
cleanContent = cleanContent.replace(/\n{2,}/g, '\n');
return `\n\`\`\`\n${cleanContent}\n\`\`\`\n`;
}
});
this.turndownService.addRule('tableCell', {
filter: ['th', 'td'],
replacement: (content: string, node: Node): string => {
const htmlNode = node as HTMLElement;
let cellContent = '';
if (htmlNode.querySelector('p')) {
cellContent = Array.from(htmlNode.querySelectorAll('p'))
.map(p => p.textContent || '')
.join(' ')
.trim();
} else {
cellContent = content.trim();
}
return ` ${cellContent.replace(/\|/g, '\\|')} |`;
}
});
this.turndownService.addRule('tableRow', {
filter: 'tr',
replacement: (content: string, node: Node): string => {
const htmlNode = node as HTMLTableRowElement;
const cells = Array.from(htmlNode.cells);
const isHeader = htmlNode.parentNode?.nodeName === 'THEAD';
let output = '|' + content.trimEnd();
if (isHeader) {
const separator = cells.map(() => '---').join(' | ');
output += '\n|' + separator + '|';
}
if (!isHeader || !htmlNode.nextElementSibling) {
output += '\n';
}
return output;
}
});
this.turndownService.addRule('table', {
filter: 'table',
replacement: (content: string): string => {
return '\n' + content.replace(/\n+/g, '\n').trim() + '\n';
}
});
this.turndownService.addRule('preserveTableWhitespace', {
filter: (node: Node): boolean => {
return (
(node.nodeName === 'TD' || node.nodeName === 'TH') &&
(node.textContent?.trim().length === 0)
);
},
replacement: (): string => {
return ' |';
}
});
logger.debug('Turndown rules setup complete');
}
public convertHtmlToMarkdown(html: string): string {
if (!html || !html.trim()) {
return '';
}
// Pre-process tabbed content before sanitization strips ARIA attributes
const dom = new JSDOM(html);
const tabButtons = dom.window.document.querySelectorAll('[role="tab"]');
if (tabButtons.length > 0) {
const logger = this.logger.child('markdown');
this.preprocessTabs(dom.window.document, logger);
html = dom.window.document.body.innerHTML;
}
// Sanitize the HTML first
const cleanHtml = sanitizeHtml(html, {
allowedTags: [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'a', 'ul', 'ol',
'li', 'b', 'i', 'strong', 'em', 'code', 'pre',
'div', 'span', 'table', 'thead', 'tbody', 'tr', 'th', 'td',
'blockquote', 'br'
],
allowedAttributes: {
'a': ['href'],
'pre': ['class', 'data-language'],
'code': ['class', 'data-language'],
'div': ['class'],
'span': ['class']
}
});
// Convert to markdown using TurndownService
return this.turndownService.turndown(cleanHtml).trim();
}
async parseSitemap(sitemapUrl: string, logger: Logger): Promise<Map<string, string | undefined>> {
logger.info(`Parsing sitemap from ${sitemapUrl}`);
try {
const response = await axios.get(sitemapUrl);
const $ = load(response.data, { xmlMode: true });
const urlMap = new Map<string, string | undefined>();
// Handle standard sitemaps — extract <loc> and optional <lastmod>
$('url').each((_, element) => {
const loc = $(element).find('loc').text().trim();
const lastmod = $(element).find('lastmod').text().trim() || undefined;
if (loc) {
urlMap.set(loc, lastmod);
}
});
// Handle sitemap indexes (sitemaps that link to other sitemaps)
const sitemapLinks: string[] = [];
$('sitemap > loc').each((_, element) => {
const nestedSitemapUrl = $(element).text().trim();
if (nestedSitemapUrl) {
sitemapLinks.push(nestedSitemapUrl);
}
});
// Recursively process nested sitemaps
for (const nestedSitemapUrl of sitemapLinks) {
logger.debug(`Found nested sitemap: ${nestedSitemapUrl}`);
const nestedMap = await this.parseSitemap(nestedSitemapUrl, logger);
for (const [url, lastmod] of nestedMap) {
urlMap.set(url, lastmod);
}
}
const withLastmod = [...urlMap.values()].filter(v => v !== undefined).length;
logger.info(`Found ${urlMap.size} URLs in sitemap ${sitemapUrl} (${withLastmod} with lastmod)`);
return urlMap;
} catch (error) {
logger.error(`Error parsing sitemap at ${sitemapUrl}:`, error);
return new Map();
}
}
async crawlWebsite(
baseUrl: string,
sourceConfig: WebsiteSourceConfig,
processPageContent: (url: string, content: string) => Promise<boolean>,
parentLogger: Logger,
visitedUrls: Set<string>,
options?: {
knownUrls?: Set<string>;
etagStore?: {
get: (url: string) => Promise<string | undefined>;
set: (url: string, etag: string) => Promise<void>;
};
lastmodStore?: {
get: (url: string) => Promise<string | undefined>;
set: (url: string, lastmod: string) => Promise<void>;
};
// When the Postgres markdown store is enabled, this set contains
// URLs that already have markdown stored. URLs NOT in this set
// bypass lastmod/ETag skip logic so that the store is fully
// populated on the first sync.
markdownStoreUrls?: Set<string>;
// When true, bypass all lastmod/ETag skip logic. Used when a
// previous sync was interrupted or never completed successfully,
// ensuring every page is processed at least once.
forceFullSync?: boolean;
}
): Promise<{ hasNetworkErrors: boolean; brokenLinks: BrokenLink[]; notFoundUrls: Set<string> }> {
const logger = parentLogger.child('crawler');
const queue: string[] = [baseUrl];
const brokenLinks: BrokenLink[] = [];
const brokenLinkKeys: Set<string> = new Set();
const notFoundUrls: Set<string> = new Set();
const referrers: Map<string, Set<string>> = new Map();
const addReferrer = (targetUrl: string, sourceUrl: string) => {
const existing = referrers.get(targetUrl);
if (existing) {
existing.add(sourceUrl);
} else {
referrers.set(targetUrl, new Set([sourceUrl]));
}
};
const addBrokenLink = (sourceUrl: string, targetUrl: string) => {
const key = `${sourceUrl} -> ${targetUrl}`;
if (brokenLinkKeys.has(key)) return;
brokenLinkKeys.add(key);
brokenLinks.push({ source: sourceUrl, target: targetUrl });
};
addReferrer(baseUrl, baseUrl);
const { knownUrls, etagStore, lastmodStore, markdownStoreUrls, forceFullSync } = options ?? {};
// Pre-seed queue with previously-known URLs so link discovery isn't lost
// when pages are skipped via ETag/lastmod matching on re-runs
if (knownUrls && knownUrls.size > 0) {
for (const url of knownUrls) {
if (url.startsWith(sourceConfig.url) && !queue.includes(url)) {
queue.push(url);
}
}
logger.info(`Pre-seeded ${knownUrls.size} known URLs from database into crawl queue`);
}
// Process sitemap if provided — extract URLs and lastmod dates
// The lastmod map is used later in the crawl loop for change detection
const sitemapLastmod = new Map<string, string>();
if (sourceConfig.sitemap_url) {
logger.section('SITEMAP PROCESSING');
const sitemapData = await this.parseSitemap(sourceConfig.sitemap_url, logger);
// Collect parent URLs that have lastmod (directories ending with /)
// so we can inherit lastmod for child URLs that lack their own.
// Example: /gloo-mesh/2.10.x/ has lastmod but /gloo-mesh/2.10.x/reference/... doesn't.
const parentLastmods: Array<{ prefix: string; lastmod: string }> = [];
// First pass: add URLs to queue and collect explicit lastmod values
for (const [url, lastmod] of sitemapData) {
if (url.startsWith(sourceConfig.url)) {
addReferrer(url, sourceConfig.sitemap_url);
if (lastmod) {
sitemapLastmod.set(url, lastmod);
// Track as a potential parent for child URL inheritance
if (url.endsWith('/')) {
parentLastmods.push({ prefix: url, lastmod });
}
}
if (!queue.includes(url)) {
logger.debug(`Adding URL from sitemap to queue: ${url}`);
queue.push(url);
}
}
}
// Second pass: inherit lastmod from the most specific parent for URLs
// that don't have their own lastmod
if (parentLastmods.length > 0) {
// Sort by prefix length descending so longest (most specific) match wins
parentLastmods.sort((a, b) => b.prefix.length - a.prefix.length);
let inheritedCount = 0;
for (const [url] of sitemapData) {
if (url.startsWith(sourceConfig.url) && !sitemapLastmod.has(url)) {
const parent = parentLastmods.find(p => url.startsWith(p.prefix));
if (parent) {
sitemapLastmod.set(url, parent.lastmod);
inheritedCount++;
}
}
}
if (inheritedCount > 0) {
logger.info(`Inherited lastmod from parent URLs for ${inheritedCount} child URLs without their own lastmod`);
}
}
logger.info(`Added ${queue.length - 1} URLs from sitemap to the crawl queue (${sitemapLastmod.size} with lastmod)`);
}
logger.info(`Starting crawl from ${baseUrl} with ${queue.length} URLs in initial queue`);
let processedCount = 0;
let skippedCount = 0;
let skippedSizeCount = 0;
let etagSkippedCount = 0;
let lastmodSkippedCount = 0;
let pdfProcessedCount = 0;
let errorCount = 0;
let hasNetworkErrors = false;
// Tracks whether the server supports ETags. Starts true and is set to false
// after a few consecutive successful HEAD responses return no ETag header,
// avoiding wasted HEAD requests for servers that don't support ETags.
// HEAD request failures (network errors, timeouts) do NOT count toward
// this threshold — they're transient issues, not evidence of missing ETag support.
let serverSupportsEtags = true;
let consecutiveMissingEtag = 0;
const MISSING_ETAG_THRESHOLD = 3;
// Track per-URL retry counts for rate limiting (429) responses
const retryCounts: Map<string, number> = new Map();
const MAX_RETRIES_PER_URL = 3;
const DEFAULT_RETRY_DELAY_MS = 30000; // 30s default when no Retry-After header
const MAX_RETRY_DELAY_MS = 120000; // Cap at 2 minutes
// Adaptive backoff for HEAD requests: starts at 0 (no delay), increases
// on 429 responses, and decays back toward 0 on successful responses.
let headBackoffMs = 0;
const HEAD_BACKOFF_INITIAL_MS = 200; // First backoff step after a 429
const HEAD_BACKOFF_MAX_MS = 5000; // Cap at 5 seconds
const HEAD_BACKOFF_DECAY_FACTOR = 0.5; // Halve delay on each success
const HEAD_BACKOFF_FLOOR_MS = 10; // Below this, snap to 0
// Launch a single browser instance and reuse one page (tab) for all URLs
let browser: Browser | null = null;
let page: Page | null = null;
const launchBrowser = async (): Promise<{ browser: Browser; page: Page }> => {
let executablePath: string | undefined = process.env.PUPPETEER_EXECUTABLE_PATH;
if (!executablePath) {
if (fs.existsSync('/usr/bin/chromium')) {
executablePath = '/usr/bin/chromium';
} else if (fs.existsSync('/usr/bin/chromium-browser')) {
executablePath = '/usr/bin/chromium-browser';
}
}
const b = await puppeteer.launch({
executablePath,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage', // Use /tmp instead of /dev/shm (critical in Docker, default 64MB)
'--disable-gpu',
'--disable-extensions',
],
protocolTimeout: 60000,
});
const p = await b.newPage();
return { browser: b, page: p };
};
// Track whether the page needs to be recreated (e.g., after a timeout error)
let pageNeedsRecreation = false;
// Track consecutive protocol-level errors (indicates browser process is degraded)
let consecutiveProtocolErrors = 0;
// Track pages processed since the last browser (re)launch for periodic restarts
let pagesSinceRestart = 0;
// Restart the browser every N pages to prevent memory accumulation
const PAGES_BETWEEN_RESTARTS = 50;
const restartBrowser = async (reason: string): Promise<void> => {
logger.warn(`Restarting browser: ${reason}`);
if (browser) {
try { await browser.close(); } catch { /* ignore close errors on a degraded browser */ }
}
const launched = await launchBrowser();
browser = launched.browser;
page = launched.page;
pageNeedsRecreation = false;
consecutiveProtocolErrors = 0;
pagesSinceRestart = 0;
};
const ensureBrowser = async (): Promise<Page> => {
// If protocol errors are persisting after page recreation, the browser
// process itself is degraded — a full restart is needed.
const needsBrowserRestart = pageNeedsRecreation && consecutiveProtocolErrors >= 1;
if (!browser || !browser.isConnected() || needsBrowserRestart) {
const reason = needsBrowserRestart
? `protocol errors persisting after page recreation (${consecutiveProtocolErrors} consecutive)`
: browser ? 'browser disconnected' : 'initial launch';
await restartBrowser(reason);
} else if (pagesSinceRestart >= PAGES_BETWEEN_RESTARTS) {
// Periodic restart to prevent memory accumulation from long crawls
await restartBrowser(`periodic restart after ${pagesSinceRestart} pages`);
} else if (pageNeedsRecreation) {
// The previous page.evaluate or navigation timed out / errored.
// Close the stale page and create a fresh one to avoid corrupted state.
logger.info('Recreating page after previous error...');
try {
if (page) await page.close();
} catch {
// Ignore errors closing a stale page
}
page = await browser.newPage();
pageNeedsRecreation = false;
}
return page!;
};
try {
while (queue.length > 0) {
const url = queue.shift();
if (!url) continue;
const normalizedUrl = Utils.normalizeUrl(url);
if (visitedUrls.has(normalizedUrl)) continue;
visitedUrls.add(normalizedUrl);
if (!Utils.shouldProcessUrl(url)) {
logger.debug(`Skipping URL with unsupported extension: ${url}`);
skippedCount++;
continue;
}
// Sitemap lastmod-based skip: if the sitemap provides a lastmod date for
// this URL and it matches the stored value, skip entirely. This avoids
// both HEAD requests and full page loads — the sitemap is fetched once
// for the entire crawl.
// Bypass this skip when:
// - forceFullSync is true (previous sync never completed)
// - markdownStoreUrls is set and the URL is not in it (markdown store gap)
const urlLastmod = sitemapLastmod.get(url);
const urlInMarkdownStore = !markdownStoreUrls || markdownStoreUrls.has(url);
if (urlLastmod && lastmodStore) {
const storedLastmod = await lastmodStore.get(url);
if (storedLastmod && storedLastmod === urlLastmod) {
if (forceFullSync) {
logger.info(`Lastmod unchanged but full sync not yet completed, forcing processing: ${url}`);
} else if (!urlInMarkdownStore) {
logger.info(`Lastmod unchanged but URL not in markdown store, forcing processing: ${url}`);
} else {
logger.info(`Lastmod unchanged (${urlLastmod}), skipping: ${url}`);
visitedUrls.add(url);
lastmodSkippedCount++;
continue;
}
} else if (storedLastmod) {
logger.debug(`Lastmod changed (stored: ${storedLastmod}, sitemap: ${urlLastmod}), processing: ${url}`);
} else {
logger.debug(`No stored lastmod for ${url}, processing`);
}
}
// ETag-based skip: send a lightweight HEAD request and compare the ETag
// to the stored value. If unchanged, skip the entire page (no Puppeteer,
// no content extraction, no chunking, no embedding).
// Skip ETag check if the URL has a lastmod from the sitemap — we trust
// lastmod as the primary change-detection signal when available.
if (!urlLastmod && !Utils.isPdfUrl(url) && etagStore && serverSupportsEtags) {
// Adaptive backoff: wait before HEAD if we've been rate-limited recently
if (headBackoffMs > 0) {
await new Promise(resolve => setTimeout(resolve, headBackoffMs));
}
const headConfig = {
timeout: 10000,
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; doc2vec crawler)' },
maxRedirects: 5,
};
// Checks an ETag from a HEAD response against the stored value.
// Returns 'skip' if unchanged, 'process' if changed/missing, 'no-etag' if header absent.
const checkEtag = async (etag: string | undefined): Promise<'skip' | 'process' | 'no-etag'> => {
if (!etag) return 'no-etag';
consecutiveMissingEtag = 0;
const storedEtag = await etagStore.get(url);
if (storedEtag && storedEtag === etag) {
return 'skip';
} else if (storedEtag) {
logger.debug(`ETag changed (stored: ${storedEtag}, received: ${etag}), processing: ${url}`);
} else {
logger.debug(`No stored ETag for ${url}, processing`);
}
return 'process';
};
// Decay backoff on successful HEAD (non-429)
const decayBackoff = () => {
if (headBackoffMs > 0) {
headBackoffMs = headBackoffMs * HEAD_BACKOFF_DECAY_FACTOR;
if (headBackoffMs < HEAD_BACKOFF_FLOOR_MS) {
headBackoffMs = 0;
logger.debug('HEAD backoff decayed to 0ms');
}
}
};
// Increase backoff on 429
const increaseBackoff = () => {
const previousMs = headBackoffMs;
headBackoffMs = headBackoffMs === 0
? HEAD_BACKOFF_INITIAL_MS
: Math.min(headBackoffMs * 2, HEAD_BACKOFF_MAX_MS);
logger.debug(`HEAD backoff increased: ${previousMs}ms → ${headBackoffMs}ms`);
};
try {
const headResponse = await axios.head(url, headConfig);
decayBackoff();
const result = await checkEtag(headResponse.headers['etag']);
if (result === 'skip') {
// Bypass ETag skip when:
// - forceFullSync is true (previous sync never completed)
// - markdownStoreUrls is set and URL is not in it
if (forceFullSync) {
logger.info(`ETag unchanged but full sync not yet completed, forcing processing: ${url}`);
} else if (!urlInMarkdownStore) {
logger.info(`ETag unchanged but URL not in markdown store, forcing processing: ${url}`);
} else {
logger.info(`ETag unchanged, skipping: ${url}`);
visitedUrls.add(url);
etagSkippedCount++;
continue;
}
} else if (result === 'no-etag') {
consecutiveMissingEtag++;
logger.debug(`No ETag in HEAD response for ${url} (${consecutiveMissingEtag}/${MISSING_ETAG_THRESHOLD})`);
if (consecutiveMissingEtag >= MISSING_ETAG_THRESHOLD) {
serverSupportsEtags = false;
logger.warn(`Server does not return ETag headers (${MISSING_ETAG_THRESHOLD} consecutive pages without ETag). Disabling ETag-based skip for this crawl.`);
}
}
} catch (headError: any) {
// If the HEAD request was rate-limited (429), increase backoff,
// wait, and retry once. The backoff ensures subsequent HEAD
// requests are spaced out to avoid further 429s.
const headStatus = headError?.response?.status;
if (headStatus === 429) {
increaseBackoff();
const retryAfterMs = this.parseRetryAfter(headError.response?.headers?.['retry-after']);
const delayMs = Math.min(retryAfterMs ?? 5000, 30000);
logger.debug(`HEAD rate-limited (429) for ${url}, waiting ${Math.round(delayMs / 1000)}s before retry`);
await new Promise(resolve => setTimeout(resolve, delayMs));
try {
const retryResponse = await axios.head(url, headConfig);
decayBackoff();
const result = await checkEtag(retryResponse.headers['etag']);
if (result === 'skip') {
if (forceFullSync) {
logger.info(`ETag unchanged but full sync not yet completed, forcing processing: ${url}`);
} else if (!urlInMarkdownStore) {
logger.info(`ETag unchanged but URL not in markdown store, forcing processing: ${url}`);
} else {
logger.info(`ETag unchanged, skipping: ${url}`);
visitedUrls.add(url);
etagSkippedCount++;
continue;
}
}
// 'process' or 'no-etag' — fall through to full processing
} catch {
logger.debug(`HEAD retry also failed for ${url}, falling through to full processing`);
}
} else if (headStatus && headStatus >= 400 && headStatus < 500 && headStatus !== 405) {
// Client error (404, 403, 410, etc.) — the page doesn't
// exist or is inaccessible. Skip instead of wasting a
// full Puppeteer load on a non-existent page.
// 405 (Method Not Allowed) is excluded because the server
// may not support HEAD but the page may still exist via GET.
logger.debug(`HEAD returned ${headStatus} for ${url}, skipping`);
if (headStatus === 404) {
notFoundUrls.add(url);
}
skippedCount++;
continue;
} else {
// Non-HTTP failure (network error, timeout), 5xx server
// error, or 405 — fall through to full processing.
// Do NOT count toward the missing-ETag threshold.
logger.debug(`HEAD request failed for ${url}: ${headError?.message || headError}. Falling through to full processing.`);
}
}
}
try {
logger.info(`Crawling: ${url}`);
const sources = referrers.get(url) ?? new Set([baseUrl]);
// For HTML pages, ensure the browser is running and pass the shared page
// For PDFs, processPage handles them without Puppeteer
const currentPage = Utils.isPdfUrl(url) ? undefined : await ensureBrowser();
const result = await this.processPage(url, sourceConfig, (reportedUrl, status) => {
if (status === 404) {
for (const source of sources) {
addBrokenLink(source, reportedUrl);
}
}
}, currentPage);
let contentProcessedSuccessfully = false;
if (result.content !== null) {
contentProcessedSuccessfully = await processPageContent(url, result.content);
if (Utils.isPdfUrl(url)) {
pdfProcessedCount++;
} else {
processedCount++;
}
} else {
skippedSizeCount++;
}
// Use links extracted from the full rendered DOM by processPage
// (no separate axios request needed)
if (result.links.length > 0) {
const pageUrlForLinks = result.finalUrl || url;
logger.debug(`Finding links on page ${url}`);
let newLinksFound = 0;
for (const href of result.links) {
const fullUrl = Utils.buildUrl(href, pageUrlForLinks, logger);
if (fullUrl.startsWith(sourceConfig.url)) {
addReferrer(fullUrl, pageUrlForLinks);
if (!visitedUrls.has(Utils.normalizeUrl(fullUrl))) {
if (!queue.includes(fullUrl)) {
queue.push(fullUrl);
newLinksFound++;
}
}
}
}
logger.debug(`Found ${newLinksFound} new links on ${url}`);
}
// Only store ETag/lastmod when content was processed successfully.
// If chunking or embedding failed, we want the next run to retry
// this page rather than skipping it based on stale metadata.
if (contentProcessedSuccessfully) {
// Store the ETag for this URL so subsequent runs can skip it
if (result.etag && etagStore) {
try {
await etagStore.set(url, result.etag);
} catch {
// ETag storage failure is non-critical
}
}
// Store the sitemap lastmod for this URL so subsequent runs can
// skip it without any HTTP requests when the lastmod hasn't changed
if (urlLastmod && lastmodStore) {
try {
await lastmodStore.set(url, urlLastmod);
} catch {
// Lastmod storage failure is non-critical
}
}
}
// Page processed successfully — reset protocol error counter and
// increment the periodic restart counter
consecutiveProtocolErrors = 0;
if (!Utils.isPdfUrl(url)) {
pagesSinceRestart++;
}
// Navigate to about:blank to clear any lingering JS, timers, or
// event listeners from the processed page before moving to the next URL.
if (currentPage) {
try {
await currentPage.goto('about:blank', { waitUntil: 'load', timeout: 5000 });
} catch {
// If even about:blank fails, the page is stuck — mark for recreation
pageNeedsRecreation = true;
}
}
} catch (error: any) {
const status = this.getHttpStatus(error);
// ── Handle 429 (Too Many Requests) with retry ──
if (status === 429) {
const retries = retryCounts.get(url) ?? 0;
if (retries < MAX_RETRIES_PER_URL) {
const retryAfterMs = error.retryAfterMs as number | undefined;
const delayMs = Math.min(
retryAfterMs ?? DEFAULT_RETRY_DELAY_MS,
MAX_RETRY_DELAY_MS
);
retryCounts.set(url, retries + 1);
logger.warn(
`Rate limited (429) on ${url} (attempt ${retries + 1}/${MAX_RETRIES_PER_URL}). ` +
`Waiting ${Math.round(delayMs / 1000)}s before retry...`
);
await new Promise(resolve => setTimeout(resolve, delayMs));
// Re-add to the front of the queue so it's retried next.
// Remove from visitedUrls so it's not skipped.
visitedUrls.delete(normalizedUrl);
queue.unshift(url);
// Do NOT set pageNeedsRecreation — the page/browser is healthy,
// the server is just rate-limiting us.
// Do NOT increment errorCount — this is a temporary condition.
continue;
}
// Max retries exhausted — fall through to normal error handling
logger.error(`Rate limit retries exhausted for ${url} after ${MAX_RETRIES_PER_URL} attempts`);
}
// ── General error handling ──
logger.error(`Failed during processing or link discovery for ${url}:`, error);
errorCount++;
// Mark the page for recreation so the next URL gets a clean tab.
// This prevents cascading failures from a stuck/corrupted page state.
pageNeedsRecreation = true;
// Track protocol-level errors separately — these indicate the browser
// process itself is degraded, not just the page. If they persist after
// page recreation, ensureBrowser() will escalate to a full browser restart.
if (this.isProtocolError(error)) {
consecutiveProtocolErrors++;
logger.warn(`Protocol error detected (${consecutiveProtocolErrors} consecutive), browser may need restart`);
} else {
consecutiveProtocolErrors = 0;
}
if (status === 404) {
const sources = referrers.get(url) ?? new Set([baseUrl]);
for (const source of sources) {
addBrokenLink(source, url);
}
}
// Check if this is a network error (DNS resolution, connection issues, etc.)
if (this.isNetworkError(error)) {
hasNetworkErrors = true;
logger.warn(`Network error detected for ${url}, this may affect cleanup decisions`);
}
}
}
} finally {
// Close the shared browser instance when the crawl is done
const browserToClose = browser as Browser | null;
if (browserToClose && browserToClose.isConnected()) {
await browserToClose.close();
logger.debug('Shared browser closed after crawl completed');
}
}
logger.info(`Crawl completed. HTML Pages: ${processedCount}, PDFs: ${pdfProcessedCount}, Skipped (Lastmod): ${lastmodSkippedCount}, Skipped (ETag): ${etagSkippedCount}, Skipped (Extension): ${skippedCount}, Skipped (Size): ${skippedSizeCount}, Errors: ${errorCount}`);
if (hasNetworkErrors) {
logger.warn('Network errors were encountered during crawling. Cleanup may be skipped to avoid removing valid chunks.');
}
return { hasNetworkErrors, brokenLinks, notFoundUrls };
}
/**
* Detects Chrome DevTools Protocol-level errors that indicate the browser
* process is degraded/stuck (not just a single page issue).
* These errors cannot be fixed by page recreation alone — the browser needs a full restart.
*/
private isProtocolError(error: any): boolean {
const msg = error?.message || '';
return msg.includes('ProtocolError') ||
msg.includes('Protocol error') ||
(msg.includes('timed out') && msg.includes('protocolTimeout')) ||
msg.includes('Target closed') ||
msg.includes('Session closed') ||
msg.includes('Network.enable timed out') ||
msg.includes('Connection closed');
}
private isNetworkError(error: any): boolean {
// Check for common network error patterns
if (error?.code) {
// DNS resolution errors
if (error.code === 'ENOTFOUND') return true;
// Connection refused
if (error.code === 'ECONNREFUSED') return true;
// Connection timeout
if (error.code === 'ETIMEDOUT') return true;
// Connection reset
if (error.code === 'ECONNRESET') return true;
// Host unreachable
if (error.code === 'EHOSTUNREACH') return true;
// Network unreachable
if (error.code === 'ENETUNREACH') return true;
}
// Check for axios-specific network errors
if (error?.isAxiosError) {
// If there's no response, it's likely a network error
if (!error.response) return true;
}
// Check error message for network-related terms
const errorMessage = error?.message?.toLowerCase() || '';
if (errorMessage.includes('getaddrinfo') ||
errorMessage.includes('network') ||
errorMessage.includes('timeout') ||
errorMessage.includes('connection') ||
errorMessage.includes('dns')) {
return true;
}
return false;
}
async processPage(
url: string,
sourceConfig: SourceConfig,
onHttpStatus?: (url: string, status: number) => void,
existingPage?: Page
): Promise<{ content: string | null, links: string[], finalUrl: string, etag?: string }> {
const logger = this.logger.child('page-processor');
logger.debug(`Processing content from ${url}`);
// Check if this is a PDF URL
if (Utils.isPdfUrl(url)) {
logger.info(`Processing PDF: ${url}`);
try {
const markdown = await this.downloadAndConvertPdfFromUrl(url, logger);
// Check size limit for PDF content
if (markdown.length > sourceConfig.max_size) {
logger.warn(`PDF content (${markdown.length} chars) exceeds max size (${sourceConfig.max_size}). Skipping ${url}.`);
return { content: null, links: [], finalUrl: url };
}
return { content: markdown, links: [], finalUrl: url };
} catch (error) {
const status = this.getHttpStatus(error);
if (status !== undefined && status >= 400) {
if (onHttpStatus) {
onHttpStatus(url, status);
}
throw error;
}
logger.error(`Failed to process PDF ${url}:`, error);
return { content: null, links: [], finalUrl: url };
}
}
// HTML page processing logic
// If an existing page (tab) is provided, reuse it; otherwise launch a standalone browser
let browser: Browser | null = null;
let page: Page;
const ownsTheBrowser = !existingPage;
try {
if (existingPage) {
page = existingPage;
} else {
// Standalone mode: launch a browser for this single page
let executablePath: string | undefined = process.env.PUPPETEER_EXECUTABLE_PATH;
if (!executablePath) {
if (fs.existsSync('/usr/bin/chromium')) {
executablePath = '/usr/bin/chromium';
} else if (fs.existsSync('/usr/bin/chromium-browser')) {
executablePath = '/usr/bin/chromium-browser';
}
}
browser = await puppeteer.launch({
executablePath,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--disable-extensions',
],
protocolTimeout: 60000,
});
page = await browser.newPage();
}
logger.debug(`Navigating to ${url}`);
const response = await page.goto(url, { waitUntil: 'networkidle2', timeout: 60000 });
const status = response?.status();
if (status !== undefined && status >= 400) {
const error = new Error(`Failed to load page: HTTP ${status}`);
(error as any).status = status;
// For 429 (Too Many Requests), extract the Retry-After header so the
// caller can wait the right amount of time before retrying.
if (status === 429 && response) {
const retryAfterMs = this.parseRetryAfter(response.headers()['retry-after']);
if (retryAfterMs !== undefined) {
(error as any).retryAfterMs = retryAfterMs;
logger.info(`Rate limited (429). Retry-After: ${retryAfterMs}ms`);
} else {
logger.info(`Rate limited (429). No Retry-After header present.`);
}
}
throw error;
}
// Get the final URL after any redirects
const finalUrl = page.url();
// Extract ETag header for change detection on subsequent runs
const etag = response?.headers()['etag'] || undefined;
// Extract ALL links from the full rendered DOM before any content filtering
// This searches the entire document, not just the main content area
const links: string[] = await this.evaluateWithTimeout(page, () => {
const anchors = document.querySelectorAll('a[href]');
const hrefs: string[] = [];
anchors.forEach(a => {
const href = a.getAttribute('href');
if (href && !href.startsWith('#') && !href.startsWith('mailto:')) {
hrefs.push(href);
}
});
return hrefs;
});
logger.debug(`Extracted ${links.length} links from full DOM of ${url}`);
const htmlContent: string = await this.evaluateWithTimeout(page, () => {
// Try specific content selectors first, then fall back to broader ones
const mainContentElement =
document.querySelector('.docs-content') || // Common docs pattern
document.querySelector('.doc-content') || // Alternative docs pattern
document.querySelector('.markdown-body') || // GitHub-style
document.querySelector('article') || // Semantic article
document.querySelector('div[role="main"].document') ||
document.querySelector('main') ||
document.body;
return mainContentElement.innerHTML;
});
if (htmlContent.length > sourceConfig.max_size) {
logger.warn(`Raw HTML content (${htmlContent.length} chars) exceeds max size (${sourceConfig.max_size}). Skipping detailed processing for ${url}.`);
return { content: null, links, finalUrl, etag };
}
logger.debug(`Got HTML content (${htmlContent.length} chars), creating DOM`);
const dom = new JSDOM(htmlContent);
const document = dom.window.document;
document.querySelectorAll('pre').forEach((pre: HTMLElement) => {
pre.classList.add('article-content');
pre.setAttribute('data-readable-content-score', '100');
this.markCodeParents(pre.parentElement);
});
// Pre-process tabbed content: inject tab labels into panels
// and make hidden panels visible so Readability doesn't discard them.
// Done in JSDOM (not in Puppeteer's page.evaluate) to avoid triggering
// reactive framework re-renders when modifying data-state attributes.
this.preprocessTabs(document, logger);
// Extract H1s BEFORE Readability - it often strips them as "chrome"
// We'll inject them back after Readability processing