import { prisma } from '@omniloq/db'; import type { Job } from '@omniloq/db'; import { runAgentPersisted } from './runtime'; import { resolveChannel } from './channel-resolver'; import { extractText } from './text'; export interface ProcessJobOptions { fetchImpl?: typeof fetch; /** Cible un job précis (tests / reprise ciblée). Sinon FIFO avec SKIP LOCKED. */ jobId?: string; } /** * Worker : claim un Job (SKIP LOCKED, ou `jobId` ciblé), exécute le runtime (qui * persiste un Message outbound `queued`), puis envoie via le canal et met à jour le * Message (`queued → sent` avec wamid, ou `failed` avec l'erreur Graph API). * Aucune transaction longue : le claim est une TX courte, le LLM/MCP/envoi hors TX. */ export async function processNextJob(options: ProcessJobOptions = {}): Promise { let claimed: Job | null = null; if (options.jobId) { const job = await prisma.job.findUnique({ where: { id: options.jobId } }); if (job && job.status === 'pending') { claimed = await prisma.job.update({ where: { id: options.jobId }, data: { status: 'locked', lockedAt: new Date(), lockExpiresAt: new Date(Date.now() + 60_000), attempts: { increment: 1 }, }, }); } } else { claimed = await prisma.$transaction(async (tx) => { const rows = await tx.$queryRaw>` SELECT id FROM "Job" WHERE status = 'pending' AND "availableAt" <= now() ORDER BY "createdAt" ASC LIMIT 1 FOR UPDATE SKIP LOCKED `; if (rows.length === 0) return null; return tx.job.update({ where: { id: rows[0].id }, data: { status: 'locked', lockedAt: new Date(), lockExpiresAt: new Date(Date.now() + 60_000), attempts: { increment: 1 }, }, }); }); } if (!claimed) return false; try { await executeJob(claimed, options.fetchImpl); await prisma.job.update({ where: { id: claimed.id }, data: { status: 'done' } }); } catch (e) { console.error(`[worker] job ${claimed.id} failed:`, e); await prisma.job.update({ where: { id: claimed.id }, data: { status: 'failed' } }).catch(() => {}); } return true; } async function executeJob(job: Job, fetchImpl?: typeof fetch): Promise { const conversationId = job.conversationId; // 1. Runtime : génère la réponse, persiste Message outbound `queued` const result = await runAgentPersisted(conversationId); // 2. Retrouver le Message outbound `queued` de ce run const outbound = await prisma.message.findFirst({ where: { runId: result.runId, direction: 'outbound', status: 'queued' }, orderBy: { createdAt: 'desc' }, }); if (!outbound) return; // rien à envoyer (ne devrait pas arriver) // 3. Résoudre la conversation + le canal const conversation = await prisma.conversation.findUnique({ where: { id: conversationId }, include: { channelIdentity: true }, }); if (!conversation) throw new Error('conversation not found'); const channel = await resolveChannel(conversation.channelIdentity.channelAccountId, fetchImpl); // 4. Envoyer (persister d'abord est déjà fait : status=queued) const text = extractText(outbound.content); const sendResult = await channel.sendMessage(conversation.channelIdentity.externalUserId, text); // 5. Mettre à jour le Message outbound if (sendResult.status === 'sent') { await prisma.message.update({ where: { id: outbound.id }, data: { status: 'sent', externalMessageId: sendResult.externalMessageId }, }); } else { await prisma.message.update({ where: { id: outbound.id }, data: { status: 'failed', providerMetadata: { error: sendResult.error } as any }, }); } }