// SPDX-License-Identifier: Apache-2.0 /** * Native BXC connector for Aphrody PostgreSQL database (pgvector). * Backed by Bun.sql (zero-overhead native driver). */ import { SQL } from "bun"; import { generateDenseVector, formatPgVector } from "../utils/vector-embed.ts"; export interface AphrodyBxcRanking { id?: string; target_url: string; query: string; serp_rank?: number | null; impressions_est?: number; ctr_est?: number; pagerank_proxy?: number; google_signals?: Record; recorded_at?: Date | string; } export interface AphrodySeoEntity { id?: string; domain: string; slug: string; url: string; canonical_url?: string; title: string; meta_description?: string; primary_keywords?: string[]; secondary_keywords?: string[]; og_metadata?: Record; structured_data?: Record; ranking_potential_score?: number; last_crawled_at?: Date | string; created_at?: Date | string; updated_at?: Date | string; } export interface AphrodyRagDocument { id?: string; corpus: string; entity_id?: string; title: string; url?: string; content: string; metadata?: Record; } /** * Resolve the PostgreSQL connection URL from explicit input or the * environment. There is deliberately no built-in fallback: credentials must * never live in source control. */ export function resolveAphrodyPgUrl(connectionUrl?: string): string | null { return ( connectionUrl || process.env.APHRODY_PG_URL || process.env.DATABASE_URL || null ); } export class AphrodyPg { readonly #url: string | null; #sql: SQL | null = null; private static instance: AphrodyPg | null = null; constructor(connectionUrl?: string) { this.#url = resolveAphrodyPgUrl(connectionUrl); } /** Whether a connection URL was provided. */ get configured(): boolean { return this.#url !== null; } private get sql(): SQL { if (!this.#url) { throw new Error( "AphrodyPg is not configured: set APHRODY_PG_URL (or DATABASE_URL) " + "or pass a connection URL.", ); } this.#sql ??= new SQL(this.#url); return this.#sql; } public static get shared(): AphrodyPg { if (!AphrodyPg.instance) { AphrodyPg.instance = new AphrodyPg(); } return AphrodyPg.instance; } public async ping(): Promise { if (!this.configured) return false; try { const rows = await this.sql`SELECT 1 as alive`; return rows.length > 0 && rows[0].alive === 1; } catch { return false; } } public async saveRanking(ranking: AphrodyBxcRanking): Promise { const signalsJson = JSON.stringify(ranking.google_signals || {}); const rows = await this.sql` INSERT INTO aphrody_bxc_rankings ( target_url, query, serp_rank, impressions_est, ctr_est, pagerank_proxy, google_signals, recorded_at ) VALUES ( ${ranking.target_url}, ${ranking.query}, ${ranking.serp_rank ?? null}, ${ranking.impressions_est ?? 0}, ${ranking.ctr_est ?? 0.0}, ${ranking.pagerank_proxy ?? 0.0}, ${signalsJson}::jsonb, NOW() ) RETURNING id; `; return rows[0]?.id as string; } public async getRankings(limit = 50): Promise { const rows = await this.sql` SELECT id, target_url, query, serp_rank, impressions_est, ctr_est, pagerank_proxy, google_signals, recorded_at FROM aphrody_bxc_rankings ORDER BY recorded_at DESC LIMIT ${limit}; `; return rows as unknown as AphrodyBxcRanking[]; } public async getRankingsByQuery(query: string, limit = 20): Promise { const rows = await this.sql` SELECT id, target_url, query, serp_rank, impressions_est, ctr_est, pagerank_proxy, google_signals, recorded_at FROM aphrody_bxc_rankings WHERE query ILIKE ${`%${query}%`} ORDER BY recorded_at DESC LIMIT ${limit}; `; return rows as unknown as AphrodyBxcRanking[]; } public async getSeoEntities(domain?: string, limit = 100): Promise { if (domain) { const rows = await this.sql` SELECT id, domain, slug, url, canonical_url, title, meta_description, primary_keywords, ranking_potential_score, last_crawled_at FROM aphrody_seo_entities WHERE domain = ${domain} ORDER BY ranking_potential_score DESC LIMIT ${limit}; `; return rows as unknown as AphrodySeoEntity[]; } const rows = await this.sql` SELECT id, domain, slug, url, canonical_url, title, meta_description, primary_keywords, ranking_potential_score, last_crawled_at FROM aphrody_seo_entities ORDER BY ranking_potential_score DESC LIMIT ${limit}; `; return rows as unknown as AphrodySeoEntity[]; } public async updateSeoEntity(url: string, update: Partial): Promise { if (update.title && update.meta_description) { await this.sql` UPDATE aphrody_seo_entities SET title = ${update.title}, meta_description = ${update.meta_description}, last_crawled_at = NOW(), updated_at = NOW() WHERE url = ${url}; `; } else { await this.sql` UPDATE aphrody_seo_entities SET last_crawled_at = NOW(), updated_at = NOW() WHERE url = ${url}; `; } } public async ingestScrape(options: { url: string; title: string; markdown: string; corpus?: string; metadata?: Record; }): Promise<{ documentId: string; chunkId: string }> { const corpus = options.corpus || "bxc_crawl"; const metaJson = JSON.stringify(options.metadata || {}); const vector = generateDenseVector(options.markdown); const vectorStr = formatPgVector(vector); // 1. Insert or update Document const docRows = await this.sql` INSERT INTO aphrody_rag_documents ( corpus, entity_id, title, url, content, metadata, created_at, updated_at ) VALUES ( ${corpus}, ${options.url}, ${options.title}, ${options.url}, ${options.markdown}, ${metaJson}::jsonb, NOW(), NOW() ) RETURNING id; `; const documentId = docRows[0].id as string; // 2. Insert chunk with pgvector embedding const tokenCount = options.markdown.split(/\s+/).length; const chunkRows = await this.sql` INSERT INTO aphrody_rag_chunks ( document_id, chunk_index, chunk_text, embedding, token_count, metadata, created_at ) VALUES ( ${documentId}, 0, ${options.markdown.slice(0, 4000)}, ${vectorStr}::vector, ${tokenCount}, ${metaJson}::jsonb, NOW() ) RETURNING id; `; const chunkId = chunkRows[0].id as string; return { documentId, chunkId }; } public async ingestScrapesBatch( scrapes: Array<{ url: string; title: string; markdown: string; corpus?: string; metadata?: Record; }>, ): Promise { if (scrapes.length === 0) return 0; for (const s of scrapes) { await this.ingestScrape(s); } return scrapes.length; } public async searchRag(query: string, limit = 5, corpus?: string): Promise { const vector = generateDenseVector(query); const vectorStr = formatPgVector(vector); if (corpus) { const rows = await this.sql` SELECT c.id, c.document_id, c.chunk_text, d.title, d.url, d.corpus, 1 - (c.embedding <=> ${vectorStr}::vector) as similarity FROM aphrody_rag_chunks c JOIN aphrody_rag_documents d ON c.document_id = d.id WHERE d.corpus = ${corpus} ORDER BY similarity DESC LIMIT ${limit}; `; return rows as any[]; } const rows = await this.sql` SELECT c.id, c.document_id, c.chunk_text, d.title, d.url, d.corpus, 1 - (c.embedding <=> ${vectorStr}::vector) as similarity FROM aphrody_rag_chunks c JOIN aphrody_rag_documents d ON c.document_id = d.id ORDER BY similarity DESC LIMIT ${limit}; `; return rows as any[]; } public async stats(): Promise<{ rankings: number; seo_entities: number; rag_documents: number; rag_chunks: number; }> { const [r, s, d, c] = await Promise.all([ this.sql`SELECT count(*) as count FROM aphrody_bxc_rankings`, this.sql`SELECT count(*) as count FROM aphrody_seo_entities`, this.sql`SELECT count(*) as count FROM aphrody_rag_documents`, this.sql`SELECT count(*) as count FROM aphrody_rag_chunks`, ]); return { rankings: Number.parseInt(r[0].count, 10), seo_entities: Number.parseInt(s[0].count, 10), rag_documents: Number.parseInt(d[0].count, 10), rag_chunks: Number.parseInt(c[0].count, 10), }; } public close(): void { this.sql.close(); } }