File size: 17,812 Bytes
c09f67c | 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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | import { loadDocument } from "@midday/documents/loader";
import {
getContentSample,
isMimeTypeSupportedForProcessing,
} from "@midday/documents/utils";
import { triggerJob, triggerJobAndWait } from "@midday/job-client";
import { createClient } from "@midday/supabase/job";
import type { Job } from "bullmq";
import type { ProcessDocumentPayload } from "../../schemas/documents";
import { getDb } from "../../utils/db";
import { detectFileTypeFromBlob } from "../../utils/detect-file-type";
import { updateDocumentWithRetry } from "../../utils/document-update";
import {
NonRetryableError,
UnsupportedFileTypeError,
} from "../../utils/error-classification";
import {
convertHeicToJpeg,
MAX_HEIC_FILE_SIZE,
} from "../../utils/image-processing";
import { TIMEOUTS, withTimeout } from "../../utils/timeout";
import { BaseProcessor } from "../base";
/**
* Process documents and images for classification
* Handles HEIC conversion, document loading, and triggers classification
*/
export class ProcessDocumentProcessor extends BaseProcessor<ProcessDocumentPayload> {
async process(job: Job<ProcessDocumentPayload>): Promise<void> {
const processStartTime = Date.now();
const { mimetype, filePath, teamId } = job.data;
const supabase = createClient();
const db = getDb();
const fileName = filePath.join("/");
this.logger.info("Starting process-document job", {
jobId: job.id,
teamId,
fileName,
mimetype,
});
// Create activity for document upload
try {
await triggerJob(
"notification",
{
type: "document_uploaded",
teamId,
fileName: filePath.join("/"),
filePath: filePath,
mimeType: mimetype,
},
"notifications",
);
} catch (error) {
// Don't fail the entire process if notification fails
this.logger.warn("Failed to trigger document_uploaded notification", {
teamId,
fileName: filePath.join("/"),
error: error instanceof Error ? error.message : "Unknown error",
});
}
try {
const fileName = filePath.join("/");
let fileData: Blob | null = null;
let processedMimetype = mimetype;
// Download file once and reuse for all operations
// For HEIC files, we'll convert and reuse the converted data
if (mimetype === "image/heic") {
this.logger.info("Converting HEIC to JPG", { filePath: fileName });
const { data } = await withTimeout(
supabase.storage.from("vault").download(fileName),
TIMEOUTS.FILE_DOWNLOAD,
`File download timed out after ${TIMEOUTS.FILE_DOWNLOAD}ms`,
);
if (!data) {
throw new NonRetryableError(
"File not found",
undefined,
"validation",
);
}
await this.updateProgress(
job,
this.ProgressMilestones.FETCHED,
"HEIC file downloaded",
);
const buffer = await data.arrayBuffer();
// Log file size for debugging memory issues
const fileSizeMB = (buffer.byteLength / (1024 * 1024)).toFixed(2);
this.logger.info("HEIC file size", {
fileName,
sizeBytes: buffer.byteLength,
sizeMB: fileSizeMB,
});
// Skip AI classification for very large HEIC files to prevent OOM
// 15MB HEIC ≈ 24MP ≈ ~100MB decoded. Complete with filename instead.
if (buffer.byteLength > MAX_HEIC_FILE_SIZE) {
this.logger.warn(
"HEIC file too large for AI classification - completing with filename",
{
fileName,
teamId,
sizeBytes: buffer.byteLength,
maxSizeBytes: MAX_HEIC_FILE_SIZE,
},
);
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
title: filePath.at(-1) ?? "Large HEIC Image",
summary: `Large image (${fileSizeMB}MB) - AI classification skipped`,
processingStatus: "completed",
},
this.logger,
);
return;
}
// Try to convert HEIC to JPEG - use graceful degradation if it fails (e.g., OOM)
try {
const { buffer: image } = await convertHeicToJpeg(
buffer,
this.logger,
);
await this.updateProgress(
job,
this.ProgressMilestones.PROCESSING,
"HEIC converted to JPEG",
);
// Upload the converted image
const { data: uploadedData } = await withTimeout(
supabase.storage.from("vault").upload(fileName, image, {
contentType: "image/jpeg",
upsert: true,
}),
TIMEOUTS.FILE_UPLOAD,
`File upload timed out after ${TIMEOUTS.FILE_UPLOAD}ms`,
);
if (!uploadedData) {
throw new Error("Failed to upload converted image");
}
await this.updateProgress(
job,
this.ProgressMilestones.HALFWAY,
"Converted image uploaded",
);
// Create Blob from converted image for reuse
fileData = new Blob([image], { type: "image/jpeg" });
processedMimetype = "image/jpeg";
} catch (conversionError) {
// HEIC conversion failed (possibly OOM) - complete with fallback
// User can still see the file and retry later
this.logger.error(
"HEIC conversion failed - completing with fallback",
{
fileName,
teamId,
fileSizeMB,
error:
conversionError instanceof Error
? conversionError.message
: "Unknown error",
},
);
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
title: filePath.at(-1) ?? "HEIC Image",
summary: "HEIC conversion failed - original file preserved",
processingStatus: "completed",
},
this.logger,
);
return;
}
} else {
// Download file for non-HEIC files
const downloadStartTime = Date.now();
this.logger.info("Downloading file from storage", {
jobId: job.id,
fileName,
teamId,
mimetype: processedMimetype,
});
const { data } = await withTimeout(
supabase.storage.from("vault").download(fileName),
TIMEOUTS.FILE_DOWNLOAD,
`File download timed out after ${TIMEOUTS.FILE_DOWNLOAD}ms`,
);
const downloadDuration = Date.now() - downloadStartTime;
this.logger.info("File downloaded", {
jobId: job.id,
fileName,
teamId,
fileSize: data?.size,
duration: `${downloadDuration}ms`,
});
if (!data) {
throw new NonRetryableError(
"File not found",
undefined,
"validation",
);
}
fileData = data;
}
// Detect actual file type for application/octet-stream by checking magic bytes
if (processedMimetype === "application/octet-stream" && fileData) {
try {
const detectionResult = await detectFileTypeFromBlob(fileData);
if (detectionResult.detected) {
this.logger.info(
"Detected file type from application/octet-stream",
{
fileName,
teamId,
detectedMimetype: detectionResult.mimetype,
},
);
processedMimetype = detectionResult.mimetype;
// Recreate Blob with correct mimetype for further processing
fileData = new Blob([detectionResult.buffer], {
type: detectionResult.mimetype,
});
} else {
// Unknown file type - log warning and skip processing
this.logger.warn(
"application/octet-stream file type could not be detected - skipping processing",
{
fileName,
teamId,
header: detectionResult.buffer.subarray(0, 8).toString("hex"),
},
);
// Update document status to indicate it's not processable
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
processingStatus: "failed",
},
this.logger,
);
return;
}
} catch (error) {
this.logger.error(
"Failed to detect file type for application/octet-stream - will attempt to process as PDF",
{
fileName,
teamId,
error: error instanceof Error ? error.message : "Unknown error",
},
);
// If detection fails, try to process as PDF (most common case)
// Re-download the file since we may have consumed the buffer
const { data: redownloadedData } = await withTimeout(
supabase.storage.from("vault").download(fileName),
TIMEOUTS.FILE_DOWNLOAD,
`File re-download timed out after ${TIMEOUTS.FILE_DOWNLOAD}ms`,
);
if (redownloadedData) {
fileData = redownloadedData;
processedMimetype = "application/pdf";
} else {
throw new Error("Failed to re-download file for type detection");
}
}
}
// Check if file type is supported - throw error for queue config to handle
if (!isMimeTypeSupportedForProcessing(processedMimetype)) {
throw new UnsupportedFileTypeError(processedMimetype, fileName);
}
// If the file is an image, trigger image classification
if (processedMimetype.startsWith("image/")) {
this.logger.info("Triggering image classification", {
fileName,
teamId,
});
// Trigger image classification via BullMQ and wait for completion
// This ensures errors propagate and status is properly updated
// Use CLASSIFICATION_JOB_WAIT timeout to ensure we don't timeout before the child job completes
// Child job uses AI_CLASSIFICATION (90s) + FILE_DOWNLOAD (60s), so we need at least 150s
// NOTE: Job IDs must include timestamp for reprocessing to work - BullMQ returns existing
// jobs instead of creating new ones when IDs match (completed retained 24h, failed 7 days)
await triggerJobAndWait(
"classify-image",
{
fileName,
teamId,
},
"documents",
{
jobId: `classify-img_${teamId}_${fileName}_${Date.now()}`,
timeout: TIMEOUTS.CLASSIFICATION_JOB_WAIT,
},
);
return;
}
// Process document: load and classify
// Use graceful degradation - if content extraction fails, complete with null values
let document: string | null = null;
let documentLoadFailed = false;
try {
const parseStartTime = Date.now();
this.logger.info("Parsing document content (extracting text)", {
jobId: job.id,
fileName,
teamId,
mimetype: processedMimetype,
fileSize: fileData?.size,
});
// 60 second timeout for document parsing - prevents hanging on corrupt/problematic files
const loadedDoc = await withTimeout(
loadDocument({
content: fileData,
metadata: { mimetype: processedMimetype },
}),
60_000,
"Document parsing timed out after 60000ms",
);
if (!loadedDoc) {
throw new Error("Failed to load document");
}
document = loadedDoc;
const parseDuration = Date.now() - parseStartTime;
this.logger.info("Document parsed successfully", {
jobId: job.id,
fileName,
teamId,
contentLength: document.length,
duration: `${parseDuration}ms`,
});
} catch (error) {
// Log error but don't fail - complete with null values so user can still access file
documentLoadFailed = true;
this.logger.warn(
"Failed to extract document content - completing with fallback",
{
jobId: job.id,
fileName,
teamId,
mimetype: processedMimetype,
error: error instanceof Error ? error.message : "Unknown error",
},
);
}
// If document loading failed, complete with null values
// User can still view/download the file and retry classification later
if (documentLoadFailed || !document) {
this.logger.info(
"Completing document with null values - user can retry classification",
{
fileName,
teamId,
documentLoadFailed,
},
);
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
title: undefined, // null - UI will show filename + retry option
summary: undefined,
processingStatus: "completed",
},
this.logger,
);
return;
}
// Edge case: Validate document has content
if (document.trim().length === 0) {
this.logger.warn("Document loaded but has no extractable content", {
fileName,
teamId,
});
// Complete with null - user can still access the file
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
title: undefined,
summary: undefined,
processingStatus: "completed",
},
this.logger,
);
return;
}
const sample = getContentSample(document);
// Edge case: Validate sample has content
if (!sample || sample.trim().length === 0) {
this.logger.warn(
"Document sample is empty, marking as completed without classification",
{
fileName,
teamId,
contentLength: document.length,
},
);
// Mark as completed - document exists but has no extractable content to classify
await updateDocumentWithRetry(
db,
{
pathTokens: filePath,
teamId,
processingStatus: "completed",
},
this.logger,
);
return;
}
const classificationStartTime = Date.now();
this.logger.info("Triggering document classification", {
jobId: job.id,
fileName,
teamId,
contentLength: document.length,
sampleLength: sample.length,
});
// Trigger document classification via BullMQ and wait for completion
// This ensures errors propagate and status is properly updated
// Use CLASSIFICATION_JOB_WAIT timeout to ensure we don't timeout before the child job completes
// Child job uses AI_CLASSIFICATION (90s), so we need at least that + overhead
// NOTE: Job IDs must include timestamp for reprocessing to work - BullMQ returns existing
// jobs instead of creating new ones when IDs match (completed retained 24h, failed 7 days)
const classificationJobResult = await triggerJobAndWait(
"classify-document",
{
content: sample,
fileName,
teamId,
},
"documents",
{
jobId: `classify-doc_${teamId}_${fileName}_${Date.now()}`,
timeout: TIMEOUTS.CLASSIFICATION_JOB_WAIT,
},
);
const classificationDuration = Date.now() - classificationStartTime;
this.logger.info("Document classification job completed", {
jobId: job.id,
fileName,
teamId,
triggeredJobId: classificationJobResult.id,
triggeredJobName: "classify-document",
duration: `${classificationDuration}ms`,
});
// Create activity for successful document processing
try {
await triggerJob(
"notification",
{
type: "document_processed",
teamId,
fileName,
filePath: filePath,
mimeType: mimetype,
contentLength: document.length,
sampleLength: sample.length,
},
"notifications",
);
} catch (error) {
// Don't fail the entire process if notification fails
this.logger.warn("Failed to trigger document_processed notification", {
teamId,
fileName,
error: error instanceof Error ? error.message : "Unknown error",
});
}
const totalDuration = Date.now() - processStartTime;
this.logger.info("process-document job completed successfully", {
jobId: job.id,
fileName,
teamId,
contentLength: document.length,
sampleLength: sample.length,
totalDuration: `${totalDuration}ms`,
});
} catch (error) {
this.logger.error("Document processing failed", {
fileName: filePath.join("/"),
teamId,
error: error instanceof Error ? error.message : "Unknown error",
});
// Status update to "failed" is handled by handleDocumentJobFinalFailure
// in documents.config.ts when all retries are exhausted
throw error;
}
}
}
|