Files
firecrawl/apps/api/src/controllers/crawl-cancel.ts
T

75 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-05-06 17:16:43 -07:00
import { Request, Response } from "express";
import { authenticateUser } from "./auth";
import { RateLimiterMode } from "../../src/types";
import { getWebScraperQueue } from "../../src/services/queue-service";
import { supabase_service } from "../../src/services/supabase";
2024-05-06 17:22:16 -07:00
import { billTeam } from "../../src/services/billing/credit_billing";
2024-07-23 17:30:46 -03:00
import { Logger } from "../../src/lib/logger";
2024-05-06 17:16:43 -07:00
export async function crawlCancelController(req: Request, res: Response) {
try {
2024-07-07 15:06:31 +02:00
const useDbAuthentication = process.env.USE_DB_AUTHENTICATION === 'true';
2024-05-06 17:16:43 -07:00
const { success, team_id, error, status } = await authenticateUser(
req,
res,
RateLimiterMode.CrawlStatus
);
if (!success) {
return res.status(status).json({ error });
}
const job = await getWebScraperQueue().getJob(req.params.jobId);
if (!job) {
return res.status(404).json({ error: "Job not found" });
}
// check if the job belongs to the team
2024-07-07 15:06:31 +02:00
if (useDbAuthentication) {
const { data, error: supaError } = await supabase_service
.from("bulljobs_teams")
.select("*")
.eq("job_id", req.params.jobId)
.eq("team_id", team_id);
if (supaError) {
return res.status(500).json({ error: supaError.message });
}
2024-05-06 17:16:43 -07:00
2024-07-07 15:06:31 +02:00
if (data.length === 0) {
return res.status(403).json({ error: "Unauthorized" });
}
2024-05-06 17:16:43 -07:00
}
2024-07-07 15:06:31 +02:00
2024-05-06 17:22:16 -07:00
const jobState = await job.getState();
2024-07-30 13:27:23 -04:00
let progress = job.progress;
if(typeof progress !== 'object') {
progress = {
partialDocs: []
}
}
const {
partialDocs = []
} = progress as { partialDocs: any[] };
2024-05-06 17:22:16 -07:00
if (partialDocs && partialDocs.length > 0 && jobState === "active") {
2024-07-23 17:30:46 -03:00
Logger.info("Billing team for partial docs...");
2024-05-06 17:22:16 -07:00
// Note: the credits that we will bill them here might be lower than the actual
// due to promises that are not yet resolved
await billTeam(team_id, partialDocs.length);
}
2024-05-06 17:16:43 -07:00
try {
2024-08-06 16:26:46 +02:00
await (await getWebScraperQueue().client).set("cancelled:" + job.id, "true", "EX", 60 * 60);
await job.discard();
2024-05-06 17:16:43 -07:00
} catch (error) {
2024-07-23 17:30:46 -03:00
Logger.error(error);
2024-05-06 17:16:43 -07:00
}
res.json({
2024-07-18 13:43:03 -04:00
status: "cancelled"
2024-05-06 17:16:43 -07:00
});
} catch (error) {
2024-07-23 17:30:46 -03:00
Logger.error(error);
2024-05-06 17:16:43 -07:00
return res.status(500).json({ error: error.message });
}
}