Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 45 additions & 24 deletions app/composables/useSearch.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { createContentClient } from 'comark-content/client'
import searchClient from 'comark-content/plugins/sqlite-full-text-search/client'
import { connectContentWorker } from 'comark-content/worker'
import type { SearchOptions, SearchResult } from 'comark-content'
import type { SearchWorkerInit } from '../workers/search'

type SearchStatus = 'idle' | 'loading' | 'ready' | 'error'

const status = ref<SearchStatus>('idle')

/** The worker of the commit being searched; a switch terminates it and starts the next commit's. */
let active: ReturnType<typeof start> | undefined

function start(key: string, init: SearchWorkerInit) {
// A worker serves one commit for its life; `name` is how it learns which.
const worker = new Worker(new URL('../workers/search.ts', import.meta.url), { type: 'module', name: JSON.stringify(init) })
const connection = connectContentWorker(worker)
const client = createContentClient({ fetch: connection.fetch, plugins: [searchClient()] })
return { key, connection, client, indexed: client.buildSearchIndex() }
}

/**
* Hydration logging switch: `?debug=search`
*/
Expand All @@ -23,19 +38,9 @@ export function useSearch() {
/** What to hydrate from, or `null` when this route has nothing searchable (yet). */
const target = computed(() => {
const isPreview = content.value.mode !== 'prod'
if (sha.value) return {
sha: sha.value,
isPreview,
apiBase: `/api/content/blob/${sha.value}`
}

if (sha.value) return { sha: sha.value }
// Prod in dev mode
if (!isPreview && import.meta.dev) return {
sha: null,
isPreview,
apiBase: '/api/content'
}

if (!isPreview && import.meta.dev) return { sha: null }
return null
})

Expand All @@ -56,32 +61,48 @@ export function useSearch() {
return
}

const key = current.sha ?? 'unpinned' // dev mode only
const debug = searchDebug()
if (active?.key !== key) {
if (debug) console.info(`[search] loading sha ${key}`)
active?.connection.terminate()
active = start(key, { sha: current.sha, debug })
}
const entry = active

status.value = 'loading'
const started = performance.now()
try {
const debug = searchDebug()
if (debug) console.info(`[search] warmup from ${current.apiBase} (sha ${current.sha ?? 'unpinned'})`)

await warmupSearch({
apiBase: current.apiBase,
sha: current.sha,
isPreview: current.isPreview,
origin: location.origin,
debug,
})
await entry.indexed
if (active !== entry) return // a switch occurred
status.value = 'ready'
if (debug) console.info(`[search] ready in ${(performance.now() - started).toFixed(1)}ms`)
} catch (error) {
if (active !== entry) return
// A fresh worker on the next warmup: the connection may be failed for good.
entry.connection.terminate()
active = undefined
status.value = 'error'
console.error('[search] could not load the search database', error)
}
}

if (import.meta.client) {
onNuxtReady(warmup)
watch(() => target.value && `${target.value.isPreview}:${target.value.sha}`, warmup)
watch(() => target.value && (target.value.sha ?? 'unpinned'), warmup)
}

async function search(query: string, opts?: SearchOptions): Promise<SearchResult[]> {
return prefixSearchResults(await searchContent(query, opts), content.value.routeBase)
const entry = active
if (!entry) return []
try {
const results = await entry.client.search(query, { limit: 25, snippet: { columns: ['content'] }, ...opts })
return prefixSearchResults(results, content.value.routeBase)
} catch (error) {
// Rejected because a switch terminated its worker, which isn't a search error.
if (active !== entry) return []
throw error
}
}

