Files
B2BCall-dialer/apps/predictive-dialer/src/tick.ts
Matheus c24a86776c feat(recording): gravacao de chamadas + object storage abstraction
Fecha agente.md secao 90-94. A especificacao lista "Recording" e "Object
Storage" como dois passos separados na ordem de implementacao (secao
232), mas ficaram numa unica fase — sao acoplados o suficiente (Recording
precisa de um lugar pra guardar bytes) pra fazer sentido construir juntos.

## packages/storage — ObjectStorageProvider (secao 92)

Abstracao pequena: putObject/getObjectStream/deleteObject. Dois backends:
LocalObjectStorageProvider (filesystem, com checagem de path traversal
mesmo a key sendo sempre montada no servidor) e S3ObjectStorageProvider
(@aws-sdk/client-s3, preparado pra AWS S3 e MinIO via endpoint/
forcePathStyle customizaveis — nunca exercitado nesta sessao, sem
servidor S3 disponivel neste laboratorio). Escolhido por STORAGE_PROVIDER
env.

buildRecordingObjectKey (secao 93):
tenants/{tenant_id}/recordings/YYYY/MM/DD/{call_id}.wav, sempre montada
no servidor a partir de dados confiaveis.

## Bind mounts, nao volumes nomeados

/recordings e /data/object-storage usam bind mount pra um diretorio real
do host — apps/api roda no host, nao em Docker, e precisa enxergar os
mesmos arquivos que fs-events escreve. LOCAL_STORAGE_ROOT tem valores
diferentes por ambiente (mesmo padrao ja usado pra REDIS_URL).

## Quem grava: apps/predictive-dialer

So' chamadas originadas pelo discador com Campaign.recordingEnabled sao
gravadas nesta fase (unico caminho de originate que o sistema controla
hoje). RECORD_STEREO=true + execute_on_answer='record_session ...'
adicionados ao originate; origination_uuid pre-gerado (em vez de deixar o
provider sortear) porque o path de gravacao precisa dele antes do
comando de originate ser montado — o mesmo uuid vira Call.id no CDR.

## Quem sobe: apps/freeswitch-events/src/recording.ts

Em CALL_ENDED, encadeado depois do persistCallEvent terminar (nao em
paralelo) — uploadRecordingIfPresent le Call.talkTime/durationSeconds,
que e' exatamente o que persistCallEvent acabou de calcular no mesmo
evento (mesma classe de corrida ja corrigida uma vez na fase CDR, aqui
evitada por ordenacao). Sobe pro storage, cria Recording (retentionUntil
a partir de Plan.recordingRetentionDays), apaga o spool local.

## API + retencao

GET /recordings, GET /recordings/:id, GET /recordings/:id/audio (stream
autenticado, nunca URL direta pro storage). runRetentionSweep (secao 94)
no boot do apps/api + a cada hora — apaga o objeto, marca status=DELETED
(linha nunca apagada, fica como auditoria).

## Bug real achado testando esta fase

Recording.sizeBytes (BigInt) quebrava GET /recordings com 500 — Fastify
nao serializa BigInt nativamente (mesma classe de bug ja corrigida uma
vez no logger, fase Event Socket). Corrigido convertendo pra number na
resposta.

Verificado ponta a ponta: gravacao real criada (RIFF WAVE, PCM 16-bit,
ESTEREO 8000Hz — RECORD_STEREO confirmado), upload com path exato da
secao 93, download via API com md5 identico ao objeto original, varredura
de retencao apagando objeto + status DELETED + list/download bloqueados
depois. typecheck do workspace inteiro limpo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1HxY46WGU4G1zmVDNKcWw
2026-08-28 14:36:03 -03:00

247 lines
8.9 KiB
TypeScript

