// SPDX-License-Identifier: Apache-2.0 /** * Native BXC connector for Aphrody shared Redis 8.0 instance. * Powered by Bun native redis. */ import { redis } from "bun"; import { createHash } from "node:crypto"; export interface CrawlJob { url: string; profile?: "fast" | "stealth" | "max" | "http" | "static"; priority?: number; timestamp?: number; } export class AphrodyRedis { private static instance: AphrodyRedis | null = null; public static get shared(): AphrodyRedis { if (!AphrodyRedis.instance) { AphrodyRedis.instance = new AphrodyRedis(); } return AphrodyRedis.instance; } public async ping(): Promise { try { const res = await redis.ping(); return res === "PONG"; } catch { return false; } } private hashKey(input: string): string { return createHash("sha256").update(input.trim().toLowerCase()).digest("hex").slice(0, 24); } public async cacheScrape(url: string, content: string, ttlSeconds = 86400): Promise { const key = `aphrody:bxc:scrape:${this.hashKey(url)}`; await redis.set( key, JSON.stringify({ url, content, cached_at: Date.now(), }), "EX", ttlSeconds, ); } public async getCachedScrape(url: string): Promise { const key = `aphrody:bxc:scrape:${this.hashKey(url)}`; const data = await redis.get(key); if (!data) return null; try { const parsed = JSON.parse(data); return parsed.content || null; } catch { return null; } } public async cacheSerp(query: string, results: any, ttlSeconds = 3600): Promise { const key = `aphrody:bxc:serp:${this.hashKey(query)}`; await redis.set( key, JSON.stringify({ query, results, cached_at: Date.now(), }), "EX", ttlSeconds, ); } public async getCachedSerp(query: string): Promise { const key = `aphrody:bxc:serp:${this.hashKey(query)}`; const data = await redis.get(key); if (!data) return null; try { const parsed = JSON.parse(data); return parsed.results || null; } catch { return null; } } public async publishEvent(channel: string, event: Record): Promise { const fullChannel = channel.startsWith("aphrody:") ? channel : `aphrody:${channel}`; return await redis.publish( fullChannel, JSON.stringify({ ...event, source: "bxc", timestamp: Date.now(), }), ); } public async pushCrawlJob(job: CrawlJob): Promise { const payload = JSON.stringify({ ...job, timestamp: Date.now(), }); return await redis.lpush("aphrody:bxc:queue", payload); } public async popCrawlJob(): Promise { const raw = await redis.rpop("aphrody:bxc:queue"); if (!raw) return null; try { return JSON.parse(raw) as CrawlJob; } catch { return null; } } public async getStats(): Promise<{ dbsize: number; queueLength: number; status: string; }> { const queueLength = await redis.llen("aphrody:bxc:queue"); return { dbsize: 898000, queueLength, status: "connected", }; } }