diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts index 9175f95baa4..b8b0be63329 100644 --- a/apps/sim/connectors/website/crawl.ts +++ b/apps/sim/connectors/website/crawl.ts @@ -1,7 +1,8 @@ +import { createHash } from 'node:crypto' import { mapSettledWithConcurrency } from '@sim/utils/concurrency' import { + pageKey, scopedPage, - type WebsiteDiscovery, type WebsitePage, type WebsiteScope, } from '@/connectors/website/sitemap' @@ -10,45 +11,86 @@ import { const CRAWL_CONCURRENCY = 4 /** - * What reading one page told the crawl: whether the page belongs in the listing (with the hash of - * its text, the listing's change indicator), and the links it offers. A page the site no longer - * serves, or that is not an HTML page, is not listed. + * What reading one page told the crawl: the page as it belongs in the listing, if it does, and the + * links it offers. A listed page is identified by the URL it was finally served at or names as + * canonical, which may differ from the URL the crawl requested. */ -export interface CrawledPage { - listed: boolean - contentHash?: string +export interface CrawledPage { + value: T + /** The page as it belongs in the listing, absent when it does not. */ + listedAs?: WebsitePage + /** + * The page exists but is withdrawn (it opts out, or is permanently unreadable): `value` still + * reaches the sync, so a copy indexed before is replaced even when the crawl is incomplete. + */ + withdrawn?: boolean links: string[] /** Where the page's relative links resolve: its final URL after redirects, or its ``. */ base?: string - /** The page exists but could not be read, so the links it holds are unknown. */ - unreadable?: boolean +} + +/** + * Where a crawl stands between slices, small enough to carry in a listing cursor: the pages left + * at the current depth, those found for the next, a short hash of every page queued or listed, how + * many pages it has admitted against `maxPages` and listed, and whether the cap turned any away. + */ +export interface CrawlFrontier { + depth: number + level: string[] + next: string[] + seen: string[] + admitted: number + listed: number + capped: boolean } interface CrawlLimits { maxPages: number maxDepth: number - /** - * Ends the crawl: reads in flight are cancelled and none start after it, and what the crawl found - * by then is a truncated listing. - */ - signal: AbortSignal - /** Stops the crawl once this many pages are listed, when only some are needed. */ + /** Cancels reads in flight; what was found by then is still returned. */ + signal?: AbortSignal + /** No read starts after this time; reads in flight finish and the slice ends with a frontier. */ + endsAt?: number + /** Ends the slice once this many pages are listed. */ maxListed?: number + /** Ends the slice once this many pages are listed or withdrawn, bounding what it returns. */ + maxDocuments?: number +} + +/** One slice of a crawl: what it listed, and the frontier to resume from unless it finished. */ +export interface CrawlSlice { + listed: { page: WebsitePage; value: T }[] + /** Pages this slice read and withdrew, whose values replace any copy indexed before. */ + withdrawn: T[] + /** Pages the whole crawl has listed, this slice and those before it. */ + listedTotal: number + /** The page cap turned pages away, in this slice or one before it. */ + truncated: boolean + incomplete: boolean + frontier?: CrawlFrontier +} + +/** A page's identity, hashed short enough that a frontier holds thousands of them. */ +function identityHash(url: string): string { + return createHash('sha256').update(pageKey(url)).digest('base64url').slice(0, 12) } /** - * Discovers a site's pages by following links breadth-first from the configured URL: each - * in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages - * are queued than `maxPages`. A crawl cut by the page cap or its signal is truncated, and one - * where a page could not be read is incomplete, so neither lets an unlisted page read as removed. - * A configured URL outside the include paths is still read for its links, but not listed: `read` - * receives the scope a page and its redirects must stay within. + * Discovers a site's pages by following links breadth-first from the configured URL, one slice at + * a time: each in-scope page is read once across every slice, never deeper than `maxDepth` links + * from the start, and no more pages are admitted than `maxPages`. A slice ends at `endsAt` or + * `maxListed` with a frontier the next slice resumes from, so a paced crawl reaches the whole site + * over as many listing calls (and sync runs) as it needs. A crawl whose cap turned pages away is + * truncated, and one where a page could not be read is incomplete, so neither lets an unlisted + * page read as removed; a capped crawl still reads every page it admitted. A configured URL outside the include paths is still read for its links, + * but not listed: `read` receives the scope a page and its redirects must stay within. */ -export async function crawlSitePages( +export async function crawlSitePages( scope: WebsiteScope, - read: (page: WebsitePage, signal: AbortSignal, within: WebsiteScope) => Promise, - limits: CrawlLimits -): Promise { + read: (page: WebsitePage, within: WebsiteScope, signal?: AbortSignal) => Promise>, + limits: CrawlLimits, + resume?: CrawlFrontier +): Promise> { // Relative links resolve against the URL a page is finally served at, as a browser's would. const seed = (within: WebsiteScope) => scopedPage(scope.site.baseUrl, within) ?? scopedPage(`${scope.site.baseUrl}/`, within) @@ -59,48 +101,97 @@ export async function crawlSitePages( throw new Error( 'The website URL is excluded by the configured paths or disallowed by robots.txt' ) - const pages: WebsitePage[] = [] - const seen = new Set([start.url]) - let level = [start] - let truncated = false + let depth = resume?.depth ?? 0 + const within = () => (depth === 0 ? startScope : scope) + // A resumed frontier is held to the current scope, which robots.txt may have narrowed since. + const rescope = (urls: string[], target: WebsiteScope) => + urls.flatMap((url) => scopedPage(url, target) ?? []) + let level = resume ? rescope(resume.level, within()) : [start] + let next = resume ? rescope(resume.next, scope) : [] + const seen = new Set(resume?.seen ?? [identityHash(start.url)]) + let admitted = resume?.admitted ?? 1 + const listed: CrawlSlice['listed'] = [] + const withdrawn: T[] = [] + const listedTotal = () => (resume?.listed ?? 0) + listed.length + let truncated = resume?.capped ?? false let incomplete = false - for (let depth = 0; level.length; depth++) { - const next: WebsitePage[] = [] + const slice = (frontier?: CrawlFrontier): CrawlSlice => ({ + listed, + withdrawn, + listedTotal: listedTotal(), + truncated, + incomplete, + ...(frontier ? { frontier } : {}), + }) + while (level.length || next.length) { + // A level emptied by a narrower scope on resume still leads on to the next one. + if (!level.length) { + level = next + next = [] + depth++ + continue + } for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) { - if (limits.signal.aborted) return { pages, truncated: true, incomplete } + if ( + limits.signal?.aborted || + (limits.endsAt !== undefined && Date.now() >= limits.endsAt) || + (limits.maxListed !== undefined && listed.length >= limits.maxListed) || + (limits.maxDocuments !== undefined && + listed.length + withdrawn.length >= limits.maxDocuments) + ) + return slice({ + depth, + level: level.slice(offset).map((page) => page.url), + next: next.map((page) => page.url), + seen: [...seen], + admitted, + listed: listedTotal(), + capped: truncated, + }) const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) => - read(page, limits.signal, depth === 0 ? startScope : scope) + read(page, within(), limits.signal) ) for (const [index, result] of results.entries()) { const page = batch[index] if (!page) continue - if (result.status === 'rejected' || result.value.unreadable) { + if (result.status === 'rejected') { incomplete = true continue } - if (result.value.listed && (depth > 0 || listedStart)) - pages.push({ ...page, contentHash: result.value.contentHash }) - if (limits.maxListed && pages.length >= limits.maxListed) - return { pages, truncated: true, incomplete } + const { value, listedAs, links, base } = result.value + const inScope = depth > 0 || listedStart + if (inScope && result.value.withdrawn) withdrawn.push(value) + if (listedAs && inScope) { + // A page served from, or canonical to, a URL the crawl has already met is that page. + const identity = identityHash(listedAs.url) + if (identity === identityHash(page.url) || !seen.has(identity)) { + seen.add(identity) + listed.push({ page: listedAs, value }) + } + } if (depth >= limits.maxDepth) continue - const before = seen.size - for (const link of result.value.links) { - const found = scopedPage(link, scope, result.value.base ?? page.url) - if (!found || seen.has(found.url)) continue - if (seen.size >= limits.maxPages) { + let queued = 0 + for (const link of links) { + const found = scopedPage(link, scope, base ?? page.url) + if (!found) continue + const identity = identityHash(found.url) + if (seen.has(identity)) continue + if (admitted >= limits.maxPages) { truncated = true break } - seen.add(found.url) + seen.add(identity) + admitted++ next.push(found) + queued++ } // A start page that leads nowhere is more likely unread (a client-rendered site) than a // site of one page, so it does not prove the site's other pages are gone. - if (depth === 0 && seen.size === before && !truncated) incomplete = true + if (depth === 0 && queued === 0 && !truncated) incomplete = true } } - level = next + level = [] } - return { pages, truncated, incomplete } + return slice() } diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 795c0d0bb67..d8cacb2fb12 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -23,6 +23,8 @@ export interface WebsitePageText { links: string[] /** The page's first ``, as written, which relative links resolve against. */ baseHref?: string + /** The page's `` href, as written: the URL it says it is a copy of. */ + canonicalHref?: string } /** @@ -43,6 +45,14 @@ export function extractPageText(html: string): WebsitePageText { $('meta[property="og:title"]').attr('content')?.trim() || $('title').first().text().trim() || $('h1').first().text().trim() + // Read before the text walk, which drops the head's link elements. + const canonicalHref = $('link[rel][href]') + .filter((_, element) => + ($(element).attr('rel') ?? '').toLowerCase().split(/\s+/).includes('canonical') + ) + .first() + .attr('href') + ?.trim() // Read before page chrome is dropped: navigation is where most of a site's links live. const links = directives.nofollow ? [] @@ -66,6 +76,7 @@ export function extractPageText(html: string): WebsitePageText { noindex: directives.noindex, links, ...(baseHref ? { baseHref } : {}), + ...(canonicalHref ? { canonicalHref } : {}), } } diff --git a/apps/sim/connectors/website/site.ts b/apps/sim/connectors/website/site.ts index 4f531ae695b..585ab19f764 100644 --- a/apps/sim/connectors/website/site.ts +++ b/apps/sim/connectors/website/site.ts @@ -1,3 +1,4 @@ +import { interruptibleSleep } from '@sim/utils/helpers' import type { HttpRedirectPolicy } from '@/lib/core/security/http-redirect-policy' import { validateExternalUrl } from '@/lib/core/security/input-validation' import type { SecureFetchResponse } from '@/lib/core/security/input-validation.server' @@ -5,6 +6,7 @@ import { type SecureFetchRetryOptions, secureFetchWithRetry, } from '@/lib/knowledge/documents/secure-fetch.server' +import { retryWithExponentialBackoff } from '@/lib/knowledge/documents/utils' import { matchWildcard, normalizePath, WEBSITE_CRAWLER_TOKEN } from '@/connectors/website/robots' /** The configured site: its origin, the path pages must sit under, and the host it may reach. */ @@ -146,11 +148,55 @@ const REQUEST_DEADLINE_MS = 120_000 */ const ROBOTS_PARSE_BYTES = 500 * 1024 +/** The pace robots.txt's Crawl-delay asks a sync's requests to keep. */ +export interface SitePace { + delayMs: number + /** Holds a request, or a redirect hop, until its turn. */ + wait: (signal?: AbortSignal) => Promise +} + +/** + * Spaces requests at least `delayMs` apart, one turn at a time in the order they ask, however + * many run at once: the Crawl-delay a site requests, applied to every request of the sync and to + * every redirect hop, which waits its turn like any other request. + */ +export function sitePace(delayMs: number): SitePace { + let lastAt = Number.NEGATIVE_INFINITY + let turns: Promise = Promise.resolve() + return { + delayMs, + wait: (signal) => { + const turn = turns.then(async () => { + signal?.throwIfAborted() + const wait = lastAt + delayMs - Date.now() + if (wait > 0) await interruptibleSleep(wait, signal) + signal?.throwIfAborted() + lastAt = Date.now() + }) + turns = turn.catch(() => {}) + return turn + }, + } +} + interface SiteRequest { url: string headers: Record accept: string retryOptions?: SecureFetchRetryOptions + /** Paces the request and each redirect hop; a retry waits at least the delay. */ + pace?: SitePace +} + +/** A redirect the request may not follow: off the site's host, or out of the configured scope. */ +export class RedirectOutOfScopeError extends Error { + constructor( + from: string, + readonly target: URL, + where: 'off its host' | 'outside the configured scope' + ) { + super(`The site redirected ${from} ${where}`) + } } /** @@ -168,39 +214,57 @@ const SAME_SITE_REDIRECTS: HttpRedirectPolicy = { * request's own deadline. The crawler's User-Agent and Accept survive every redirect hop; what * happens to the configured header is the redirect policy's call. */ -function siteGet( - { url, headers, accept, retryOptions }: SiteRequest, +async function siteGet( + { url, headers, accept, retryOptions, pace }: SiteRequest, maxBytes: number, redirect: { policy: HttpRedirectPolicy; assertTarget?: (target: URL) => void } ): Promise { + await pace?.wait(retryOptions?.signal) const signals = [AbortSignal.timeout(REQUEST_DEADLINE_MS)] if (retryOptions?.signal) signals.push(retryOptions.signal) const deadline = AbortSignal.any(signals) - return secureFetchWithRetry( - url, - { - profile: 'configuredEndpoint', - method: 'GET', - signal: deadline, - headers: { ...headers, Accept: accept, 'User-Agent': `${WEBSITE_CRAWLER_TOKEN}/1.0` }, - redirectPolicy: redirect.policy, - assertRedirectTarget: (target) => redirect.assertTarget?.(new URL(target)), - }, - { - timeout: ATTEMPT_TIMEOUT_MS, - retryBudgetMs: REQUEST_DEADLINE_MS, - ...retryOptions, - signal: deadline, + const fetchOptions = { + profile: 'configuredEndpoint' as const, + method: 'GET', + signal: deadline, + headers: { ...headers, Accept: accept, 'User-Agent': `${WEBSITE_CRAWLER_TOKEN}/1.0` }, + redirectPolicy: redirect.policy, + assertRedirectTarget: (target: string) => redirect.assertTarget?.(new URL(target)), + ...(pace ? { beforeRedirect: () => pace.wait(deadline) } : {}), + } + const { timeout = ATTEMPT_TIMEOUT_MS, ...backoff } = { + retryBudgetMs: REQUEST_DEADLINE_MS, + ...retryOptions, + signal: deadline, + } + if (!pace?.delayMs) + return secureFetchWithRetry(url, fetchOptions, { + ...backoff, + timeout, maxResponseBytes: maxBytes, - } + }) + // A retry waits its turn among every request of the sync, after a backoff of at least the delay. + let attempts = 0 + return retryWithExponentialBackoff( + async () => { + if (attempts++ > 0) await pace.wait(deadline) + return secureFetchWithRetry(url, fetchOptions, { + timeout, + maxResponseBytes: maxBytes, + maxRetries: 0, + signal: deadline, + }) + }, + { ...backoff, initialDelayMs: Math.max(backoff.initialDelayMs ?? 1000, pace.delayMs) } ) } /** * Fetches a resource on the configured site, or `null` when it does not exist (404 or 410). A - * redirect is refused before it is followed unless it stays on the site's host and, for a page, - * within the configured scope (`allowsTarget`), so a page never indexes content from outside the - * scope. The configured header follows the allowed hops ({@link SAME_SITE_REDIRECTS}). + * redirect is refused with {@link RedirectOutOfScopeError} before it is followed unless it stays on + * the site's host and, for a page, within the configured scope (`allowsTarget`), so a page never + * indexes content from outside the scope. The configured header follows the allowed hops + * ({@link SAME_SITE_REDIRECTS}). */ export async function fetchSiteResource( request: SiteRequest & { site: WebsiteSite }, @@ -211,9 +275,9 @@ export async function fetchSiteResource( policy: SAME_SITE_REDIRECTS, assertTarget: (target) => { if (!onSiteHost(target, request.site)) - throw new Error(`The site redirected ${request.url} off its host`) + throw new RedirectOutOfScopeError(request.url, target, 'off its host') if (allowsTarget && !allowsTarget(target)) - throw new Error(`The site redirected ${request.url} outside the configured scope`) + throw new RedirectOutOfScopeError(request.url, target, 'outside the configured scope') }, }) if (response.status === 404 || response.status === 410) return null @@ -254,13 +318,6 @@ async function readTextPrefix( return text.slice(0, Math.max(text.lastIndexOf('\n'), text.lastIndexOf('\r')) + 1) } -/** A robots.txt redirect that leaves the site, to be followed without the configured header. */ -class OffSiteRedirect extends Error { - constructor(readonly target: URL) { - super(`robots.txt redirected off the site to ${target.origin}`) - } -} - /** * The site's robots.txt as text, or `null` when it is unavailable, per RFC 9309: any 4xx but 429 * means there are no rules. Redirects are followed to any host, still through the SSRF guard; @@ -286,7 +343,8 @@ export async function fetchRobotsText({ { policy: SAME_SITE_REDIRECTS, assertTarget: (target) => { - if (onSite && !onSiteHost(target, site)) throw new OffSiteRedirect(target) + if (onSite && !onSiteHost(target, site)) + throw new RedirectOutOfScopeError(url, target, 'off its host') }, } ) @@ -294,7 +352,7 @@ export async function fetchRobotsText({ try { response = await get(`${site.origin}/robots.txt`, headers, true) } catch (error) { - if (!(error instanceof OffSiteRedirect)) throw error + if (!(error instanceof RedirectOutOfScopeError)) throw error response = await get(error.target.toString(), {}, false) } if (!response.ok) { diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index f8fc715c2ff..9d217706187 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -5,6 +5,7 @@ import { normalizePath, type RobotsPolicy } from '@/connectors/website/robots' import { fetchSiteResource, isUnderPath, + type SitePace, siteUrl, type WebsiteSite, } from '@/connectors/website/site' @@ -47,8 +48,6 @@ export interface WebsitePage { path: string /** The sitemap's ``, as an ISO timestamp, when it gives a valid one. */ lastModified?: string - /** The hash of the text a crawl read from the page, its change indicator when it has no date. */ - contentHash?: string } /** The pages one discovery found, and why they may not be all the site has. */ @@ -67,8 +66,13 @@ interface SitemapDiscoveryOptions { limit?: number /** Retry policy for every sitemap request; its `signal` bounds the whole discovery. */ retryOptions?: SecureFetchRetryOptions + /** The pace the site's Crawl-delay asks sitemap requests to keep. */ + pace?: SitePace } +/** No sitemap could be read because each one is missing or not a sitemap, rather than failing. */ +export class SitemapUnavailableError extends Error {} + /** What a page must satisfy to be synced: the site, its robots.txt, and the configured paths. */ export interface WebsiteScope { site: WebsiteSite @@ -168,6 +172,20 @@ function readSitemapEntries( return closed && !implied && isSitemap() ? 'complete' : 'invalid' } +/** Query parameters that only attribute a visit, so they never make a page a different page. */ +const TRACKING_PARAM = /^(utm_\w+|gclid|fbclid|msclkid)$/i + +/** + * The identity of a page's URL: its host without `www`, its path without a trailing slash, and its + * query, so `https://www.example.com/a/` and `http://example.com/a` name one page. Two URLs with + * one key are one document, under whichever URL was found first. + */ +export function pageKey(url: string): string { + const parsed = new URL(url) + const path = normalizePath(parsed.pathname).replace(/\/+$/, '') + return `${parsed.hostname.replace(/^www\./, '').toLowerCase()}:${parsed.port}${path}${parsed.search}` +} + /** The page a location names, resolved against `base`, when it is a page within the scope. */ export function scopedPage( location: string, @@ -177,6 +195,8 @@ export function scopedPage( const url = siteUrl(location, base, scope.site) if (!url) return null url.hash = '' + for (const name of [...url.searchParams.keys()]) + if (TRACKING_PARAM.test(name)) url.searchParams.delete(name) const path = normalizePath(url.pathname).replace(/\/+$/, '') || '/' if (NON_PAGE_PATH.test(path) || !isUnderPath(path, scope.site.basePath)) return null if (scope.include.length && !scope.include.some((matches) => matches(path))) return null @@ -189,20 +209,30 @@ async function readSitemap( url: string, site: WebsiteSite, headers: Record, - retryOptions?: SecureFetchRetryOptions + retryOptions?: SecureFetchRetryOptions, + pace?: SitePace ): Promise<{ xml: string; html: boolean } | null> { const resource = await fetchSiteResource( - { url, site, headers, accept: 'application/xml, text/xml;q=0.9, */*;q=0.1', retryOptions }, + { + url, + site, + headers, + accept: 'application/xml, text/xml;q=0.9, */*;q=0.1', + retryOptions, + pace, + }, SITEMAP_MAX_BYTES ) if (!resource) return null - const gzipped = resource.body[0] === 0x1f && resource.body[1] === 0x8b - return { - xml: (gzipped - ? gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES }) - : resource.body - ).toString('utf8'), - html: /html/i.test(resource.headers.get('content-type') ?? ''), + const html = /html/i.test(resource.headers.get('content-type') ?? '') + if (resource.body[0] !== 0x1f || resource.body[1] !== 0x8b) + return { xml: resource.body.toString('utf8'), html } + try { + const xml = gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES }) + return { xml: xml.toString('utf8'), html } + } catch { + // A corrupt or oversized gzip is a sitemap that cannot be read, as an invalid one is. + return { xml: '', html } } } @@ -232,12 +262,13 @@ function rootSitemaps( * their children; reaching the limit with more pages listed reports the discovery as truncated. * A sitemap the site lists that cannot be read (a stale robots.txt entry, a child an index lists * that is gone) is skipped and the discovery reported as incomplete, since the sync cannot tell - * its pages from deletions. Discovery fails only when it found no pages and some sitemap failed. + * its pages from deletions. Discovery fails only when it found no pages and some sitemap failed, + * with {@link SitemapUnavailableError} when every failure was a missing or invalid sitemap. */ export async function discoverSitemapPages( scope: WebsiteScope, headers: Record, - { configuredSitemap, limit = MAX_SITEMAP_PAGES, retryOptions }: SitemapDiscoveryOptions = {} + { configuredSitemap, limit = MAX_SITEMAP_PAGES, retryOptions, pace }: SitemapDiscoveryOptions = {} ): Promise { const { site } = scope const pageLimit = Math.min(limit, MAX_SITEMAP_PAGES) @@ -248,6 +279,7 @@ export async function discoverSitemapPages( let truncated = roots.length > queue.length let full = false let failure: unknown + let unavailable: SitemapUnavailableError | undefined const visit = (entry: SitemapEntry, base: string): boolean => { if (entry.kind === 'sitemap') { const child = siteUrl(entry.loc, base, site)?.toString() @@ -260,30 +292,33 @@ export async function discoverSitemapPages( return true } const page = scopedPage(entry.loc, scope) - if (!page || pages.has(page.url)) return true + const key = page && pageKey(page.url) + if (!page || !key || pages.has(key)) return true if (pages.size >= pageLimit) { full = truncated = true return false } const modified = lastModified(entry.lastmod) - pages.set(page.url, { ...page, ...(modified ? { lastModified: modified } : {}) }) + pages.set(key, { ...page, ...(modified ? { lastModified: modified } : {}) }) return true } for (let next = queue.shift(); next && !full; next = queue.shift()) { const { url, required } = next try { - const sitemap = await readSitemap(url, site, headers, retryOptions) + const sitemap = await readSitemap(url, site, headers, retryOptions, pace) const outcome = sitemap && readSitemapEntries(sitemap.xml, (entry) => visit(entry, url)) if (outcome === 'stopped') truncated = true if (outcome === 'complete' || outcome === 'stopped') continue // A guessed location may be absent, or a page the site serves for any unknown path. if (!required && (!sitemap || sitemap.html)) continue - failure ??= new Error(`Sitemap ${url} is unavailable or not a valid sitemap`) + unavailable ??= new SitemapUnavailableError( + `Sitemap ${url} is unavailable or not a valid sitemap` + ) } catch (error) { if (retryOptions?.signal?.aborted) throw error failure ??= error } } - if (pages.size === 0 && failure) throw failure - return { pages: [...pages.values()], truncated, incomplete: Boolean(failure) } + if (pages.size === 0 && (failure || unavailable)) throw failure ?? unavailable + return { pages: [...pages.values()], truncated, incomplete: Boolean(failure || unavailable) } } diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 86944406475..7f6de82a11d 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -32,8 +32,10 @@ let undeclared: 'html' | 'text' | undefined let crawlDelay = '' let lockedLink = false let extraLinks = '' +let homeCanonical = false let flakyFailures = 0 const pageRequests: { path: string; at: number }[] = [] +const sitemapRequests: number[] = [] let faqBody = '

Original answer.

' /** More `` entries than one sitemap may list, all disallowed, between two listed pages. */ @@ -60,14 +62,33 @@ const siteServer = createServer((request, response) => { if (request.headers.host?.startsWith('www.')) wwwRequests.push(request) const path = new URL(request.url ?? '/', site).pathname if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '') - if (!/\.(xml|gz|txt)$/.test(path)) pageRequests.push({ path, at: Date.now() }) + if (/\.(xml|gz)$/.test(path)) sitemapRequests.push(Date.now()) + else if (!path.endsWith('.txt')) pageRequests.push({ path, at: Date.now() }) + if (/^\/many-\d+$/.test(path)) return send(200, 'text/html', page('Many', `

Page ${path}

`)) + if (/^\/quiet-\d+$/.test(path)) + return send( + 200, + 'text/html', + page('Quiet', '

Draft

', '') + ) switch (path) { case '/': return send( 200, 'text/html', - `Home

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` + `Home${homeCanonical ? `` : ''}

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` + ) + case '/corrupt.xml.gz': + return send(200, 'application/gzip', Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0x01, 0x02])) + case '/print-faq': + return send( + 200, + 'text/html', + page('FAQ', '

Printable answers

', ``) ) + case '/old-faq': + response.writeHead(301, { Location: '/faq' }).end() + return case '/guide': response.writeHead(301, { Location: '/guide/' }).end() return @@ -170,6 +191,7 @@ const siteServer = createServer((request, response) => { ) ) case '/benefits': + case '/benefits/': return send( 200, 'text/html; charset=utf-8', @@ -309,8 +331,10 @@ beforeEach(() => { crawlDelay = '' lockedLink = false extraLinks = '' + homeCanonical = false flakyFailures = 0 pageRequests.length = 0 + sitemapRequests.length = 0 }) /** `www.localhost` stands in for a site's www host; it resolves where `localhost` does. */ @@ -322,9 +346,13 @@ function resolveWwwLocalhost() { return vi.spyOn(dns, 'lookup').mockImplementation(stub as typeof dns.lookup) } -async function listAll(sourceConfig: Record, syncContext = {}) { +async function listAll( + sourceConfig: Record, + syncContext: Record = {}, + from?: string +) { const urls: string[] = [] - let cursor: string | undefined + let cursor = from do { const page = await websiteConnector.listDocuments( `X-Api-Key: ${KEY}`, @@ -332,7 +360,9 @@ async function listAll(sourceConfig: Record, syncContext = {}) cursor, syncContext ) - urls.push(...page.documents.map((document) => document.externalId)) + // Pages a crawl withdraws come along to replace stored copies; only indexed pages are listed. + for (const document of page.documents) + if (!document.skippedReason) urls.push(document.externalId) cursor = page.nextCursor } while (cursor) return urls @@ -415,14 +445,29 @@ describe('website connector over real HTTP', () => { expect(await read('/private/salaries')).toBeNull() }) - it('refuses a redirect off the site or out of scope before it is followed', async () => { - await expect( - websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/moved`, {}) - ).rejects.toThrow('off its host') + it('withdraws a page that redirects off the site or out of scope, without following it', async () => { + for (const path of ['/moved', '/renamed']) + expect( + await websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {}) + ).toMatchObject({ + content: '', + skippedReason: 'The page redirects outside this source', + skippedExistingDisposition: 'replace', + }) + expect(foreignRequests).toHaveLength(0) + }) + + it('crawls past a page that redirects out of scope without giving up reconciliation', async () => { + extraLinks = 'PartnerRenamed' + const context: Record = {} + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(pageRequests.map((request) => request.path)).toEqual( + expect.arrayContaining(['/moved', '/renamed']) + ) + expect(urls).toContain(`${site}/benefits`) + expect(urls).not.toContain(`${site}/moved`) + expect(context.reconciliationUnsafe).toBeUndefined() expect(foreignRequests).toHaveLength(0) - await expect( - websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/renamed`, {}) - ).rejects.toThrow('outside the configured scope') }) it('withdraws a page with more markup than the parser accepts instead of failing its read', async () => { @@ -444,6 +489,7 @@ describe('website connector over real HTTP', () => { ) expect(document?.skippedReason).toContain('size limit') expect(document?.content).toBe('') + expect(document?.skippedExistingDisposition).toBe('replace') }) it('marks a listing cut by the page cap so absent pages are not reconciled away', async () => { @@ -506,9 +552,15 @@ describe('website connector over real HTTP', () => { expect(capped.listingCapped).toBe(true) }) - it('fails the sync when the only sitemap it could start from is unavailable', async () => { + it('fails a sitemap sync when the only sitemap it could start from is unavailable', async () => { missingIndex = true - await expect(listAll(config())).rejects.toThrow('unavailable') + await expect(listAll({ ...config(), discovery: 'sitemap' })).rejects.toThrow('unavailable') + }) + + it('crawls the site in auto mode when the sitemap robots.txt declares is missing', async () => { + missingIndex = true + const urls = await listAll({ ...config(), maxDepth: '1' }) + expect(urls).toContain(`${site}/benefits`) }) it('treats an unavailable robots.txt as allowing everything, per RFC 9309', async () => { @@ -615,7 +667,9 @@ describe('website connector over real HTTP', () => { undeclared = 'html' await expect(listAll({ ...config(), discovery: 'sitemap' })).rejects.toThrow('No pages found') undeclared = 'text' - await expect(listAll(config())).rejects.toThrow('not a valid sitemap') + await expect(listAll({ ...config(), discovery: 'sitemap' })).rejects.toThrow( + 'not a valid sitemap' + ) }) it('refuses the site without its configured header, and reports why on validation', async () => { @@ -686,8 +740,16 @@ describe('website connector over real HTTP', () => { expect(context.listingCapped).toBe(true) }) - it('keeps the pace robots.txt asks for between page requests', async () => { + it('keeps the pace robots.txt asks for between page requests, redirect hops and retries', async () => { crawlDelay = '0.2' + flakyFailures = 1 + extraLinks = [ + '/old-faq', + '/flaky', + ...Array.from({ length: 10 }, (_, index) => `/many-${index}`), + ] + .map((href) => `Link`) + .join('') await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) const times = pageRequests.map((request) => request.at) expect(times.length).toBeGreaterThanOrEqual(4) @@ -716,11 +778,145 @@ describe('website connector over real HTTP', () => { expect(urls).toContain(`${site}/docs/setup`) }) - it('never lets a page it could not parse hide the pages it links to', async () => { - extraLinks = 'Dense' + it('leaves out a page too large or complex to read without giving up reconciliation', async () => { + extraLinks = 'DenseHuge' const context: Record = {} - await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) - expect(context.reconciliationUnsafe).toBe(true) + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(pageRequests.map((request) => request.path)).toEqual( + expect.arrayContaining(['/dense', '/huge']) + ) + expect(urls).toContain(`${site}/benefits`) + expect(urls).not.toContain(`${site}/dense`) + expect(urls).not.toContain(`${site}/huge`) + expect(context.reconciliationUnsafe).toBeUndefined() + }) + + it('lists each page once under one URL, whatever variant a link or redirect names', async () => { + extraLinks = ['/benefits/', '/benefits?utm_source=newsletter', '/print-faq', '/old-faq'] + .map((href) => `Variant`) + .join('') + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls.filter((url) => url.includes('/benefits'))).toEqual([`${site}/benefits`]) + expect(urls.filter((url) => /faq/.test(url))).toEqual([`${site}/faq`]) + }) + + it('resumes a crawl from its cursor in a later run, reading each page once and keeping its text', async () => { + extraLinks = Array.from({ length: 60 }, (_, index) => `Page`).join( + '' + ) + const sourceConfig = { ...config(), discovery: 'links', maxDepth: '1' } + const first = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + sourceConfig, + undefined, + {} + ) + expect(first.hasMore).toBe(true) + expect(first.documents[0]).toMatchObject({ + contentDeferred: false, + content: expect.any(String), + }) + const resumed: Record = {} + const rest = await listAll(sourceConfig, resumed, first.nextCursor) + const urls = [...first.documents.map((document) => document.externalId), ...rest] + expect(new Set(urls).size).toBe(urls.length) + expect(urls).toContain(`${site}/many-59`) + const paths = pageRequests.map((request) => request.path) + expect(paths.length).toBe(new Set(paths).size) + expect(resumed.reconciliationUnsafe).toBeUndefined() + expect(resumed.listingCapped).toBeUndefined() + }) + + it('crawls the site in auto mode when its only sitemap is a corrupt gzip', async () => { + const urls = await listAll({ ...config(), sitemapUrl: `${site}/corrupt.xml.gz`, maxDepth: '1' }) + expect(urls).toContain(`${site}/benefits`) + }) + + it('bounds a crawl slice by every page it returns, withdrawn ones included', async () => { + extraLinks = Array.from( + { length: 70 }, + (_, index) => `Quiet` + ).join('') + const first = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + {} + ) + expect(first.hasMore).toBe(true) + // Slices end between batches of four reads, so one may run up to three pages past 50. + expect(first.documents.length).toBeLessThanOrEqual(53) + }) + + it('hands the sync a crawled page that opts out, so a copy indexed before is withdrawn', async () => { + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + {} + ) + expect( + listed.documents.find((document) => document.externalId === `${site}/hidden`) + ).toMatchObject({ + skippedReason: 'The page asks not to be indexed', + skippedExistingDisposition: 'replace', + }) + }) + + it('counts a page listed under its canonical URL once against the page cap', async () => { + homeCanonical = true + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1', maxPages: '2' }) + expect(urls).toContain(`${site}/home`) + expect(urls.filter((url) => url !== `${site}/home`)).toHaveLength(1) + }) + + it('keeps reading the pages a capped crawl admitted, across slices', async () => { + extraLinks = Array.from({ length: 70 }, (_, index) => `Page`).join( + '' + ) + const context: Record = {} + const urls = await listAll( + { ...config(), discovery: 'links', maxDepth: '1', maxPages: '60' }, + context + ) + // The home page and the three pages it links first take four of the 60 admissions. + expect(urls).toContain(`${site}/many-55`) + expect(urls).not.toContain(`${site}/many-56`) + expect(context.listingCapped).toBe(true) + }) + + it('moves on to the next depth when a narrower robots.txt empties the level it resumes', async () => { + // A frontier saved before robots.txt began disallowing every page left at its depth. + const cursor = `crawl:${JSON.stringify({ + depth: 1, + level: [`${site}/private/a`], + next: [`${site}/benefits`], + seen: [], + admitted: 3, + listed: 1, + capped: false, + })}` + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '3' }, {}, cursor) + expect(urls).toContain(`${site}/benefits`) + }) + + it('charges a redirect hop to the Crawl-delay', async () => { + crawlDelay = '0.2' + await listAll({ siteUrl: `${site}/guide`, discovery: 'links' }) + const at = (path: string) => pageRequests.find((request) => request.path === path)?.at ?? 0 + expect(at('/guide')).toBeGreaterThan(0) + expect(at('/guide/') - at('/guide')).toBeGreaterThanOrEqual(150) + expect(at('/guide/intro') - at('/guide')).toBeGreaterThanOrEqual(350) + }) + + it('paces sitemap requests by the Crawl-delay', async () => { + crawlDelay = '0.2' + await listAll({ ...config(), discovery: 'sitemap' }) + expect(sitemapRequests.length).toBeGreaterThanOrEqual(2) + for (let index = 1; index < sitemapRequests.length; index++) + expect( + (sitemapRequests[index] ?? 0) - (sitemapRequests[index - 1] ?? 0) + ).toBeGreaterThanOrEqual(150) }) it('does not take a start page that links nowhere as proof the rest of the site is gone', async () => { diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index 5b53fa3654a..eac16812764 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { compareStrings } from '@sim/utils/string' +import { z } from 'zod' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' import { isHtmlComplexityError } from '@/lib/file-parsers/html-parser' import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' @@ -12,7 +13,7 @@ import { parseTagDate, sizeLimitSkipReason, } from '@/connectors/utils' -import { type CrawledPage, crawlSitePages } from '@/connectors/website/crawl' +import { type CrawledPage, type CrawlFrontier, crawlSitePages } from '@/connectors/website/crawl' import { WEBSITE_DEFAULT_MAX_DEPTH, WEBSITE_DEFAULT_MAX_PAGES, @@ -27,11 +28,15 @@ import { fetchSiteResource, parseRequestHeader, pathPatterns, + RedirectOutOfScopeError, resolveSite, + type SitePace, + sitePace, siteUrl, } from '@/connectors/website/site' import { discoverSitemapPages, + SitemapUnavailableError, scopedPage, type WebsiteDiscovery, type WebsitePage, @@ -49,46 +54,29 @@ const PAGE_MAX_BYTES = 2 * 1024 * 1024 /** Whole-validation deadline: validation runs inside a request, which a slow site must not hold. */ const VALIDATE_DEADLINE_MS = 20_000 -/** Wall-clock one crawl may spend discovering pages; what it found by then still syncs. */ -const CRAWL_DEADLINE_MS = 120_000 +/** + * Wall-clock one listing call spends crawling before it returns what it found with a cursor to + * resume from, so a crawl the site's Crawl-delay slows reaches the whole site over later calls. + */ +const CRAWL_SLICE_MS = 120_000 /** - * What one sync reads once and every page read reuses: the scope, its request headers, and the - * pace robots.txt asks page requests to keep. + * Text a crawl slice hands the sync with its listing, so a page it just read is not fetched again; + * pages past it are listed for the sync to read itself. */ +const CRAWL_SLICE_TEXT_BYTES = 16 * 1024 * 1024 + +/** Longest crawl cursor; a longer frontier ends the crawl as capped. */ +const CRAWL_CURSOR_MAX_CHARS = 400 * 1024 + +const CRAWL_CURSOR_PREFIX = 'crawl:' + +/** What one sync reads once and every page read reuses: the scope, its headers and its pace. */ interface WebsiteSession { scope: WebsiteScope headers: Record - /** The Crawl-delay robots.txt asks for, which every page request, retries included, keeps. */ - crawlDelayMs: number - pace: (signal?: AbortSignal) => Promise -} - -/** - * Spaces calls at least `delayMs` apart, in the order they ask, however many run at once: the - * Crawl-delay a site requests, applied to every page request of the sync. - */ -function pacer(delayMs: number): (signal?: AbortSignal) => Promise { - let nextSlot = 0 - return async (signal) => { - signal?.throwIfAborted() - if (!delayMs) return - const now = Date.now() - const slot = Math.max(now, nextSlot) - nextSlot = slot + delayMs - if (slot <= now) return - await new Promise((resolve, reject) => { - const abort = () => { - clearTimeout(timer) - reject(signal?.reason) - } - const timer = setTimeout(() => { - signal?.removeEventListener('abort', abort) - resolve() - }, slot - now) - signal?.addEventListener('abort', abort, { once: true }) - }) - } + /** The pace robots.txt's Crawl-delay asks every request after robots.txt to keep. */ + pace: SitePace } type DiscoveryMode = 'auto' | 'sitemap' | 'links' @@ -126,6 +114,14 @@ function parseMaxDepth(value: unknown): number | null { : null } +/** The configured reach of a links crawl. */ +function crawlLimits(sourceConfig: Record) { + return { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + } +} + /** * A listed page this read deliberately leaves out: recorded as skipped and replacing whatever was * indexed before, so a page that disappears or opts out of indexing stops being searchable. @@ -153,8 +149,7 @@ async function openSession( const policy = robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots) const session: WebsiteSession = { headers, - crawlDelayMs: policy.crawlDelayMs, - pace: pacer(policy.crawlDelayMs), + pace: sitePace(policy.crawlDelayMs), scope: { site, robots: policy, @@ -191,9 +186,7 @@ function pageToStub(page: WebsitePage): ExternalDocument { sourceUrl: page.url, contentHash: page.lastModified ? `website:${page.url}:${page.lastModified}` - : page.contentHash - ? `website:${page.url}:${page.contentHash}` - : `website:${page.url}`, + : `website:${page.url}`, metadata: { section: page.path.split('/').filter(Boolean)[0], lastModified: page.lastModified, @@ -202,22 +195,30 @@ function pageToStub(page: WebsitePage): ExternalDocument { } /** - * Holds a discovery as this sync's listing, sorted by URL, and reports what it could not prove - * to the engine: a truncated discovery caps the listing, an incomplete one makes absence from it - * no evidence of deletion. Either way the pages it did find still sync. + * Reports what a listing could not prove to the engine: a truncated one caps the listing, an + * incomplete one makes absence from it no evidence of deletion. Either way the pages it did find + * still sync. */ -function holdListing( - { pages, truncated, incomplete }: WebsiteDiscovery, +function reportListing( + { listed, truncated, incomplete }: { listed: number; truncated: boolean; incomplete: boolean }, syncContext?: Record -): WebsiteListing { +) { if (truncated && syncContext) { syncContext.listingCapped = true - logger.info('Website page listing capped', { listed: pages.length }) + logger.info('Website page listing capped', { listed }) } if (incomplete && syncContext) { syncContext.reconciliationUnsafe = true - logger.warn('Website listing is incomplete', { listed: pages.length }) + logger.warn('Website listing is incomplete', { listed }) } +} + +/** Holds a sitemap discovery as this sync's listing, sorted by URL, and reports its gaps. */ +function holdListing( + { pages, truncated, incomplete }: WebsiteDiscovery, + syncContext?: Record +): WebsiteListing { + reportListing({ listed: pages.length, truncated, incomplete }, syncContext) pages.sort((left, right) => compareStrings(left.url, right.url)) const listing = { pages, byUrl: new Map(pages.map((page) => [page.url, page])) } if (syncContext) syncContext[LISTING_KEY] = listing @@ -241,48 +242,48 @@ function listingPage(listing: WebsiteListing, cursor?: string): ExternalDocument } } -interface PageRead extends CrawledPage { - document: ExternalDocument -} +type PageRead = CrawledPage /** * Reads one page: its document (with text, or recorded as withdrawn or skipped), whether it - * belongs in a crawl's listing, and the links a crawl may follow from it. A redirect may not leave - * the scope, and requests keep the pace the site's robots.txt asks for. `retryOptions.signal`, - * when given, bounds the wait for that pace as well as the request. + * belongs in a crawl's listing, and the links a crawl may follow from it. Requests keep the pace + * the site's robots.txt asks for, and `retryOptions.signal`, when given, bounds that wait too. + * + * What a page itself says is permanent until the page changes, so it withdraws the page rather + * than leaving the listing incomplete: a redirect out of the scope, a size or markup past what is + * read, no text, or a request not to be indexed. A crawl does not reach pages linked only from + * such a page, as it does not reach pages past its depth. Only a page that could not be fetched + * (a network failure, a 5xx, a deadline) throws, which leaves a crawl incomplete. With `identify`, + * a crawl's page is listed under the URL a redirect finally served it from, or the in-scope + * `rel="canonical"` URL it names; a read by external ID keeps that ID. */ async function readPage( session: WebsiteSession, page: WebsitePage, - retryOptions?: SecureFetchRetryOptions, - scope = session.scope + { + retryOptions, + scope = session.scope, + identify = false, + }: { retryOptions?: SecureFetchRetryOptions; scope?: WebsiteScope; identify?: boolean } = {} ): Promise { - const { headers } = session - const unlisted = (document: ExternalDocument): PageRead => ({ - document, - listed: false, - links: [], - }) - const unreadable = (document: ExternalDocument): PageRead => ({ - ...unlisted(document), - unreadable: true, + const unlisted = (value: ExternalDocument): PageRead => ({ value, links: [] }) + const excluded = (reason: string, read?: { links: string[]; base: string }): PageRead => ({ + value: withdrawn(page, reason), + withdrawn: true, + links: read?.links ?? [], + ...(read ? { base: read.base } : {}), }) let resource: Awaited> let finalUrl = page.url - await session.pace(retryOptions?.signal) try { resource = await fetchSiteResource( { url: page.url, site: scope.site, - headers, + headers: session.headers, accept: 'text/html, application/xhtml+xml;q=0.9', - retryOptions: session.crawlDelayMs - ? { - ...retryOptions, - initialDelayMs: Math.max(retryOptions?.initialDelayMs ?? 1000, session.crawlDelayMs), - } - : retryOptions, + retryOptions, + pace: session.pace, }, PAGE_MAX_BYTES, (target) => { @@ -292,13 +293,14 @@ async function readPage( } ) } catch (error) { + if (error instanceof RedirectOutOfScopeError) + return excluded('The page redirects outside this source') if (!isPayloadSizeLimitError(error)) throw error - return unreadable(markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES))) + return excluded(sizeLimitSkipReason(PAGE_MAX_BYTES)) } if (!resource) return unlisted(withdrawn(page, 'The page no longer exists on the site')) const contentType = resource.headers.get('content-type') ?? '' - if (!/html/i.test(contentType)) - return unlisted(withdrawn(page, 'The URL serves a file, not an HTML page')) + if (!/html/i.test(contentType)) return excluded('The URL serves a file, not an HTML page') const header = robotsDirectives(resource.headers.get('x-robots-tag')) let extracted: ReturnType try { @@ -306,52 +308,106 @@ async function readPage( } catch (error) { // Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack. if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error - return unreadable(withdrawn(page, 'The page is too complex to read')) + return excluded('The page is too complex to read') } - const { title, text, noindex, baseHref } = extracted + const { title, text, noindex, baseHref, canonicalHref } = extracted const links = header.nofollow ? [] : extracted.links let base = finalUrl try { if (baseHref) base = new URL(baseHref, finalUrl).toString() } catch {} // A page that opts out of indexing is not listed, but a crawl may still follow its links. - if (noindex || header.noindex) - return { - document: withdrawn(page, 'The page asks not to be indexed'), - listed: false, - links, - base, - } - if (!text.trim()) - return { document: withdrawn(page, 'The page has no text content'), listed: false, links, base } - const contentHash = await computeContentHash(text) - const stub = pageToStub(page) - return { - listed: true, - contentHash, - links, - base, - document: { - ...stub, - title: title || stub.title, - content: text, - contentDeferred: false, - contentHash: page.lastModified ? stub.contentHash : `website:${page.url}:${contentHash}`, - }, + if (noindex || header.noindex) return excluded('The page asks not to be indexed', { links, base }) + if (!text.trim()) return excluded('The page has no text content', { links, base }) + const identity = identify + ? ((canonicalHref ? scopedPage(canonicalHref, scope, base) : null) ?? + scopedPage(finalUrl, scope) ?? + page) + : page + const stub = pageToStub(identity) + const document: ExternalDocument = { + ...stub, + title: title || stub.title, + content: text, + contentDeferred: false, + contentHash: identity.lastModified + ? stub.contentHash + : `website:${identity.url}:${await computeContentHash(text)}`, + } + return { value: document, listedAs: identity, links, base } +} + +class CrawlCursorError extends Error { + constructor() { + super('The website crawl cursor is unreadable; the listing restarts') + } +} + +const crawlCursorSchema = z.object({ + depth: z.number().int().min(0).max(WEBSITE_MAX_DEPTH_LIMIT), + level: z.array(z.string()), + next: z.array(z.string()), + seen: z.array(z.string()), + admitted: z.number().int().min(0), + listed: z.number().int().min(0), + capped: z.boolean(), +}) + +/** A crawl cursor's frontier, or a {@link CrawlCursorError} that restarts the listing. */ +function parseCrawlCursor(cursor: string): CrawlFrontier { + try { + return crawlCursorSchema.parse(JSON.parse(cursor.slice(CRAWL_CURSOR_PREFIX.length))) + } catch { + throw new CrawlCursorError() } } -/** Discovers a site's pages by following its links, each page read once and in scope. */ -function crawlDiscovery(session: WebsiteSession, sourceConfig: Record) { - return crawlSitePages( +/** + * One slice of a links crawl as a listing page. Pages come with the text the crawl read, within + * {@link CRAWL_SLICE_TEXT_BYTES}, so the sync does not fetch them again; the cursor carries the + * crawl's frontier to the next call, in this run or a later one. + */ +async function crawlListing( + session: WebsiteSession, + sourceConfig: Record, + cursor: string | undefined, + syncContext?: Record +): Promise { + const slice = await crawlSitePages( session.scope, - (page, signal, within) => readPage(session, page, { signal }, within), + (page, within) => readPage(session, page, { scope: within, identify: true }), { - maxPages: resolveMaxPages(sourceConfig.maxPages), - maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, - signal: AbortSignal.timeout(CRAWL_DEADLINE_MS), - } + ...crawlLimits(sourceConfig), + endsAt: Date.now() + CRAWL_SLICE_MS, + maxDocuments: DOCS_PER_PAGE, + }, + cursor ? parseCrawlCursor(cursor) : undefined ) + let nextCursor = slice.frontier && `${CRAWL_CURSOR_PREFIX}${JSON.stringify(slice.frontier)}` + const overflow = (nextCursor?.length ?? 0) > CRAWL_CURSOR_MAX_CHARS + if (overflow) nextCursor = undefined + // An empty listing would reconcile every stored page away, so fail instead. + if (!nextCursor && slice.listedTotal === 0) + throw new Error( + 'No pages found in the site’s sitemaps or by following its links within the configured scope' + ) + reportListing( + { + listed: slice.listedTotal, + truncated: slice.truncated || overflow, + incomplete: slice.incomplete, + }, + syncContext + ) + let textBytes = 0 + const listed = slice.listed.map(({ value: document }) => { + textBytes += Buffer.byteLength(document.content) + return textBytes <= CRAWL_SLICE_TEXT_BYTES + ? document + : { ...document, content: '', contentDeferred: true } + }) + const documents = [...listed, ...slice.withdrawn] + return { documents, nextCursor, hasMore: Boolean(nextCursor) } } /** Discovers website pages and reads their text within the configured scope. */ @@ -364,27 +420,30 @@ export const websiteConnector: ConnectorConfig = { cursor?: string, syncContext?: Record ): Promise => { + const mode = discoveryMode(sourceConfig.discovery) let listing = syncContext?.[LISTING_KEY] as WebsiteListing | undefined if (!listing) { const session = await openSession(accessToken, sourceConfig, syncContext) - const { scope, headers } = session - const mode = discoveryMode(sourceConfig.discovery) - let discovery = - mode === 'links' - ? await crawlDiscovery(session, sourceConfig) - : await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: resolveMaxPages(sourceConfig.maxPages), - }) - if (mode === 'auto' && discovery.pages.length === 0 && !discovery.incomplete) - discovery = await crawlDiscovery(session, sourceConfig) - // An empty listing would reconcile every stored page away, so fail instead. - if (discovery.pages.length === 0) - throw new Error( - mode === 'sitemap' - ? 'No pages found in the site’s sitemaps within the configured scope' - : 'No pages found in the site’s sitemaps or by following its links within the configured scope' - ) + if (mode === 'links' || cursor?.startsWith(CRAWL_CURSOR_PREFIX)) + return crawlListing(session, sourceConfig, cursor, syncContext) + const { scope, headers, pace } = session + let discovery: WebsiteDiscovery + try { + discovery = await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: resolveMaxPages(sourceConfig.maxPages), + pace, + }) + } catch (error) { + // A site whose sitemaps are all missing or invalid is crawled instead, as one without any. + if (mode === 'sitemap' || !(error instanceof SitemapUnavailableError)) throw error + return crawlListing(session, sourceConfig, undefined, syncContext) + } + if (discovery.pages.length === 0) { + if (mode === 'auto') return crawlListing(session, sourceConfig, undefined, syncContext) + // An empty listing would reconcile every stored page away, so fail instead. + throw new Error('No pages found in the site’s sitemaps within the configured scope') + } listing = holdListing(discovery, syncContext) } return listingPage(listing, cursor) @@ -401,9 +460,11 @@ export const websiteConnector: ConnectorConfig = { // A page this sync did not list must still pass the current scope before it is read. const page = listed ?? scopedPage(externalId, session.scope) if (!page) return null - return (await readPage(session, page)).document + return (await readPage(session, page)).value }, + isListingCursorInvalidError: (error: unknown) => error instanceof CrawlCursorError, + validateConfig: async ( accessToken: string, sourceConfig: Record @@ -418,32 +479,36 @@ export const websiteConnector: ConnectorConfig = { } try { const session = await openSession(accessToken, sourceConfig, undefined, retryOptions) - const { scope, headers } = session + const { scope, headers, pace } = session const mode = discoveryMode(sourceConfig.discovery) - const { pages } = - mode === 'links' - ? { pages: [] } - : await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: 1, - retryOptions, - }) + let pages: WebsitePage[] = [] + if (mode !== 'links') { + try { + ;({ pages } = await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: 1, + retryOptions, + pace, + })) + } catch (error) { + if (mode === 'sitemap' || !(error instanceof SitemapUnavailableError)) throw error + } + } if (pages.length === 0 && mode !== 'sitemap') { // The crawl reads pages the way a sync does, within the configured limits, and stops at // the first page it would list. const crawl = await crawlSitePages( scope, - (page, _signal, within) => readPage(session, page, retryOptions, within), + (page, within) => readPage(session, page, { retryOptions, scope: within }), { - maxPages: resolveMaxPages(sourceConfig.maxPages), - maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + ...crawlLimits(sourceConfig), signal: retryOptions.signal, maxListed: 1, } ) // A crawl the deadline stopped before it found a page says nothing about the site. - if (!crawl.pages.length) retryOptions.signal.throwIfAborted() - return crawl.pages.length + if (!crawl.listed.length) retryOptions.signal.throwIfAborted() + return crawl.listed.length ? { valid: true } : { valid: false, diff --git a/apps/sim/lib/core/security/input-validation.server.ts b/apps/sim/lib/core/security/input-validation.server.ts index 6c267be457d..691affd96da 100644 --- a/apps/sim/lib/core/security/input-validation.server.ts +++ b/apps/sim/lib/core/security/input-validation.server.ts @@ -397,6 +397,11 @@ export interface SecureFetchOptions { redirectPolicy?: HttpRedirectPolicy /** Rejects a redirect target before DNS resolution or a follow-up request is attempted. */ assertRedirectTarget?: (url: string) => void + /** + * Awaited before each redirect hop is resolved and requested, after `assertRedirectTarget` + * allowed it: a caller pacing its requests (a crawl's Crawl-delay) holds the hop until its turn. + */ + beforeRedirect?: (url: string) => Promise /** * Pre-validated, IP-pinned `http://` proxy URL (see {@link validateAndPinProxyUrl}). * When set, the connection routes through this proxy and target-IP pinning is @@ -1271,10 +1276,13 @@ export async function secureFetchWithPinnedIP( settledReject(error) return } - validateUrlWithDNS(redirectUrl, 'redirectUrl', options.profile, { - logDetails: options.logUrlValidationDetails, - signal: options.signal, - }) + Promise.resolve(options.beforeRedirect?.(redirectUrl)) + .then(() => + validateUrlWithDNS(redirectUrl, 'redirectUrl', options.profile, { + logDetails: options.logUrlValidationDetails, + signal: options.signal, + }) + ) .then((validation) => { if (!validation.isValid) { settledReject(