import type Redis from "ioredis";
import { getPrismaClient, withTenantContext, type Campaign, type Tenant } from "@b2bcall/database";
import type { FreeSwitchTelephonyProvider } from "@b2bcall/telephony";
import { createLogger } from "@b2bcall/shared";
import { tryAcquireCps } from "./redis-primitives";
import { reserveLeads } from "./lead-reservation";
import { computeCapacity, decidePacing } from "./pacing";
import { isWithinSchedule } from "./schedule";
import { simulateOutcome } from "./simulation";
import { originateSimulatedAnswerLeg, originateRealPstnLeg } from "./originate";
import { createCallAttempt, setAttemptStatus, completeAttempt } from "./call-attempt";
import { registerQueuedAttempt } from "./queued-attempts-registry";
const logger = createLogger("b2bcall-predictive-dialer");
export interface TickDeps {
redis: Redis;
provider: FreeSwitchTelephonyProvider;
dialerSimulation: boolean;
allowRealOutboundCalls: boolean;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function tickCampaign(deps: TickDeps, tenant: Tenant, campaign: Campaign): Promise<void> {
const prisma = getPrismaClient();
if (!isWithinSchedule(campaign)) {
if (campaign.status === "RUNNING") {
await withTenantContext(prisma, tenant.id, (tx) =>
tx.campaign.update({ where: { id: campaign.id }, data: { status: "WAITING_SCHEDULE" } }),
);
logger.info("campanha fora da janela de funcionamento", { campaignId: campaign.id });
}
return;
}
if (campaign.status === "WAITING_SCHEDULE") {
await withTenantContext(prisma, tenant.id, (tx) =>
tx.campaign.update({ where: { id: campaign.id }, data: { status: "RUNNING" } }),
);
}
const stats = await withTenantContext(prisma, tenant.id, (tx) =>
tx.campaignStats.upsert({
where: { campaignId: campaign.id },
update: {},
create: { campaignId: campaign.id, tenantId: tenant.id, pacingFactor: campaign.pacingInitial },
}),
);
const capacity = await withTenantContext(prisma, tenant.id, (tx) => computeCapacity(tx, tenant.id, campaign, stats));
const { callsToOriginate, newPacingFactor } = decidePacing(campaign, stats, capacity);
if (newPacingFactor !== stats.pacingFactor) {
await withTenantContext(prisma, tenant.id, (tx) =>
tx.campaignStats.update({ where: { campaignId: campaign.id }, data: { pacingFactor: newPacingFactor } }),
);
}
if (callsToOriginate <= 0) return;
const reserved = await withTenantContext(prisma, tenant.id, (tx) =>
reserveLeads(tx, tenant.id, campaign.id, callsToOriginate),
);
if (reserved.length === 0) return;
logger.info("originando tentativas", {
campaignId: campaign.id,
count: reserved.length,
availableAgents: capacity.availableAgents,
predictedBecomingAvailable: capacity.predictedBecomingAvailable,
pacingFactor: newPacingFactor,
answerProbability: stats.answerProbability,
});
for (const lead of reserved) {
const cpsChecks = [
{ key: "cps:global", maxPerSecond: 0 }, // sem teto global configurado nesta fase
{ key: `cps:tenant:${tenant.id}`, maxPerSecond: (await getTenantMaxCps(tenant.id)) ?? 0 },
{ key: `cps:campaign:${campaign.id}`, maxPerSecond: campaign.maxCps ?? 0 },
{ key: `cps:trunk:${campaign.trunkId}`, maxPerSecond: 0 }, // Trunk.maxCps já e' opcional; aplicado no real-outbound path
];
const allowed = await tryAcquireCps(deps.redis, cpsChecks);
if (!allowed) {
// De volta pra READY: essa reserva não gerou tentativa nenhuma, não
// conta como attempt (agente.md secao 62: hierarquia de CPS respeitada
// antes de originar, não depois).
await withTenantContext(prisma, tenant.id, (tx) =>
tx.lead.update({ where: { id: lead.id }, data: { status: "READY" } }),
);
continue;
}
await originateOneAttempt(deps, tenant, campaign, lead.id);
}
}
async function getTenantMaxCps(tenantId: string): Promise<number | null> {
const prisma = getPrismaClient();
const tenant = await prisma.tenant.findUniqueOrThrow({ where: { id: tenantId }, include: { plan: true } });
return tenant.plan.maxCps;
}
async function originateOneAttempt(
deps: TickDeps,
tenant: Tenant,
campaign: Campaign,
leadId: string,
): Promise<void> {
const prisma = getPrismaClient();
const simulated = deps.dialerSimulation || !deps.allowRealOutboundCalls;
const attempt = await withTenantContext(prisma, tenant.id, (tx) =>
createCallAttempt(tx, { tenantId: tenant.id, campaignId: campaign.id, leadId, simulated }),
);
if (simulated) {
runSimulatedAttempt(deps, tenant, campaign, leadId, attempt.id).catch((err) => {
logger.error("falha na simulacao da tentativa", { error: String(err), attemptId: attempt.id });
});
return;
}
await runRealAttempt(deps, tenant, campaign, leadId, attempt.id);
}
/**
* Modo simulação (agente.md secao 185): sorteia o desfecho da "chamada
* PSTN" inteiramente em software (RINGING -> ANSWER/BUSY/NO_ANSWER/FAILED
* com delay), sem tocar o FreeSWITCH pra isso. Só quando o sorteio dá
* ANSWERED é que uma chamada real (sintética, sem PSTN) entra na fila de
* verdade — a partir daí quem decide o resto é o mod_callcenter real,
* observado via event-listener.ts.
*/
async function runSimulatedAttempt(
deps: TickDeps,
tenant: Tenant,
campaign: Campaign,
leadId: string,
attemptId: string,
): Promise<void> {
const prisma = getPrismaClient();
const stats = await withTenantContext(prisma, tenant.id, (tx) =>
tx.campaignStats.findUniqueOrThrow({ where: { campaignId: campaign.id } }),
);
const outcome = simulateOutcome(campaign.ringTimeout, stats.averageTalkTime);
await withTenantContext(prisma, tenant.id, (tx) => setAttemptStatus(tx, attemptId, "RINGING", { ringingAt: new Date() }));
await sleep(outcome.ringDelayMs);
if (outcome.type !== "ANSWERED") {
await withTenantContext(prisma, tenant.id, (tx) =>
completeAttempt(
tx,
{
attemptId,
tenantId: tenant.id,
campaignId: campaign.id,
leadId,
outcome: outcome.type as "BUSY" | "NO_ANSWER" | "FAILED",
reachedQueue: false,
},
campaign.maxAttempts,
),
);
return;
}
const answerDelaySeconds = outcome.ringDelayMs / 1000;
await withTenantContext(prisma, tenant.id, (tx) => setAttemptStatus(tx, attemptId, "ANSWERED", { answeredAt: new Date() }));
const { uuid } = await originateSimulatedAnswerLeg(
deps.provider,
{ tenantId: tenant.id, attemptId, campaignId: campaign.id, leadId },
campaign.queueId,
tenant.telephonyDomain ?? "",
campaign.recordingEnabled,
);
registerQueuedAttempt(uuid, {
attemptId,
tenantId: tenant.id,
campaignId: campaign.id,
leadId,
maxAttempts: campaign.maxAttempts,
queuedAtMs: Date.now(),
answerDelaySeconds,
});
await withTenantContext(prisma, tenant.id, (tx) => setAttemptStatus(tx, attemptId, "QUEUEING", { originationUuid: uuid }));
// A perna sintética (null/dummy) não tem mídia real do outro lado — nada
// faz a chamada terminar sozinha depois de bridgear com um agente
// (diferente de uma ligação PSTN de verdade, onde o cliente desliga).
// Encerra explicitamente depois do talk_time simulado; se a chamada já
// tiver terminado antes disso (abandonada na fila, por exemplo),
// `killCall` num uuid que não existe mais só retorna erro, sem efeito.
setTimeout(() => {
deps.provider.killCall(uuid, "NORMAL_CLEARING").catch(() => undefined);
}, outcome.talkTimeSeconds! * 1000);
}
/**
* Perna PSTN real (agente.md secao 80-83, 186) — só chamada quando as DUAS
* flags de segurança estão explicitamente ligadas. Nunca exercitada nesta
* sessão (sem trunk/operadora real disponível) — ver
* docs/PREDICTIVE_DIALER.md.
*/
async function runRealAttempt(
deps: TickDeps,
tenant: Tenant,
campaign: Campaign,
leadId: string,
attemptId: string,
): Promise<void> {
const prisma = getPrismaClient();
const lead = await withTenantContext(prisma, tenant.id, (tx) => tx.lead.findUniqueOrThrow({ where: { id: leadId } }));
const { uuid } = await originateRealPstnLeg(
deps.provider,
{ tenantId: tenant.id, attemptId, campaignId: campaign.id, leadId },
{
trunkId: campaign.trunkId,
phoneNumber: lead.phoneNormalized,
queueId: campaign.queueId,
domain: tenant.telephonyDomain ?? "",
callerIdName: campaign.callerIdName ?? undefined,
callerIdNumber: campaign.callerIdNumber ?? undefined,
ringTimeoutSeconds: campaign.ringTimeout,
recordingEnabled: campaign.recordingEnabled,
},
);
registerQueuedAttempt(uuid, {
attemptId,
tenantId: tenant.id,
campaignId: campaign.id,
leadId,
maxAttempts: campaign.maxAttempts,
queuedAtMs: Date.now(),
});
await withTenantContext(prisma, tenant.id, (tx) => setAttemptStatus(tx, attemptId, "ORIGINATING", { originationUuid: uuid }));
}