return {
Expand Down
43 changes: 3 additions & 40 deletions app/workers/internal/search-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,20 @@
*
* Triggered by `?debug=search` param.
*/
import type { ContentFile, Logger, RelationalDatabase } from 'comark-content/runtime'
import type { Logger } from 'comark-content/runtime'

const PREFIX = '[search:worker]'

let debug = false

/** Called on every `warmup`; once on, it stays on for the life of the worker. */
export function setDebug(value: boolean): void {
debug = debug || value
debug = value
}

export function isDebug(): boolean {
return debug
}

export function log(...args: unknown[]): void {
function log(...args: unknown[]): void {
if (debug) console.info(PREFIX, ...args)
}

/** Milliseconds since `from`, for log lines. */
export function since(from: number): string {
return `${(performance.now() - from).toFixed(1)}ms`
}

/**
* Warn and error are deliberately ungated: the FTS plugin reports a missing snapshot through this
* channel, and that failure is otherwise indistinguishable from "the query matched nothing".
Expand All @@ -37,30 +27,3 @@ export const logger: Logger = {
warn: (tag, ...args) => console.warn(`${PREFIX} ${tag}:`, ...args),
error: (tag, ...args) => console.error(`${PREFIX} ${tag}:`, ...args),
}

export function describeArtifact(decoded: unknown): string {
const raw = Array.isArray(decoded) ? decoded : (decoded as { items?: unknown } | null)?.items
if (Array.isArray(raw)) {
const items = raw as ContentFile[]
const documents = items.filter((item) => item.meta.kind === 'document')
const withNodes = documents.filter((item) => item.nodes?.length)
return `${items.length} item(s), ${documents.length} document(s), ${withNodes.length} with nodes`
}
return `${raw ? Object.keys(raw as Record<string, unknown>).length : 0} manifest item(s)`
}

/**
* Mirrors the FTS plugin's `ownId` convention
*/
function sourceIdFor(content: { name: string, key: string }): string {
return content.key ? `${content.name}@${content.key}` : content.name
}

export async function indexedRows(database: RelationalDatabase, content: { name: string, key: string }): Promise<number | string> {
try {
const rows = await database.all<{ n: number }>('SELECT count(*) as n FROM __fts_search WHERE source = ?', [sourceIdFor(content)])
return rows?.[0]?.n ?? 'unknown'
} catch (error) {
return `unknown (${error instanceof Error ? error.message : String(error)})`
}
}
156 changes: 16 additions & 140 deletions app/workers/search.ts
Original file line number Diff line number Diff line change
@@ -1,153 +1,29 @@
/**
* Search worker: owns the browser-standalone `comark-content` instance (sqlite-wasm FTS5).
* Search worker: serves one browser-standalone `comark-content` instance (sqlite-wasm FTS5) to `useSearch()`.
*
* Hydrated from the per-commit snapshot artifacts, every mode's (prod, blob, tree, pr) served from
* its own SHA-pinned `/api/content/blob/<sha>` URL.
*
* Instances are cached by SHA:
* - Prod is always kept
* - One preview only is kept, evicted on the next switch
* Hydrated from one commit's snapshot artifacts: `useSearch()` starts one worker per commit.
*/
import { comarkContent, DEFAULT_CONTENT_NAME, readArtifact } from 'comark-content/runtime'
import { comarkContent, DEFAULT_CONTENT_NAME } from 'comark-content/runtime'
import sqliteWasm from 'comark-content/database/sqlite-wasm'
import snapshot from 'comark-content/sources/snapshot'
import sqliteFullTextSearch from 'comark-content/plugins/sqlite-full-text-search'
import { ofetch } from 'ofetch'
import { describeArtifact, indexedRows, isDebug, log, logger, setDebug, since } from './internal/search-logger'
import type { CacheArtifact, SearchOptions, SearchResult } from 'comark-content/runtime'
import { serveContentWorker } from 'comark-content/worker'
import { logger, setDebug } from './internal/search-logger'

export interface SearchTarget {
apiBase: string
export interface SearchWorkerInit {
/** Commit the artifacts are pinned to, `null` for the unpinned dev content. */
sha: string | null
isPreview: boolean
origin: string
debug: boolean
}

// Shared database for the worker's lifetime
const database = sqliteWasm()

function createInstance(fetchArtifact: (path: string) => Promise<CacheArtifact>, apiBase: string, sha: string | null) {
const content = comarkContent({
source: snapshot(
() => fetchArtifact(`${apiBase}/snapshot/${DEFAULT_CONTENT_NAME}.json`),
() => fetchArtifact(`${apiBase}/manifest.json`)
),
plugins: [sqliteFullTextSearch({ database })],
logger,
})

return sha ? content.withRef(sha) : content
}

type SearchInstance = ReturnType<typeof createInstance>

/** Whichever instance `searchContent()` should query */
let active: SearchInstance | undefined

/** Hydrated instances by key */
const loaded = new Map<string, SearchInstance>()
/** In-flight hydrations, so concurrent warmups for one commit share a single load. */
const pending = new Map<string, Promise<SearchInstance>>()

/** Needed to avoid evicting prod */
let prodKey: string | undefined
/** Most recently requested key (for eviction) */
let currentKey = ''

function hydrate(target: SearchTarget): Promise<SearchInstance> {
const key = target.sha ?? 'unpinned' // dev mode only
const existing = loaded.get(key)
if (existing) return Promise.resolve(existing)

let promise = pending.get(key)
if (!promise) {
promise = loadInstance(target)
.then((instance) => {
loaded.set(key, instance)
return instance
})
// Cleared on failure too, so the next warmup retries instead of re-awaiting this rejection.
.finally(() => pending.delete(key))
pending.set(key, promise)
}
return promise
}

/**
* Loads (or reuses) the database for `target`, makes it active, and evicts whatever else is
* cached — keeping prod warm and dropping any preview once navigated away from it.
*/
export async function warmupSearch(target: SearchTarget): Promise<void> {
setDebug(target.debug)
const key = target.sha ?? 'unpinned'
currentKey = key
// Claim prod's key before awaiting, so the eviction below can never clean it.
if (!target.isPreview) prodKey = key

const instance = await hydrate(target)
if (currentKey !== key) return // a switch occurred, so skip the eviction

active = instance
for (const [staleKey, stale] of loaded) {
if (staleKey === key || staleKey === prodKey) continue
loaded.delete(staleKey)
void stale.clean().catch((error) => log(`cleanup failed for ${staleKey}`, error))
}
}
// Set by `useSearch()` through the Worker's `name`.
const { sha, debug } = JSON.parse(self.name) as SearchWorkerInit
setDebug(debug)

async function loadInstance(target: SearchTarget): Promise<SearchInstance> {
const started = performance.now()
try {
const fetchArtifact = async (path: string): Promise<CacheArtifact> => {
const url = new URL(path, target.origin).href
const fetchStarted = performance.now()
try {
const artifact = await ofetch<CacheArtifact>(url)
if (isDebug()) {
let contents: string
try {
contents = describeArtifact(await readArtifact(artifact))
} catch (error) {
contents = `undecodable: ${error instanceof Error ? error.message : String(error)}`
}
log(`fetched ${path} in ${since(fetchStarted)} — ${artifact?.size ?? 0} bytes, ${contents}`)
}
return artifact
} catch (error) {
log(`failed ${path} after ${since(fetchStarted)}`, error)
throw error
}
}
const apiBase = sha ? `/api/content/blob/${sha}` : '/api/content'

const content = createInstance(fetchArtifact, target.apiBase, target.sha)
await content.init()

const indexStarted = performance.now()
await content.search('') // pulls the snapshot in and builds the FTS index
const rows = await indexedRows(database, content)
log(`index built in ${since(indexStarted)} for ${target.apiBase} — ${rows} row(s)`)

log(`ready in ${since(started)} (${target.isPreview ? 'preview' : 'prod'} ${target.sha ?? 'unpinned'})`)
return content
} catch (error) {
log(`hydration failed after ${since(started)} for ${target.apiBase}`, error)
throw error
}
}

/** Empty until hydration lands. */
export async function searchContent(query: string, opts?: SearchOptions): Promise<SearchResult[]> {
if (!active) {
log(`dropped query "${query}" — no instance yet`)
return []
}
const queryStarted = performance.now()
const results = await active.search(query, {
limit: 25,
snippet: { columns: ['content'] },
...opts,
})
log(`query "${query}" -> ${results.length} result(s) in ${since(queryStarted)}`)
return results
}
serveContentWorker(comarkContent({
source: snapshot(`${apiBase}/snapshot/${DEFAULT_CONTENT_NAME}.json`, `${apiBase}/manifest.json`),
plugins: [sqliteFullTextSearch({ database: sqliteWasm() })],
logger,
}))
1 change: 0 additions & 1 deletion nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export default defineNuxtConfig({
'nuxt-schema-org',
'@nuxtjs/mcp-toolkit',
'nuxt-llms',
'nuxt-workers',
'nuxt-agent-discovery',
],
ignore: ['content/**'],
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"ai": "^7.0.173",
"beautiful-mermaid": "^1.1.3",
"comark": "^0.9.2",
"comark-content": "^0.6.2",
"comark-content": "https://pkg.pr.new/comark-content@ec7a084",
"defu": "^6.1.7",
"exsolve": "^1.2.0",
"forges": "^0.3.2",
Expand All @@ -81,7 +81,6 @@
"nuxt-og-image": "^7.0.7",
"nuxt-schema-org": "^7.0.1",
"nuxt-seo-utils": "^9.0.2",
"nuxt-workers": "^0.1.0",
"ofetch": "^1.5.1",
"pathe": "^2.0.3",
"rangi": "^2.2.0",
Expand Down
Loading
Loading