Spaces:
Sleeping
Sleeping
File size: 6,691 Bytes
097eaf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | import "dotenv/config";
import { config } from "../config";
import "./sentry";
import { setSentryServiceTag } from "./sentry";
import * as Sentry from "@sentry/node";
import { logger as _logger } from "../lib/logger";
import { configDotenv } from "dotenv";
import { ExtractResult } from "../lib/extract/extraction-service";
import { updateExtract } from "../lib/extract/extract-redis";
import { performExtraction_F0 } from "../lib/extract/fire-0/extraction-service-f0";
import { createWebhookSender, WebhookEvent } from "./webhook";
import Express from "express";
import { getErrorContactMessage } from "../lib/deployment";
import { TransportableError } from "../lib/error";
import { initializeBlocklist } from "../scraper/WebScraper/utils/blocklist";
import { initializeEngineForcing } from "../scraper/WebScraper/utils/engine-forcing";
import {
consumeExtractJobs,
consumeExtractDLQ,
shutdownExtractQueue,
ExtractJobData,
} from "./extract-queue";
import { logExtract } from "./logging/log_job";
import { jobDurationSeconds } from "../lib/job-metrics";
import { register } from "prom-client";
configDotenv();
const processExtractJob = async (
data: ExtractJobData,
ack: () => void,
nack: () => void,
) => {
const logger = _logger.child({
module: "extract-worker",
method: "processExtractJob",
extractId: data.extractId,
teamId: data.teamId,
});
const sender = await createWebhookSender({
teamId: data.teamId,
jobId: data.extractId,
webhook: data.request.webhook,
v0: false,
});
const endJobTimer = jobDurationSeconds.startTimer({ type: "extract" });
try {
if (sender) {
sender.send(WebhookEvent.EXTRACT_STARTED, {
success: true,
});
}
let result: ExtractResult | null = null;
result = await performExtraction_F0(data.extractId, {
request: data.request,
teamId: data.teamId,
subId: data.subId ?? undefined,
apiKeyId: data.apiKeyId ?? null,
});
if (result && result.success) {
await updateExtract(data.extractId, {
status: "completed",
llmUsage: result.llmUsage,
sources: result.sources,
tokensBilled: result.tokensBilled,
creditsBilled: result.creditsBilled,
});
if (sender) {
sender.send(WebhookEvent.EXTRACT_COMPLETED, {
success: true,
data: [result],
});
}
endJobTimer({ status: "success" });
ack();
return;
} else {
await updateExtract(data.extractId, {
status: "failed",
error: result?.error ?? getErrorContactMessage(data.extractId),
});
if (sender) {
sender.send(WebhookEvent.EXTRACT_FAILED, {
success: false,
error: result?.error ?? getErrorContactMessage(data.extractId),
});
}
endJobTimer({ status: "failed" });
ack();
return;
}
} catch (error) {
endJobTimer({ status: "failed" });
logger.error(`🚫 Extract job errored ${data.extractId} - ${error}`, {
error,
});
// Filter out TransportableErrors (flow control)
if (!(error instanceof TransportableError)) {
Sentry.captureException(error, {
data: {
extractId: data.extractId,
},
});
}
await updateExtract(data.extractId, {
status: "failed",
error:
(error as any)?.error ??
(error as any)?.message ??
getErrorContactMessage(data.extractId),
});
if (sender) {
sender.send(WebhookEvent.EXTRACT_FAILED, {
success: false,
error:
(error as any)?.message ?? getErrorContactMessage(data.extractId),
});
}
// Ack the message even on error - we've handled it and updated the DB
// Only nack if we want to send to DLX (which we don't for handled errors)
ack();
}
};
const processDLQJob = async (data: ExtractJobData) => {
const logger = _logger.child({
module: "extract-dlq",
extractId: data.extractId,
teamId: data.teamId,
});
logger.error("Processing crashed extract job from DLQ");
// Update the extract status to failed in the database
await updateExtract(data.extractId, {
status: "failed",
error:
"Extract job crashed unexpectedly. Please try again or contact support if the issue persists.",
});
await logExtract({
id: data.extractId,
request_id: data.extractId,
urls: data.request.urls,
team_id: data.teamId,
options: data.request,
model_kind: data.request.agent?.model ?? "fire-0",
credits_cost: 0,
is_successful: false,
error:
"Extract job crashed unexpectedly. Please try again or contact support if the issue persists.",
cost_tracking: undefined,
});
// Send webhook notification
const sender = await createWebhookSender({
teamId: data.teamId,
jobId: data.extractId,
webhook: data.request.webhook,
v0: false,
});
if (sender) {
sender.send(WebhookEvent.EXTRACT_FAILED, {
success: false,
error:
"Extract job crashed unexpectedly. Please try again or contact support if the issue persists.",
});
}
logger.info("DLQ job processed - extract marked as failed");
};
// Start the worker
const app = Express();
app.get("/health", (req, res) => {
res.status(200).json({ ok: true });
});
app.get("/liveness", (req, res) => {
res.status(200).json({ ok: true });
});
app.get("/metrics", async (_, res) => {
res.contentType("text/plain").send(await register.metrics());
});
const workerPort = config.EXTRACT_WORKER_PORT || config.PORT;
app.listen(workerPort, () => {
_logger.info(
`Extract worker health endpoint is running on port ${workerPort}`,
);
});
async function shutdown() {
_logger.info("Shutting down extract worker...");
await shutdownExtractQueue();
_logger.info("Extract worker shut down");
process.exit(0);
}
if (require.main === module) {
process.on("SIGINT", () => {
_logger.debug("Received SIGINT. Shutting down gracefully...");
shutdown();
});
process.on("SIGTERM", () => {
_logger.debug("Received SIGTERM. Shutting down gracefully...");
shutdown();
});
}
(async () => {
setSentryServiceTag("extract-worker");
await initializeBlocklist().catch(e => {
_logger.error("Failed to initialize blocklist", { error: e });
process.exit(1);
});
initializeEngineForcing();
_logger.info("Starting extract worker with RabbitMQ...");
// Start consuming from both the main queue and the DLQ
await Promise.all([
consumeExtractJobs(processExtractJob),
consumeExtractDLQ(processDLQJob),
]);
_logger.info("Extract worker started, consuming from RabbitMQ");
})();
|