Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
chore(api): remove unused domain frequency tracking system (#2796)
firecrawl-spring[bot]77432a82b4ac
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 57450a5a5..8b9c3ada5 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -30,7 +30,6 @@ import { v7 as uuidv7 } from "uuid";import { attachWsProxy } from "./services/agentLivecastWS";import { cacheableLookup } from "./scraper/scrapeURL/lib/cacheableLookup";import { v2Router } from "./routes/v2";-import domainFrequencyRouter from "./routes/domain-frequency";import { nuqShutdown } from "./services/worker/nuq";import { getErrorContactMessage } from "./lib/deployment";import { initializeBlocklist } from "./scraper/WebScraper/utils/blocklist";@@ -106,7 +105,6 @@ app.use(v0Router);app.use("/v1", v1Router);app.use("/v2", v2Router);app.use(adminRouter);-app.use(domainFrequencyRouter);const DEFAULT_PORT = config.PORT;const HOST = config.HOST;diff --git a/apps/api/src/routes/domain-frequency.ts b/apps/api/src/routes/domain-frequency.tsdeleted file mode 100644index 2d7391c2a..000000000--- a/apps/api/src/routes/domain-frequency.ts+++ /dev/null@@ -1,99 +0,0 @@-import express from "express";-import { config } from "../config";-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(- `/domain-frequency/${config.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(- `/domain-frequency/${config.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(- `/domain-frequency/${config.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/shared.ts b/apps/api/src/routes/shared.tsindex 92079bf72..5ecabd013 100644--- a/apps/api/src/routes/shared.ts+++ b/apps/api/src/routes/shared.ts@@ -14,7 +14,6 @@ import { checkTeamCredits } from "../services/billing/credit_billing";import { isUrlBlocked } from "../scraper/WebScraper/utils/blocklist";import { logger } from "../lib/logger";import { UNSUPPORTED_SITE_MESSAGE } from "../lib/strings";-import { addDomainFrequencyJob } from "../services";import * as geoip from "geoip-country";import { isSelfHosted } from "../lib/deployment";import { validate as isUuid } from "uuid";@@ -142,18 +141,6 @@ 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/services/index.ts b/apps/api/src/services/index.tsindex b22cac240..16630c3a1 100644--- a/apps/api/src/services/index.ts+++ b/apps/api/src/services/index.ts@@ -418,197 +418,6 @@ 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;--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);-}--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,diff --git a/apps/api/src/services/indexing/index-worker.ts b/apps/api/src/services/indexing/index-worker.tsindex e29a3194e..fb883005e 100644--- a/apps/api/src/services/indexing/index-worker.ts+++ b/apps/api/src/services/indexing/index-worker.ts@@ -22,7 +22,6 @@ import {index_supabase_service,processIndexInsertJobs,processOMCEJobs,- processDomainFrequencyJobs,queryDomainsForPrecrawl,} from "..";import { getSearchIndexClient } from "../../lib/search-index-client";@@ -684,7 +683,6 @@ async function tallyBilling() {const INDEX_INSERT_INTERVAL = 3000;const WEBHOOK_INSERT_INTERVAL = 15000;const OMCE_INSERT_INTERVAL = 5000;-const DOMAIN_FREQUENCY_INTERVAL = 10000;// Search indexing is now handled by separate search service, not this worker// const SEARCH_INDEX_INTERVAL = 10000;@@ -739,22 +737,6 @@ const DOMAIN_FREQUENCY_INTERVAL = 10000;});}, OMCE_INSERT_INTERVAL);- const domainFrequencyInterval = setInterval(async () => {- if (isShuttingDown) {- return;- }- await withSpan(- "firecrawl-index-worker-process-domain-frequency-jobs",- async span => {- setSpanAttributes(span, {- "index.worker.operation": "process_domain_frequency_jobs",- "index.worker.type": "scheduled",- });- await processDomainFrequencyJobs();- },- );- }, DOMAIN_FREQUENCY_INTERVAL);-const billingTallyInterval = setInterval(async () => {if (isShuttingDown) {@@ -812,7 +794,6 @@ const DOMAIN_FREQUENCY_INTERVAL = 10000;clearInterval(indexInserterInterval);clearInterval(webhookInserterInterval);clearInterval(omceInserterInterval);- clearInterval(domainFrequencyInterval);clearInterval(billingTallyInterval);logger.info("All workers shut down, exiting process");