firecrawl/apps/api/src/controllers/v0/crawl-status.ts

61 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-04-20 16:38:05 -07:00
import { Request, Response } from "express";
import { authenticateUser } from "./auth";
2024-08-15 21:51:59 +02:00
import { RateLimiterMode } from "../../../src/types";
import { getScrapeQueue } from "../../../src/services/queue-service";
import { Logger } from "../../../src/lib/logger";
import { getCrawl, getCrawlJobs } from "../../../src/lib/crawl-redis";
import { supabaseGetJobById } from "../../../src/lib/supabase-jobs";
2024-04-20 16:38:05 -07:00
export async function crawlStatusController(req: Request, res: Response) {
try {
const { success, team_id, error, status } = await authenticateUser(
req,
res,
RateLimiterMode.CrawlStatus
);
if (!success) {
return res.status(status).json({ error });
}
2024-08-13 20:51:43 +02:00
const sc = await getCrawl(req.params.jobId);
if (!sc) {
2024-04-20 16:38:05 -07:00
return res.status(404).json({ error: "Job not found" });
}
2024-08-13 21:40:59 +02:00
if (sc.team_id !== team_id) {
return res.status(403).json({ error: "Forbidden" });
}
2024-08-13 20:51:43 +02:00
const jobIDs = await getCrawlJobs(req.params.jobId);
2024-08-06 16:26:46 +02:00
2024-08-13 21:55:13 +02:00
const jobs = (await Promise.all(jobIDs.map(async x => {
2024-08-13 21:40:59 +02:00
const job = await getScrapeQueue().getJob(x);
if (process.env.USE_DB_AUTHENTICATION === "true") {
const supabaseData = await supabaseGetJobById(job.id);
2024-08-13 21:40:59 +02:00
if (supabaseData) {
job.returnvalue = supabaseData.docs;
}
}
2024-08-13 21:40:59 +02:00
return job;
2024-08-13 21:55:13 +02:00
}))).sort((a, b) => a.timestamp - b.timestamp);
2024-08-13 20:51:43 +02:00
const jobStatuses = await Promise.all(jobs.map(x => x.getState()));
const jobStatus = sc.cancelled ? "failed" : jobStatuses.every(x => x === "completed") ? "completed" : jobStatuses.some(x => x === "failed") ? "failed" : "active";
2024-08-13 20:51:43 +02:00
const data = jobs.map(x => Array.isArray(x.returnvalue) ? x.returnvalue[0] : x.returnvalue);
2024-04-20 16:38:05 -07:00
res.json({
2024-08-13 20:51:43 +02:00
status: jobStatus,
current: jobStatuses.filter(x => x === "completed" || x === "failed").length,
total: jobs.length,
data: jobStatus === "completed" ? data : null,
partial_data: jobStatus === "completed" ? [] : data.filter(x => x !== null),
2024-04-20 16:38:05 -07:00
});
} catch (error) {
2024-07-25 09:48:06 -03:00
Logger.error(error);
2024-04-20 16:38:05 -07:00
return res.status(500).json({ error: error.message });
}
}