From 725352d43227c2e68b877d7884d3f61dccc3ddfa Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 21:57:28 -0700 Subject: [PATCH 1/3] move crawlers to their own files --- core/indexing/docs/DocsCrawler.ts | 479 +----------------- core/indexing/docs/crawlers/CheerioCrawler.ts | 146 ++++++ .../indexing/docs/crawlers/ChromiumCrawler.ts | 260 ++++++++++ core/indexing/docs/crawlers/DefaultCrawler.ts | 5 + core/indexing/docs/crawlers/GitHubCrawler.ts | 80 +++ 5 files changed, 494 insertions(+), 476 deletions(-) create mode 100644 core/indexing/docs/crawlers/CheerioCrawler.ts create mode 100644 core/indexing/docs/crawlers/ChromiumCrawler.ts create mode 100644 core/indexing/docs/crawlers/DefaultCrawler.ts create mode 100644 core/indexing/docs/crawlers/GitHubCrawler.ts diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 19300cd0b..a30f99471 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -1,18 +1,10 @@ -import { Octokit } from "@octokit/rest"; -import * as cheerio from "cheerio"; -import * as fs from "fs"; -import fetch from "node-fetch"; import { URL } from "node:url"; -import { Handler, HTTPResponse, Page } from "puppeteer"; -import { - editConfigJson, - getChromiumPath, - getContinueUtilsPath, -} from "../../util/paths"; // @ts-ignore // @prettier-ignore -import PCR from "puppeteer-chromium-resolver"; import { ContinueConfig, IDE } from "../.."; +import CheerioCrawler from "./crawlers/CheerioCrawler"; +import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; +import GitHubCrawler from "./crawlers/GitHubCrawler"; export type PageData = { url: string; @@ -83,471 +75,6 @@ class DocsCrawler { } } -class GitHubCrawler { - private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); - private octokit = new Octokit({ auth: undefined }); - - constructor(private readonly startUrl: URL) {} - - async *crawl(): AsyncGenerator { - console.debug( - `[${ - (this.constructor as any).name - }] Crawling GitHub repo: ${this.startUrl.toString()}`, - ); - const urlStr = this.startUrl.toString(); - const [_, owner, repo] = this.startUrl.pathname.split("/"); - const branch = await this.getGithubRepoDefaultBranch(owner, repo); - const paths = await this.getGitHubRepoPaths(owner, repo, branch); - - for await (const path of paths) { - const content = await this.getGithubRepoFileContent(path, owner, repo); - yield { path, url: urlStr, content: content ?? "" }; - } - } - - private async getGithubRepoDefaultBranch( - owner: string, - repo: string, - ): Promise { - const repoInfo = await this.octokit.repos.get({ owner, repo }); - return repoInfo.data.default_branch; - } - - private async getGitHubRepoPaths( - owner: string, - repo: string, - branch: string, - ) { - const tree = await this.octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { "X-GitHub-Api-Version": "2022-11-28" }, - recursive: "true", - }, - ); - - return tree.data.tree - .filter( - (file: any) => - file.type === "blob" && this.markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => file.path); - } - - private async getGithubRepoFileContent( - path: string, - owner: string, - repo: string, - ) { - try { - const response = await this.octokit.repos.getContent({ - owner, - repo, - path, - headers: { Accept: "application/vnd.github.raw+json" }, - }); - return response.data as unknown as string; - } catch (error) { - console.debug("Error fetching file contents:", error); - return null; - } - } -} - -class CheerioCrawler { - private readonly IGNORE_PATHS_ENDING_IN = [ - "favicon.ico", - "robots.txt", - ".rst.txt", - "genindex", - "py-modindex", - "search.html", - "search", - "genindex.html", - "changelog", - "changelog.html", - ]; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - async *crawl(): AsyncGenerator { - yield* this.crawlPage(this.startUrl); - } - - private async *crawlPage( - url: URL, - maxDepth: number = 3, - ): AsyncGenerator { - console.log( - `[${ - (this.constructor as any).name - }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, - ); - - const { baseUrl, basePath } = this.splitUrl(url); - - let paths: { path: string; depth: number }[] = [ - { path: basePath, depth: 0 }, - ]; - - let index = 0; - - while (index < paths.length) { - const batch = paths.slice(index, index + 50); - - try { - const promises = batch.map(({ path, depth }) => - this.getLinksFromUrl(baseUrl, path).then((links) => ({ - links, - path, - depth, - })), - ); - - const results = await Promise.all(promises); - for (const { - links: { html, links: linksArray }, - path, - depth, - } of results) { - if (html !== "" && depth <= maxDepth) { - yield { url: url.toString(), path, content: html }; - } - - if (depth < maxDepth) { - for (let link of linksArray) { - if (!paths.some((p) => p.path === link)) { - paths.push({ path: link, depth: depth + 1 }); - } - } - } - } - } catch (e) { - console.debug("Error while crawling page: ", e); - } - - index += batch.length; - } - - console.log("Crawl completed"); - } - - private async getLinksFromUrl(url: string, path: string) { - const baseUrl = new URL(url); - const location = new URL(path, url); - let response; - - try { - response = await fetch(location.toString()); - } catch (error: unknown) { - if ( - error instanceof Error && - error.message.includes("maximum redirect") - ) { - console.error( - `[${ - (this.constructor as any).name - }] Maximum redirect reached for: ${location.toString()}`, - ); - return { html: "", links: [] }; - } - console.error(error); - return { html: "", links: [] }; - } - if (!response.ok) { - return { html: "", links: [] }; - } - const html = await response.text(); - let links: string[] = []; - - if (url.includes("github.com")) { - return { html, links }; - } - - const $ = cheerio.load(html); - - $("a").each((_: any, element: any) => { - const href = $(element).attr("href"); - if (!href) { - return; - } - - const parsedUrl = new URL(href, location); - if (parsedUrl.hostname === baseUrl.hostname) { - links.push(parsedUrl.pathname); - } - }); - - links = [...new Set(links)].filter((link) => { - return ( - !link.includes("#") && - !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) - ); - }); - return { html, links }; - } - - private splitUrl(url: URL) { - const baseUrl = new URL('/', url).href; - const basePath = url.pathname; - return { baseUrl, basePath }; - } -} - -class ChromiumCrawler { - private readonly LINK_GROUP_SIZE = 2; - private curCrawlCount = 0; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { - editConfigJson((config) => ({ - ...config, - experimental: { - ...config.experimental, - useChromiumForDocsCrawling, - }, - })); - } - - async *crawl(): AsyncGenerator { - console.debug( - `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, - ); - - const stats = await PCR(ChromiumInstaller.PCR_CONFIG); - const browser = await stats.puppeteer.launch({ - args: [ - "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", - ], - executablePath: stats.executablePath, - }); - const page = await browser.newPage(); - - try { - yield* this.crawlSitePages(page, this.startUrl); - } catch (e) { - console.debug("Error getting links: ", e); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - } finally { - await browser.close(); - } - } - - /** - * We need to handle redirects manually, otherwise there are race conditions. - * - * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 - */ - private async gotoPageAndHandleRedirects(page: Page, url: string) { - const MAX_PAGE_WAIT_MS = 5000; - - await page.goto(url, { - timeout: 0, - waitUntil: "networkidle2", - }); - - let responseEventOccurred = false; - const responseHandler: Handler = (event) => - (responseEventOccurred = true); - - const responseWatcher = new Promise(function (resolve, reject) { - setTimeout(() => { - if (!responseEventOccurred) { - resolve(); - } else { - setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); - } - }, 500); - }); - - page.on("response", responseHandler); - - await Promise.race([responseWatcher, page.waitForNavigation()]); - } - - private async *crawlSitePages( - page: Page, - curUrl: URL, - visitedLinks: Set = new Set(), - ): AsyncGenerator { - const urlStr = curUrl.toString(); - - if (visitedLinks.has(urlStr)) { - return; - } - - await this.gotoPageAndHandleRedirects(page, urlStr); - - const htmlContent = await page.content(); - const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); - this.curCrawlCount++; - - visitedLinks.add(urlStr); - - yield { - path: curUrl.pathname, - url: urlStr, - content: htmlContent, - }; - - for (const linkGroup of linkGroups) { - let enqueuedLinkCount = this.curCrawlCount; - - for (const link of linkGroup) { - enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); - if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { - yield* this.crawlSitePages(page, new URL(link), visitedLinks); - } - } - } - } - - private stripHashFromUrl(urlStr: string) { - try { - let url = new URL(urlStr); - url.hash = ""; - return url; - } catch (err) { - return null; - } - } - - private isValidHostAndPath(newUrl: URL, curUrl: URL) { - return ( - newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host - ); - } - - private async getLinksFromPage(page: Page, curUrl: URL) { - const links = await page.$$eval("a", (links) => links.map((a) => a.href)); - - const cleanedLinks = links - .map(this.stripHashFromUrl) - .filter( - (newUrl) => - newUrl !== null && - this.isValidHostAndPath(newUrl, curUrl) && - newUrl !== curUrl, - ) - .map((newUrl) => (newUrl as URL).href); - - const dedupedLinks = Array.from(new Set(cleanedLinks)); - - return dedupedLinks; - } - - private async getLinkGroupsFromPage(page: Page, curUrl: URL) { - const links = await this.getLinksFromPage(page, curUrl); - - const groups = links.reduce((acc, link, i) => { - const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); - - if (!acc[groupIndex]) { - acc.push([]); - } - - acc[groupIndex].push(link); - - return acc; - }, [] as string[][]); - - return groups; - } -} - -class ChromiumInstaller { - static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; - - constructor( - private readonly ide: IDE, - private readonly config: ContinueConfig, - ) { - if (this.shouldInstallOnStartup()) { - console.log("Installing Chromium"); - void this.install(); - } - } - - isInstalled() { - return fs.existsSync(getChromiumPath()); - } - - shouldInstallOnStartup() { - return ( - !this.isInstalled() && - this.config.experimental?.useChromiumForDocsCrawling - ); - } - - shouldProposeUseChromiumOnCrawlFailure() { - const { experimental } = this.config; - - return ( - experimental?.useChromiumForDocsCrawling === undefined || - experimental.useChromiumForDocsCrawling - ); - } - - async proposeAndAttemptInstall(site: string) { - const userAcceptedInstall = await this.proposeInstall(site); - - if (userAcceptedInstall) { - const didInstall = await this.install(); - return didInstall; - } - } - - async install() { - try { - await PCR(ChromiumInstaller.PCR_CONFIG); - - ChromiumCrawler.setUseChromiumForDocsCrawling(true); - - return true; - } catch (error) { - console.debug("Error installing Chromium : ", error); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - - await this.ide.showToast("error", "Failed to install Chromium"); - - return false; - } - } - - private async proposeInstall(site: string) { - const msg = - `Unable to crawl documentation site: ${site}\n` + - "We recommend installing Chromium. " + - "Download progress can be viewed in the developer console."; - - const actionMsg = "Install Chromium"; - - const res = await this.ide.showToast("warning", msg, actionMsg); - - return res === actionMsg; - } -} - export default DocsCrawler; export { CheerioCrawler, diff --git a/core/indexing/docs/crawlers/CheerioCrawler.ts b/core/indexing/docs/crawlers/CheerioCrawler.ts new file mode 100644 index 000000000..df3eaf1bd --- /dev/null +++ b/core/indexing/docs/crawlers/CheerioCrawler.ts @@ -0,0 +1,146 @@ +import * as cheerio from "cheerio"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +export default class CheerioCrawler { + private readonly IGNORE_PATHS_ENDING_IN = [ + "favicon.ico", + "robots.txt", + ".rst.txt", + "genindex", + "py-modindex", + "search.html", + "search", + "genindex.html", + "changelog", + "changelog.html", + ]; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + async *crawl(): AsyncGenerator { + yield* this.crawlPage(this.startUrl); + } + + private async *crawlPage( + url: URL, + maxDepth: number = 3, + ): AsyncGenerator { + console.log( + `[${ + (this.constructor as any).name + }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, + ); + + const { baseUrl, basePath } = this.splitUrl(url); + + let paths: { path: string; depth: number }[] = [ + { path: basePath, depth: 0 }, + ]; + + let index = 0; + + while (index < paths.length) { + const batch = paths.slice(index, index + 50); + + try { + const promises = batch.map(({ path, depth }) => + this.getLinksFromUrl(baseUrl, path).then((links) => ({ + links, + path, + depth, + })), + ); + + const results = await Promise.all(promises); + for (const { + links: { html, links: linksArray }, + path, + depth, + } of results) { + if (html !== "" && depth <= maxDepth) { + yield { url: url.toString(), path, content: html }; + } + + if (depth < maxDepth) { + for (let link of linksArray) { + if (!paths.some((p) => p.path === link)) { + paths.push({ path: link, depth: depth + 1 }); + } + } + } + } + } catch (e) { + console.debug("Error while crawling page: ", e); + } + + index += batch.length; + } + + console.log("Crawl completed"); + } + + private async getLinksFromUrl(url: string, path: string) { + const baseUrl = new URL(url); + const location = new URL(path, url); + let response; + + try { + response = await fetch(location.toString()); + } catch (error: unknown) { + if ( + error instanceof Error && + error.message.includes("maximum redirect") + ) { + console.error( + `[${ + (this.constructor as any).name + }] Maximum redirect reached for: ${location.toString()}`, + ); + return { html: "", links: [] }; + } + console.error(error); + return { html: "", links: [] }; + } + if (!response.ok) { + return { html: "", links: [] }; + } + const html = await response.text(); + let links: string[] = []; + + if (url.includes("github.com")) { + return { html, links }; + } + + const $ = cheerio.load(html); + + $("a").each((_: any, element: any) => { + const href = $(element).attr("href"); + if (!href) { + return; + } + + const parsedUrl = new URL(href, location); + if (parsedUrl.hostname === baseUrl.hostname) { + links.push(parsedUrl.pathname); + } + }); + + links = [...new Set(links)].filter((link) => { + return ( + !link.includes("#") && + !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) + ); + }); + return { html, links }; + } + + private splitUrl(url: URL) { + const baseUrl = new URL("/", url).href; + const basePath = url.pathname; + return { baseUrl, basePath }; + } +} diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts new file mode 100644 index 000000000..1b4dbab01 --- /dev/null +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -0,0 +1,260 @@ +import * as fs from "fs"; +import { URL } from "node:url"; +import { Handler, HTTPResponse, Page } from "puppeteer"; +import { + editConfigJson, + getChromiumPath, + getContinueUtilsPath, +} from "../../../util/paths"; +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; +import { ContinueConfig, IDE } from "../../.."; +import { PageData } from "../DocsCrawler"; + +export class ChromiumCrawler { + private readonly LINK_GROUP_SIZE = 2; + private curCrawlCount = 0; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { + editConfigJson((config) => ({ + ...config, + experimental: { + ...config.experimental, + useChromiumForDocsCrawling, + }, + })); + } + + async *crawl(): AsyncGenerator { + console.debug( + `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, + ); + + const stats = await PCR(ChromiumInstaller.PCR_CONFIG); + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + } finally { + await browser.close(); + } + } + + /** + * We need to handle redirects manually, otherwise there are race conditions. + * + * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 + */ + private async gotoPageAndHandleRedirects(page: Page, url: string) { + const MAX_PAGE_WAIT_MS = 5000; + + await page.goto(url, { + timeout: 0, + waitUntil: "networkidle2", + }); + + let responseEventOccurred = false; + const responseHandler: Handler = (event) => + (responseEventOccurred = true); + + const responseWatcher = new Promise(function (resolve, reject) { + setTimeout(() => { + if (!responseEventOccurred) { + resolve(); + } else { + setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); + } + }, 500); + }); + + page.on("response", responseHandler); + + await Promise.race([responseWatcher, page.waitForNavigation()]); + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + ): AsyncGenerator { + const urlStr = curUrl.toString(); + + if (visitedLinks.has(urlStr)) { + return; + } + + await this.gotoPageAndHandleRedirects(page, urlStr); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + this.curCrawlCount++; + + visitedLinks.add(urlStr); + + yield { + path: curUrl.pathname, + url: urlStr, + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + let enqueuedLinkCount = this.curCrawlCount; + + for (const link of linkGroup) { + enqueuedLinkCount++; + console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); + if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { + yield* this.crawlSitePages(page, new URL(link), visitedLinks); + } + } + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } +} + +export class ChromiumInstaller { + static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; + + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + ) { + if (this.shouldInstallOnStartup()) { + console.log("Installing Chromium"); + void this.install(); + } + } + + isInstalled() { + return fs.existsSync(getChromiumPath()); + } + + shouldInstallOnStartup() { + return ( + !this.isInstalled() && + this.config.experimental?.useChromiumForDocsCrawling + ); + } + + shouldProposeUseChromiumOnCrawlFailure() { + const { experimental } = this.config; + + return ( + experimental?.useChromiumForDocsCrawling === undefined || + experimental.useChromiumForDocsCrawling + ); + } + + async proposeAndAttemptInstall(site: string) { + const userAcceptedInstall = await this.proposeInstall(site); + + if (userAcceptedInstall) { + const didInstall = await this.install(); + return didInstall; + } + } + + async install() { + try { + await PCR(ChromiumInstaller.PCR_CONFIG); + + ChromiumCrawler.setUseChromiumForDocsCrawling(true); + + return true; + } catch (error) { + console.debug("Error installing Chromium : ", error); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + + await this.ide.showToast("error", "Failed to install Chromium"); + + return false; + } + } + + private async proposeInstall(site: string) { + const msg = + `Unable to crawl documentation site: ${site}\n` + + "We recommend installing Chromium. " + + "Download progress can be viewed in the developer console."; + + const actionMsg = "Install Chromium"; + + const res = await this.ide.showToast("warning", msg, actionMsg); + + return res === actionMsg; + } +} diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts new file mode 100644 index 000000000..abadbf7d3 --- /dev/null +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -0,0 +1,5 @@ +import { PageData } from "../DocsCrawler"; + +export class DefaultCrawler { + async *crawl(): AsyncGenerator {} +} diff --git a/core/indexing/docs/crawlers/GitHubCrawler.ts b/core/indexing/docs/crawlers/GitHubCrawler.ts new file mode 100644 index 000000000..41362cf72 --- /dev/null +++ b/core/indexing/docs/crawlers/GitHubCrawler.ts @@ -0,0 +1,80 @@ +import { Octokit } from "@octokit/rest"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +class GitHubCrawler { + private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); + private octokit = new Octokit({ auth: undefined }); + + constructor(private readonly startUrl: URL) {} + + async *crawl(): AsyncGenerator { + console.debug( + `[${ + (this.constructor as any).name + }] Crawling GitHub repo: ${this.startUrl.toString()}`, + ); + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + yield { path, url: urlStr, content: content ?? "" }; + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ owner, repo }); + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { "X-GitHub-Api-Version": "2022-11-28" }, + recursive: "true", + }, + ); + + return tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { Accept: "application/vnd.github.raw+json" }, + }); + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } +} + +export default GitHubCrawler; From 2965c4c65770c1d05d01b807e4db2553d939d70f Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 23:07:22 -0700 Subject: [PATCH 2/3] DefaultCrawler --- core/indexing/docs/DocsCrawler.ts | 3 +++ core/indexing/docs/crawlers/DefaultCrawler.ts | 24 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index a30f99471..8438ff073 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -4,6 +4,7 @@ import { URL } from "node:url"; import { ContinueConfig, IDE } from "../.."; import CheerioCrawler from "./crawlers/CheerioCrawler"; import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; +import { DefaultCrawler } from "./crawlers/DefaultCrawler"; import GitHubCrawler from "./crawlers/GitHubCrawler"; export type PageData = { @@ -39,6 +40,8 @@ class DocsCrawler { yield* new GitHubCrawler(startUrl).crawl(); } else if (this.shouldUseChromium()) { yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); + } else if (true) { + yield* new DefaultCrawler(startUrl).crawl(); } else { let didCrawlSinglePage = false; diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts index abadbf7d3..b5282df55 100644 --- a/core/indexing/docs/crawlers/DefaultCrawler.ts +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -1,5 +1,27 @@ +import { URL } from "node:url"; +import { getHeaders } from "../../../continueServer/stubs/headers"; +import { TRIAL_PROXY_URL } from "../../../control-plane/client"; import { PageData } from "../DocsCrawler"; export class DefaultCrawler { - async *crawl(): AsyncGenerator {} + constructor(private readonly startUrl: URL) {} + + async *crawl(): AsyncGenerator { + const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ startUrl: this.startUrl.toString() }), + }); + if (!resp.ok) { + const text = await resp.text(); + throw new Error(`Failed to crawl site: ${text}`); + } + const json = (await resp.json()) as PageData[]; + for (const pageData of json) { + yield pageData; + } + } } From 45c36eb5b9c72f8f03f85d70f0d7e6b6573ff208 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 2 Nov 2024 00:17:41 -0700 Subject: [PATCH 3/3] fall back if default crawler fails --- core/indexing/docs/DocsCrawler.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 8438ff073..1f72f73b6 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -38,10 +38,18 @@ class DocsCrawler { ): AsyncGenerator { if (startUrl.host === this.GITHUB_HOST) { yield* new GitHubCrawler(startUrl).crawl(); - } else if (this.shouldUseChromium()) { - yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); - } else if (true) { + return; + } + + try { yield* new DefaultCrawler(startUrl).crawl(); + return; + } catch (e) { + console.error("Default crawler failed, trying backup: ", e); + } + + if (this.shouldUseChromium()) { + yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); } else { let didCrawlSinglePage = false;