Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

(feat/index) Domain frequency aggregator (#1908)

Nicolas9a3a354d8f4a
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index b6fc1e3fa..2bed3cc71 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -26,6 +26,7 @@ import { v4 as uuidv4 } from "uuid";
import { RateLimiterMode } from "./types";
import { attachWsProxy } from "./services/agentLivecastWS";
import { cacheableLookup } from "./scraper/scrapeURL/lib/cacheableLookup";
+import domainFrequencyRouter from "./routes/domain-frequency";
const { createBullBoard } = require("@bull-board/api");
const { BullMQAdapter } = require('@bull-board/api/bullMQAdapter');
@@ -83,6 +84,7 @@ app.get("/test", async (req, res) => {
app.use(v0Router);
app.use("/v1", v1Router);
app.use(adminRouter);
+app.use(domainFrequencyRouter);
const DEFAULT_PORT = process.env.PORT ?? 3002;
const HOST = process.env.HOST ?? "localhost";
diff --git a/apps/api/src/routes/domain-frequency.ts b/apps/api/src/routes/domain-frequency.ts
new file mode 100644
index 000000000..f71ee7ed1
--- /dev/null
+++ b/apps/api/src/routes/domain-frequency.ts
@@ -0,0 +1,98 @@
+import express from "express";
+import { Request, Response } from "express";
+import {
+ getTopDomains,
+ getDomainFrequency,
+ getDomainFrequencyStats,
+ getDomainFrequencyQueueLength,
+} from "../services";
+import { logger } from "../lib/logger";
+
+const domainFrequencyRouter = express.Router();
+
+// Get top domains by frequency
+domainFrequencyRouter.get(
+ `/admin/domain-frequency/${process.env.BULL_AUTH_KEY}/top`,
+ async (req: Request, res: Response) => {
+ try {
+ const limit = parseInt(req.query.limit as string) || 100;
+ const topDomains = await getTopDomains(Math.min(limit, 1000)); // Cap at 1000
+
+ res.json({
+ success: true,
+ data: topDomains,
+ });
+ } catch (error) {
+ logger.error("Failed to get top domains", { error });
+ res.status(500).json({
+ success: false,
+ error: "Failed to retrieve top domains",
+ });
+ }
+ },
+);
+
+// Get frequency for a specific domain
+domainFrequencyRouter.get(
+ `/admin/domain-frequency/${process.env.BULL_AUTH_KEY}/domain/:domain`,
+ async (req: Request, res: Response) => {
+ try {
+ const { domain } = req.params;
+ const frequency = await getDomainFrequency(domain);
+
+ if (frequency === null) {
+ res.status(404).json({
+ success: false,
+ error: "Domain not found",
+ });
+ return;
+ }
+
+ res.json({
+ success: true,
+ data: {
+ domain,
+ frequency,
+ },
+ });
+ } catch (error) {
+ logger.error("Failed to get domain frequency", {
+ error,
+ domain: req.params.domain,
+ });
+ res.status(500).json({
+ success: false,
+ error: "Failed to retrieve domain frequency",
+ });
+ }
+ },
+);
+
+// Get overall statistics
+domainFrequencyRouter.get(
+ `/admin/domain-frequency/${process.env.BULL_AUTH_KEY}/stats`,
+ async (req: Request, res: Response) => {
+ try {
+ const [stats, queueLength] = await Promise.all([
+ getDomainFrequencyStats(),
+ getDomainFrequencyQueueLength(),
+ ]);
+
+ res.json({
+ success: true,
+ data: {
+ ...stats,
+ pendingUpdates: queueLength,
+ },
+ });
+ } catch (error) {
+ logger.error("Failed to get domain frequency stats", { error });
+ res.status(500).json({
+ success: false,
+ error: "Failed to retrieve statistics",
+ });
+ }
+ },
+);
+
+export default domainFrequencyRouter;
diff --git a/apps/api/src/routes/v1.ts b/apps/api/src/routes/v1.ts
index cfb98cbe7..cf6704bb3 100644
--- a/apps/api/src/routes/v1.ts
+++ b/apps/api/src/routes/v1.ts
@@ -36,6 +36,7 @@ import { deepResearchController } from "../controllers/v1/deep-research";
import { deepResearchStatusController } from "../controllers/v1/deep-research-status";
import { tokenUsageController } from "../controllers/v1/token-usage";
import { ongoingCrawlsController } from "../controllers/v1/crawl-ongoing";
+import { addDomainFrequencyJob } from "../services"
function checkCreditsMiddleware(
_minimum?: number,
@@ -101,6 +102,18 @@ export function authMiddleware(
currentRateLimiterMode = RateLimiterMode.ExtractAgentPreview;
}
+ // Track domain frequency regardless of caching
+ try {
+ // Use the URL from the request body if available
+ const urlToTrack = (req.body as any)?.url;
+ if (urlToTrack) {
+ await addDomainFrequencyJob(urlToTrack);
+ }
+ } catch (error) {
+ // Log error without meta.logger since it's not available in this context
+ logger.warn("Failed to track domain frequency", { error });
+ }
+
// if (currentRateLimiterMode === RateLimiterMode.Scrape && isAgentExtractModelValid((req.body as any)?.agent?.model)) {
// currentRateLimiterMode = RateLimiterMode.ScrapeAgentPreview;
// }
diff --git a/apps/api/src/scraper/scrapeURL/engines/index/index.ts b/apps/api/src/scraper/scrapeURL/engines/index/index.ts
index af67c9e91..c5024101b 100644
--- a/apps/api/src/scraper/scrapeURL/engines/index/index.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/index/index.ts
@@ -1,11 +1,13 @@
import { Document } from "../../../../controllers/v1/types";
import { EngineScrapeResult } from "..";
import { Meta } from "../..";
-import { getIndexFromGCS, hashURL, index_supabase_service, normalizeURLForIndex, saveIndexToGCS, generateURLSplits, addIndexInsertJob, generateDomainSplits, addOMCEJob } from "../../../../services";
+import { getIndexFromGCS, hashURL, index_supabase_service, normalizeURLForIndex, saveIndexToGCS, generateURLSplits, addIndexInsertJob, generateDomainSplits, addOMCEJob, addDomainFrequencyJob } from "../../../../services";
import { EngineError, IndexMissError, TimeoutError } from "../../error";
import crypto from "crypto";
export async function sendDocumentToIndex(meta: Meta, document: Document) {
+
+
const shouldCache = meta.options.storeInCache
&& !meta.internalOptions.zeroDataRetention
&& meta.winnerEngine !== "index"
diff --git a/apps/api/src/services/index.ts b/apps/api/src/services/index.ts
index d0f7d5375..dcc813632 100644
--- a/apps/api/src/services/index.ts
+++ b/apps/api/src/services/index.ts
@@ -333,6 +333,173 @@ export async function getOMCEQueueLength(): Promise<number> {
return await redisEvictConnection.scard(OMCE_JOB_QUEUE_KEY) ?? 0;
}
+// Domain Frequency Tracking
+const DOMAIN_FREQUENCY_QUEUE_KEY = "domain-frequency-queue";
+const DOMAIN_FREQUENCY_BATCH_SIZE = 100;
+
+export function extractDomainFromUrl(url: string): string | null {
+ try {
+ const urlObj = new URL(url);
+ // Remove www. prefix for consistency
+ let domain = urlObj.hostname;
+ if (domain.startsWith("www.")) {
+ domain = domain.slice(4);
+ }
+ return domain;
+ } catch (error) {
+ _logger.warn("Failed to extract domain from URL", { url, error });
+ return null;
+ }
+}
+
+export async function addDomainFrequencyJob(url: string) {
+ const domain = extractDomainFromUrl(url);
+ if (!domain) {
+ return;
+ }
+
+ await redisEvictConnection.rpush(DOMAIN_FREQUENCY_QUEUE_KEY, domain);
+}
+
+export async function getDomainFrequencyJobs(): Promise<Map<string, number>> {
+ const domains = (await redisEvictConnection.lpop(DOMAIN_FREQUENCY_QUEUE_KEY, DOMAIN_FREQUENCY_BATCH_SIZE)) ?? [];
+
+ // Aggregate domain counts in memory before batch insert
+ const domainCounts = new Map<string, number>();
+ for (const domain of domains) {
+ domainCounts.set(domain, (domainCounts.get(domain) || 0) + 1);
+ }
+
+ return domainCounts;
+}
+
+export async function processDomainFrequencyJobs() {
+ if (!useIndex) {
+ return;
+ }
+
+ const domainCounts = await getDomainFrequencyJobs();
+ if (domainCounts.size === 0) {
+ return;
+ }
+
+ _logger.info(`Domain frequency processor found domains to update`, { domainCount: domainCounts.size });
+
+ try {
+ // Convert to array format for the stored procedure
+ const updates = Array.from(domainCounts.entries()).map(([domain, count]) => ({
+ domain,
+ count
+ }));
+
+ // Use the upsert function for efficient batch update
+ const { error } = await index_supabase_service.rpc('upsert_domain_frequencies', {
+ domain_updates: updates
+ });
+
+ if (error) {
+ _logger.error(`Domain frequency processor failed to update domains`, { error, domainCount: domainCounts.size });
+ // Re-queue the domains on failure
+ for (const [domain, count] of domainCounts) {
+ for (let i = 0; i < count; i++) {
+ await redisEvictConnection.rpush(DOMAIN_FREQUENCY_QUEUE_KEY, domain);
+ }
+ }
+ } else {
+ _logger.info(`Domain frequency processor updated domains`, { domainCount: domainCounts.size });
+ }
+ } catch (error) {
+ _logger.error(`Domain frequency processor failed to update domains`, { error, domainCount: domainCounts.size });
+ // Re-queue the domains on failure
+ for (const [domain, count] of domainCounts) {
+ for (let i = 0; i < count; i++) {
+ await redisEvictConnection.rpush(DOMAIN_FREQUENCY_QUEUE_KEY, domain);
+ }
+ }
+ }
+}
+
+export async function getDomainFrequencyQueueLength(): Promise<number> {
+ return await redisEvictConnection.llen(DOMAIN_FREQUENCY_QUEUE_KEY) ?? 0;
+}
+
+// Domain frequency query utilities
+export async function getTopDomains(limit: number = 100): Promise<Array<{ domain: string, frequency: number, last_updated: string }>> {
+ if (!useIndex) {
+ return [];
+ }
+
+ const { data, error } = await index_supabase_service
+ .from("domain_frequency")
+ .select("domain, frequency, last_updated")
+ .order("frequency", { ascending: false })
+ .limit(limit);
+
+ if (error) {
+ _logger.error("Failed to get top domains", { error });
+ return [];
+ }
+
+ return data ?? [];
+}
+
+export async function getDomainFrequency(domain: string): Promise<number | null> {
+ if (!useIndex) {
+ return null;
+ }
+
+ const { data, error } = await index_supabase_service
+ .from("domain_frequency")
+ .select("frequency")
+ .eq("domain", domain)
+ .single();
+
+ if (error) {
+ if (error.code !== "PGRST116") { // Not found error
+ _logger.error("Failed to get domain frequency", { error, domain });
+ }
+ return null;
+ }
+
+ return data?.frequency ?? null;
+}
+
+export async function getDomainFrequencyStats(): Promise<{
+ totalDomains: number;
+ totalRequests: number;
+ avgRequestsPerDomain: number;
+} | null> {
+ if (!useIndex) {
+ return null;
+ }
+
+ const { data, error } = await index_supabase_service
+ .from("domain_frequency")
+ .select("frequency");
+
+ if (error) {
+ _logger.error("Failed to get domain frequency stats", { error });
+ return null;
+ }
+
+ if (!data || data.length === 0) {
+ return {
+ totalDomains: 0,
+ totalRequests: 0,
+ avgRequestsPerDomain: 0
+ };
+ }
+
+ const totalRequests = data.reduce((sum, row) => sum + row.frequency, 0);
+ const totalDomains = data.length;
+
+ return {
+ totalDomains,
+ totalRequests,
+ avgRequestsPerDomain: Math.round(totalRequests / totalDomains)
+ };
+}
+
export async function queryIndexAtSplitLevel(url: string, limit: number, maxAge = 2 * 24 * 60 * 60 * 1000): Promise<string[]> {
if (!useIndex || process.env.FIRECRAWL_INDEX_WRITE_ONLY === "true") {
return [];
diff --git a/apps/api/src/services/indexing/index-worker.ts b/apps/api/src/services/indexing/index-worker.ts
index ef8be0349..a041da939 100644
--- a/apps/api/src/services/indexing/index-worker.ts
+++ b/apps/api/src/services/indexing/index-worker.ts
@@ -11,7 +11,7 @@ import {
import { processBillingBatch, queueBillingOperation, startBillingBatchProcessing } from "../billing/batch_billing";
import systemMonitor from "../system-monitor";
import { v4 as uuidv4 } from "uuid";
-import { index_supabase_service, processIndexInsertJobs, processIndexRFInsertJobs, processOMCEJobs } from "..";
+import { index_supabase_service, processIndexInsertJobs, processIndexRFInsertJobs, processOMCEJobs, processDomainFrequencyJobs } from "..";
import { processWebhookInsertJobs } from "../webhook";
import { scrapeOptions as scrapeOptionsSchema, crawlRequestSchema, toLegacyCrawlerOptions } from "../../controllers/v1/types";
import { StoredCrawl, crawlToCrawler, saveCrawl } from "../../lib/crawl-redis";
@@ -286,6 +286,7 @@ const workerFun = async (queue: Queue, jobProcessor: (token: string, job: Job) =
const INDEX_INSERT_INTERVAL = 3000;
const WEBHOOK_INSERT_INTERVAL = 15000;
const OMCE_INSERT_INTERVAL = 5000;
+const DOMAIN_FREQUENCY_INTERVAL = 10000;
// Start the workers
(async () => {
@@ -325,6 +326,13 @@ const OMCE_INSERT_INTERVAL = 5000;
await processOMCEJobs();
}, OMCE_INSERT_INTERVAL);
+ const domainFrequencyInterval = setInterval(async () => {
+ if (isShuttingDown) {
+ return;
+ }
+ await processDomainFrequencyJobs();
+ }, DOMAIN_FREQUENCY_INTERVAL);
+
// Wait for all workers to complete (which should only happen on shutdown)
await Promise.all([billingWorkerPromise, precrawlWorkerPromise]);
@@ -332,4 +340,5 @@ const OMCE_INSERT_INTERVAL = 5000;
clearInterval(webhookInserterInterval);
clearInterval(indexRFInserterInterval);
clearInterval(omceInserterInterval);
+ clearInterval(domainFrequencyInterval);
})();