feat(dialer): CPS Limiter + Predictive Dialer Engine
Fecha agente.md secao 72-86 (motor preditivo) e 77-79 (CPS distribuido,
reserva de leads, lock de campanha). Uma campanha RUNNING agora origina
chamadas sozinha, respeitando capacidade de agentes, CPS hierarquico e
taxa de abandono — sem intervencao manual.
Deliberadamente fora do escopo (agente.md secao 72: "nao e' so' `for lead
-> originate`"): mod_avmd (opcional), callbacks agendados, disposicoes de
agente — ficam pra fase CDR.
## Novo servico apps/predictive-dialer
Mesmo padrao arquitetural de fs-events/fs-config: Node standalone em
Docker, ESL propria, tick a cada 2s sobre tenants ativos x campanhas
RUNNING/WAITING_SCHEDULE.
- Lock de campanha (dialer:campaign:{id}, secao 79): TTL/ownership/
renewal/safe-release via Lua compare-and-delete.
- CPS distribuido (secao 77, 62): token bucket janela 1s, hierarquia
GLOBAL/TENANT/TRUNK/CAMPAIGN numa unica chamada Lua atomica — nivel
esgotado bloqueia todos SEM incremento parcial dos que passariam.
- Reserva atomica de leads (secao 78): FOR UPDATE SKIP LOCKED dentro da
mesma transacao withTenantContext.
- CallAttempt/CampaignStats (schema novo): state machine da chamada
(secao 82) + EWMA (secao 75) de answer_probability/average_answer_delay/
average_talk_time/abandon_rate por campanha.
- Capacidade em tempo real + pacing (secao 73-76, 84-85): conta agentes
por estado via Tier->Agent.state, previsao de liberacao (horizonte
unico de 15s, simplificacao documentada dos 4 buckets da especificacao),
controle de abandono reduz pacing progressivamente, nunca origina sem
capacidade prevista.
## Modo simulacao (secao 185-186)
DIALER_SIMULATION=true (default, ja estava no .env desde o inicio da
sessao) sorteia ANSWER/BUSY/NO_ANSWER/FAILED em software, sem PSTN real.
So' quando ANSWERED e' que uma chamada sintetica (null/dummy, sem PSTN)
entra na fila real via mod_callcenter de verdade — escolha deliberada pra
maximizar codigo real exercitado em vez de simular tudo em memoria. Os
identificadores da secao 81 (b2bcall_tenant_id/call_id/attempt_id/
campaign_id/lead_id) vao como channel variables nessa perna, entregando
tenantId real no WebSocket sem fan-out.
Real Outbound Safety (secao 186): as duas flags checadas no boot, nunca
ativadas automaticamente — caminho PSTN real implementado mas nunca
exercitado (sem trunk/operadora real neste laboratorio).
## Dois bugs reais achados e corrigidos testando esta fase
- Perna sintetica (null/dummy) nao tem midia do outro lado — nunca
desligava sozinha depois de bridgear com um agente. Corrigido com
hangup agendado via uuid_kill no talk_time simulado.
- Corrida entre queue:sync e tier:sync (dois canais Redis independentes,
sem ordem garantida): atribuir tier logo depois de criar a fila podia
rodar tier add antes do queue reload terminar ("-ERR Queue not found!",
erro real, diferente do ja conhecido "already exist"). Corrigido com
retry curto (ate 3 tentativas) em agent-sync.ts::addTierWithRetry.
## GET /campaigns/:id/stats
Secao 227.7 "visualizar pacing" — CampaignStats + agentes por estado +
calls em andamento, sem esperar a fase Frontend.
Verificado ponta a ponta: campanha RUNNING originando 3 tentativas por
tick, outcomes simulados corretos com retry agendado (BUSY 15min/
NO_ANSWER 60min/FAILED 30min), uma tentativa ANSWERED completando o ciclo
real inteiro (fila -> agente -> bridge -> hangup -> EWMA atualizada),
stop nao derruba chamada ativa (secao 66), calls_answered=3 confirmado no
`queue list` do FreeSWITCH. CPS limiter e lock de campanha testados
isoladamente (hierarquia sem incremento parcial, ownership nunca
roubado). typecheck do workspace inteiro limpo.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1HxY46WGU4G1zmVDNKcWw
This commit is contained in:
137
apps/predictive-dialer/src/call-attempt.ts
Normal file
137
apps/predictive-dialer/src/call-attempt.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { CallAttempt, CallAttemptStatus, Prisma } from "@b2bcall/database";
|
||||
import { computeNextAttemptAt } from "./retry-rules";
|
||||
import { ewmaUpdate } from "./ewma";
|
||||
|
||||
export interface CreateAttemptParams {
|
||||
tenantId: string;
|
||||
campaignId: string;
|
||||
leadId: string;
|
||||
simulated: boolean;
|
||||
}
|
||||
|
||||
export async function createCallAttempt(
|
||||
tx: Prisma.TransactionClient,
|
||||
params: CreateAttemptParams,
|
||||
): Promise<CallAttempt> {
|
||||
return tx.callAttempt.create({
|
||||
data: {
|
||||
tenantId: params.tenantId,
|
||||
campaignId: params.campaignId,
|
||||
leadId: params.leadId,
|
||||
simulated: params.simulated,
|
||||
status: "RESERVED",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function setAttemptStatus(
|
||||
tx: Prisma.TransactionClient,
|
||||
attemptId: string,
|
||||
status: CallAttemptStatus,
|
||||
extra: Partial<Pick<CallAttempt, "originationUuid" | "ringingAt" | "answeredAt" | "bridgedAt" | "agentId">> = {},
|
||||
): Promise<void> {
|
||||
await tx.callAttempt.update({ where: { id: attemptId }, data: { status, ...extra } });
|
||||
}
|
||||
|
||||
export function newOriginationUuid(): string {
|
||||
return randomUUID();
|
||||
}
|
||||
|
||||
export type TerminalOutcome = "COMPLETED" | "BUSY" | "NO_ANSWER" | "FAILED" | "ABANDONED";
|
||||
|
||||
export interface CompleteAttemptParams {
|
||||
attemptId: string;
|
||||
tenantId: string;
|
||||
campaignId: string;
|
||||
leadId: string;
|
||||
outcome: TerminalOutcome;
|
||||
reachedQueue: boolean;
|
||||
answerDelaySeconds?: number;
|
||||
talkTimeSeconds?: number;
|
||||
hangupCause?: string;
|
||||
agentId?: string;
|
||||
}
|
||||
|
||||
const OUTCOME_TO_STATUS: Record<TerminalOutcome, CallAttemptStatus> = {
|
||||
COMPLETED: "COMPLETED",
|
||||
BUSY: "BUSY",
|
||||
NO_ANSWER: "NO_ANSWER",
|
||||
FAILED: "FAILED",
|
||||
ABANDONED: "ABANDONED",
|
||||
};
|
||||
|
||||
/**
|
||||
* Fecha uma tentativa: grava o CallAttempt terminal, atualiza a EWMA da
|
||||
* campanha (agente.md secao 75) e decide o próximo passo do Lead — nunca
|
||||
* retry infinito (secao 86): `attemptCount >= maxAttempts` vira
|
||||
* MAX_ATTEMPTS, terminal, nunca mais selecionado. Leads que ainda vão
|
||||
* tentar de novo voltam pra READY (não BUSY/NO_ANSWER/etc como status
|
||||
* consultável — a razão especifica fica em `lastResult`; READY é o único
|
||||
* jeito da query de reserva achar o lead de novo depois de
|
||||
* `nextAttemptAt`).
|
||||
*/
|
||||
export async function completeAttempt(
|
||||
tx: Prisma.TransactionClient,
|
||||
params: CompleteAttemptParams,
|
||||
campaignMaxAttempts: number,
|
||||
): Promise<void> {
|
||||
const now = new Date();
|
||||
|
||||
await tx.callAttempt.update({
|
||||
where: { id: params.attemptId },
|
||||
data: {
|
||||
status: OUTCOME_TO_STATUS[params.outcome],
|
||||
talkTimeSeconds: params.talkTimeSeconds,
|
||||
hangupCause: params.hangupCause,
|
||||
agentId: params.agentId,
|
||||
endedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const stats = await tx.campaignStats.findUniqueOrThrow({ where: { campaignId: params.campaignId } });
|
||||
const wasAnswered = params.outcome === "COMPLETED" || params.outcome === "ABANDONED";
|
||||
const data: Prisma.CampaignStatsUpdateInput = {
|
||||
answerProbability: ewmaUpdate(stats.answerProbability, wasAnswered ? 1 : 0),
|
||||
};
|
||||
if (wasAnswered && params.answerDelaySeconds != null) {
|
||||
data.averageAnswerDelay = ewmaUpdate(stats.averageAnswerDelay, params.answerDelaySeconds);
|
||||
}
|
||||
if (params.talkTimeSeconds != null) {
|
||||
data.averageTalkTime = ewmaUpdate(stats.averageTalkTime, params.talkTimeSeconds);
|
||||
}
|
||||
if (params.reachedQueue) {
|
||||
data.abandonRate = ewmaUpdate(stats.abandonRate, params.outcome === "ABANDONED" ? 1 : 0);
|
||||
}
|
||||
await tx.campaignStats.update({ where: { campaignId: params.campaignId }, data });
|
||||
|
||||
const lead = await tx.lead.findUniqueOrThrow({ where: { id: params.leadId } });
|
||||
const attemptCount = lead.attemptCount + 1;
|
||||
|
||||
if (params.outcome === "COMPLETED") {
|
||||
await tx.lead.update({
|
||||
where: { id: params.leadId },
|
||||
data: { status: "COMPLETED", attemptCount, lastAttemptAt: now, lastResult: params.outcome },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (attemptCount >= campaignMaxAttempts) {
|
||||
await tx.lead.update({
|
||||
where: { id: params.leadId },
|
||||
data: { status: "MAX_ATTEMPTS", attemptCount, lastAttemptAt: now, lastResult: params.outcome },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await tx.lead.update({
|
||||
where: { id: params.leadId },
|
||||
data: {
|
||||
status: "READY",
|
||||
attemptCount,
|
||||
lastAttemptAt: now,
|
||||
lastResult: params.outcome,
|
||||
nextAttemptAt: computeNextAttemptAt(params.outcome, now),
|
||||
},
|
||||
});
|
||||
}
|
||||
140
apps/predictive-dialer/src/event-listener.ts
Normal file
140
apps/predictive-dialer/src/event-listener.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import Redis from "ioredis";
|
||||
import { getPrismaClient, withTenantContext, type Prisma } from "@b2bcall/database";
|
||||
import type { NormalizedEvent } from "@b2bcall/telephony";
|
||||
import { createLogger } from "@b2bcall/shared";
|
||||
import { completeAttempt } from "./call-attempt";
|
||||
import { getQueuedAttempt, unregisterQueuedAttempt } from "./queued-attempts-registry";
|
||||
|
||||
const logger = createLogger("b2bcall-predictive-dialer");
|
||||
|
||||
const EVENTS_CHANNEL = "b2bcall:events";
|
||||
|
||||
function extractId(fsName: string | undefined): string | undefined {
|
||||
return fsName?.split("@")[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Assina o mesmo canal `b2bcall:events` que a fase Realtime Monitoring já
|
||||
* usa (agente.md secao 24) — a perna sintética/real que entrou na fila
|
||||
* carrega os channel variables b2bcall_* (secao 81), então os eventos dela
|
||||
* chegam tenant-scoped de verdade, sem precisar do fan-out usado por
|
||||
* eventos que não têm esses vars (ver docs/AGENTS.md, docs/REALTIME.md).
|
||||
*/
|
||||
export function startEventListener(redisUrl: string): Redis {
|
||||
const subscriber = new Redis(redisUrl);
|
||||
subscriber.on("error", (err) => logger.error("erro na conexao Redis (event listener)", { error: String(err) }));
|
||||
subscriber.subscribe(EVENTS_CHANNEL).catch((err) => {
|
||||
logger.error("falha ao assinar b2bcall:events", { error: String(err) });
|
||||
});
|
||||
|
||||
subscriber.on("message", (_channel, raw) => {
|
||||
handleMessage(raw).catch((err) => {
|
||||
logger.error("falha ao processar evento", { error: String(err) });
|
||||
});
|
||||
});
|
||||
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
async function handleMessage(raw: string): Promise<void> {
|
||||
let event: NormalizedEvent;
|
||||
try {
|
||||
event = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "CALL_ANSWERED": {
|
||||
// Só relevante pro caminho PSTN real (secao 80-83) — a perna
|
||||
// simulada já entra na fila com o delay pré-sorteado, sem passar por
|
||||
// aqui (ver tick.ts). Nunca exercitado nesta sessão.
|
||||
if (!event.callUuid) return;
|
||||
const pending = getQueuedAttempt(event.callUuid);
|
||||
if (!pending || pending.answerDelaySeconds != null) return;
|
||||
pending.answeredAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
|
||||
case "AGENT_OFFERED_CALL": {
|
||||
const memberSessionUuid = event.data.memberSessionUuid as string | undefined;
|
||||
const agentFsName = event.data.agent as string | undefined;
|
||||
const pending = memberSessionUuid && getQueuedAttempt(memberSessionUuid);
|
||||
if (pending && agentFsName) {
|
||||
pending.agentId = extractId(agentFsName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case "CALL_BRIDGED": {
|
||||
if (!event.callUuid) return;
|
||||
const pending = getQueuedAttempt(event.callUuid);
|
||||
if (!pending) return;
|
||||
pending.bridgedAtMs = Date.now();
|
||||
const prisma = getPrismaClient();
|
||||
await withTenantContext(prisma, pending.tenantId, (tx) =>
|
||||
tx.callAttempt.update({
|
||||
where: { id: pending.attemptId },
|
||||
data: { status: "AGENT_CONNECTED", bridgedAt: new Date(), agentId: pending.agentId },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
case "QUEUE_MEMBER_LEFT": {
|
||||
const memberSessionUuid = event.data.memberSessionUuid as string | undefined;
|
||||
if (!memberSessionUuid) return;
|
||||
const pending = getQueuedAttempt(memberSessionUuid);
|
||||
if (!pending || pending.bridgedAtMs) return; // já foi pra um agente, quem fecha é CALL_ENDED
|
||||
await finishAttempt(memberSessionUuid, pending, "ABANDONED");
|
||||
return;
|
||||
}
|
||||
|
||||
case "CALL_ENDED": {
|
||||
if (!event.callUuid) return;
|
||||
const pending = getQueuedAttempt(event.callUuid);
|
||||
if (!pending) return;
|
||||
const outcome = pending.bridgedAtMs ? "COMPLETED" : "ABANDONED";
|
||||
await finishAttempt(event.callUuid, pending, outcome, event.data.hangupCause as string | undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
async function finishAttempt(
|
||||
originationUuid: string,
|
||||
pending: NonNullable<ReturnType<typeof getQueuedAttempt>>,
|
||||
outcome: "COMPLETED" | "ABANDONED",
|
||||
hangupCause?: string,
|
||||
): Promise<void> {
|
||||
unregisterQueuedAttempt(originationUuid);
|
||||
const prisma = getPrismaClient();
|
||||
const talkTimeSeconds = pending.bridgedAtMs ? Math.round((Date.now() - pending.bridgedAtMs) / 1000) : undefined;
|
||||
const answerDelaySeconds =
|
||||
pending.answerDelaySeconds ??
|
||||
(pending.answeredAtMs ? (pending.answeredAtMs - pending.queuedAtMs) / 1000 : undefined);
|
||||
|
||||
await withTenantContext(prisma, pending.tenantId, (tx: Prisma.TransactionClient) =>
|
||||
completeAttempt(
|
||||
tx,
|
||||
{
|
||||
attemptId: pending.attemptId,
|
||||
tenantId: pending.tenantId,
|
||||
campaignId: pending.campaignId,
|
||||
leadId: pending.leadId,
|
||||
outcome,
|
||||
reachedQueue: true,
|
||||
answerDelaySeconds,
|
||||
talkTimeSeconds,
|
||||
hangupCause,
|
||||
agentId: pending.agentId,
|
||||
},
|
||||
pending.maxAttempts,
|
||||
),
|
||||
);
|
||||
|
||||
logger.info("tentativa finalizada (fila real)", { attemptId: pending.attemptId, outcome });
|
||||
}
|
||||
12
apps/predictive-dialer/src/ewma.ts
Normal file
12
apps/predictive-dialer/src/ewma.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* EWMA (agente.md secao 75) pra suavizar answer_probability/
|
||||
* average_answer_delay/TMA/abandon_rate — evita que o pacing oscile
|
||||
* violentamente por causa de uma única amostra ruim. alpha alto = reage
|
||||
* rápido a mudanças recentes; 0.25 é um meio-termo razoável (equivalente a
|
||||
* uma janela de ~7-8 amostras).
|
||||
*/
|
||||
const ALPHA = 0.25;
|
||||
|
||||
export function ewmaUpdate(previous: number, sample: number, alpha = ALPHA): number {
|
||||
return alpha * sample + (1 - alpha) * previous;
|
||||
}
|
||||
51
apps/predictive-dialer/src/lead-reservation.ts
Normal file
51
apps/predictive-dialer/src/lead-reservation.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { Prisma } from "@b2bcall/database";
|
||||
|
||||
export interface ReservedLead {
|
||||
id: string;
|
||||
phoneNormalized: string;
|
||||
name: string | null;
|
||||
attemptCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserva atômica de leads (agente.md secao 78): `FOR UPDATE SKIP LOCKED`
|
||||
* garante que dois workers concorrentes nunca pegam o mesmo lead — quem
|
||||
* chegar primeiro tranca a linha, o outro pula pra próxima em vez de
|
||||
* esperar (nada de fila de espera aqui, é melhor originar outro lead do
|
||||
* que travar o tick inteiro). `count` normalmente é pequeno (poucas
|
||||
* unidades por tick), então `SELECT ... LIMIT` é barato mesmo sem índice
|
||||
* dedicado além do já existente em `(campaign_id, status, next_attempt_at)`.
|
||||
*
|
||||
* Precisa rodar dentro do MESMO `withTenantContext` transaction que fez a
|
||||
* checagem de RLS — o lock de linha só vale até o commit/rollback da
|
||||
* transação atual.
|
||||
*/
|
||||
export async function reserveLeads(
|
||||
tx: Prisma.TransactionClient,
|
||||
tenantId: string,
|
||||
campaignId: string,
|
||||
count: number,
|
||||
): Promise<ReservedLead[]> {
|
||||
if (count <= 0) return [];
|
||||
|
||||
const rows = await tx.$queryRaw<ReservedLead[]>`
|
||||
SELECT id, phone_normalized AS "phoneNormalized", name, attempt_count AS "attemptCount"
|
||||
FROM leads
|
||||
WHERE tenant_id = ${tenantId}::uuid
|
||||
AND campaign_id = ${campaignId}::uuid
|
||||
AND status IN ('NEW', 'READY')
|
||||
AND (next_attempt_at IS NULL OR next_attempt_at <= now())
|
||||
ORDER BY next_attempt_at ASC NULLS FIRST, created_at ASC
|
||||
LIMIT ${count}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`;
|
||||
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
await tx.lead.updateMany({
|
||||
where: { id: { in: rows.map((r) => r.id) } },
|
||||
data: { status: "RESERVED" },
|
||||
});
|
||||
|
||||
return rows;
|
||||
}
|
||||
134
apps/predictive-dialer/src/main.ts
Normal file
134
apps/predictive-dialer/src/main.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import Redis from "ioredis";
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { FreeSwitchTelephonyProvider } from "@b2bcall/telephony";
|
||||
import { createLogger } from "@b2bcall/shared";
|
||||
import { acquireCampaignLock, renewCampaignLock, releaseCampaignLock } from "./redis-primitives";
|
||||
import { tickCampaign, type TickDeps } from "./tick";
|
||||
import { startEventListener } from "./event-listener";
|
||||
|
||||
const logger = createLogger("b2bcall-predictive-dialer");
|
||||
|
||||
const TICK_INTERVAL_MS = 2000;
|
||||
const LOCK_TTL_MS = 10_000;
|
||||
|
||||
function requireEnv(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) throw new Error(`${name} nao definido no ambiente`);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Real Outbound Safety (agente.md secao 186): as DUAS condições precisam
|
||||
* estar explicitamente ligadas — nunca ativado automaticamente. Lido uma
|
||||
* vez no boot (não é algo que deveria mudar em runtime sem reiniciar o
|
||||
* worker).
|
||||
*/
|
||||
function readOutboundSafetyFlags(): { dialerSimulation: boolean; allowRealOutboundCalls: boolean } {
|
||||
const dialerSimulation = (process.env.DIALER_SIMULATION ?? "true") !== "false";
|
||||
const allowRealOutboundCalls = process.env.ALLOW_REAL_OUTBOUND_CALLS === "true";
|
||||
if (dialerSimulation) {
|
||||
logger.info("DIALER_SIMULATION=true — nenhuma chamada PSTN real sera originada");
|
||||
} else if (!allowRealOutboundCalls) {
|
||||
logger.warn(
|
||||
"DIALER_SIMULATION=false mas ALLOW_REAL_OUTBOUND_CALLS != true — chamadas reais continuam bloqueadas (secao 186)",
|
||||
);
|
||||
} else {
|
||||
logger.warn("CHAMADAS PSTN REAIS HABILITADAS (DIALER_SIMULATION=false + ALLOW_REAL_OUTBOUND_CALLS=true)");
|
||||
}
|
||||
return { dialerSimulation, allowRealOutboundCalls };
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { dialerSimulation, allowRealOutboundCalls } = readOutboundSafetyFlags();
|
||||
const redis = new Redis(requireEnv("REDIS_URL"));
|
||||
redis.on("error", (err) => logger.error("erro na conexao Redis", { error: String(err) }));
|
||||
|
||||
const provider = new FreeSwitchTelephonyProvider({
|
||||
host: requireEnv("ESL_HOST"),
|
||||
port: Number(process.env.ESL_PORT ?? 8021),
|
||||
password: requireEnv("ESL_PASSWORD"),
|
||||
logger: {
|
||||
debug: () => {},
|
||||
info: (msg) => logger.debug(msg),
|
||||
error: (msg, data) => logger.error(msg, { detail: data }),
|
||||
},
|
||||
});
|
||||
provider.connect();
|
||||
await provider.waitUntilConnected(10_000);
|
||||
|
||||
const eventSubscriber = startEventListener(requireEnv("REDIS_URL"));
|
||||
|
||||
const workerId = randomUUID();
|
||||
const deps: TickDeps = { redis, provider, dialerSimulation, allowRealOutboundCalls };
|
||||
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
try {
|
||||
await runTick(deps, workerId);
|
||||
} catch (err) {
|
||||
logger.error("falha no tick", { error: String(err) });
|
||||
}
|
||||
if (!stopped) setTimeout(tick, TICK_INTERVAL_MS);
|
||||
};
|
||||
setTimeout(tick, TICK_INTERVAL_MS);
|
||||
|
||||
logger.info("b2bcall-predictive-dialer iniciado", { workerId, tickIntervalMs: TICK_INTERVAL_MS });
|
||||
|
||||
const shutdown = async () => {
|
||||
stopped = true;
|
||||
logger.info("encerrando b2bcall-predictive-dialer");
|
||||
await provider.disconnect();
|
||||
redis.disconnect();
|
||||
eventSubscriber.disconnect();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Um tick = uma passada por todos os tenants ativos, campanhas RUNNING (ou
|
||||
* WAITING_SCHEDULE, que pode voltar a RUNNING dentro da janela — ver
|
||||
* tick.ts). Lock por campanha (secao 79) garante que, mesmo rodando mais
|
||||
* de um worker deste serviço, só um processa uma dada campanha por vez —
|
||||
* renovado durante o processamento, liberado com compare-and-delete no
|
||||
* final (nunca libera o lock de outro dono).
|
||||
*/
|
||||
async function runTick(deps: TickDeps, workerId: string): Promise<void> {
|
||||
const prisma = getPrismaClient();
|
||||
const tenants = await prisma.tenant.findMany({ where: { status: "ACTIVE" } });
|
||||
|
||||
for (const tenant of tenants) {
|
||||
const campaigns = await withTenantContext(prisma, tenant.id, (tx) =>
|
||||
tx.campaign.findMany({
|
||||
where: { tenantId: tenant.id, deletedAt: null, status: { in: ["RUNNING", "WAITING_SCHEDULE"] } },
|
||||
}),
|
||||
);
|
||||
|
||||
for (const campaign of campaigns) {
|
||||
const ownerToken = `${workerId}:${randomUUID()}`;
|
||||
const locked = await acquireCampaignLock(deps.redis, campaign.id, ownerToken, LOCK_TTL_MS);
|
||||
if (!locked) continue;
|
||||
|
||||
const renewTimer = setInterval(() => {
|
||||
renewCampaignLock(deps.redis, campaign.id, ownerToken, LOCK_TTL_MS).catch(() => undefined);
|
||||
}, LOCK_TTL_MS / 2);
|
||||
|
||||
try {
|
||||
await tickCampaign(deps, tenant, campaign);
|
||||
} catch (err) {
|
||||
logger.error("falha no tick da campanha", { error: String(err), campaignId: campaign.id });
|
||||
} finally {
|
||||
clearInterval(renewTimer);
|
||||
await releaseCampaignLock(deps.redis, campaign.id, ownerToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
logger.error("falha fatal ao iniciar b2bcall-predictive-dialer", { error: String(err) });
|
||||
process.exit(1);
|
||||
});
|
||||
75
apps/predictive-dialer/src/originate.ts
Normal file
75
apps/predictive-dialer/src/originate.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type { FreeSwitchTelephonyProvider } from "@b2bcall/telephony";
|
||||
|
||||
export interface OriginateIdentifiers {
|
||||
tenantId: string;
|
||||
attemptId: string;
|
||||
campaignId: string;
|
||||
leadId: string;
|
||||
}
|
||||
|
||||
function channelVars(ids: OriginateIdentifiers): Record<string, string> {
|
||||
// agente.md secao 81: tenant_id/call_id/attempt_id/campaign_id/lead_id
|
||||
// como channel variables. Não existe uma entidade "Call" separada de
|
||||
// CallAttempt nesta fase — b2bcall_call_id usa o mesmo id do attempt.
|
||||
return {
|
||||
b2bcall_tenant_id: ids.tenantId,
|
||||
b2bcall_call_id: ids.attemptId,
|
||||
b2bcall_attempt_id: ids.attemptId,
|
||||
b2bcall_campaign_id: ids.campaignId,
|
||||
b2bcall_lead_id: ids.leadId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Perna "atendida" sintética (modo simulação): quando o outcome sorteado é
|
||||
* ANSWERED, origina uma chamada de verdade no FreeSWITCH (`null/dummy`,
|
||||
* sem PSTN nenhum envolvido) direto pra `&callcenter(...)` — a parte
|
||||
* "cliente atendeu" é simulada, mas a partir daqui o pipeline de
|
||||
* fila/agente é 100% real (o mesmo mod_callcenter já testado nas fases
|
||||
* Queues/Agents/Realtime Monitoring).
|
||||
*/
|
||||
export async function originateSimulatedAnswerLeg(
|
||||
provider: FreeSwitchTelephonyProvider,
|
||||
ids: OriginateIdentifiers,
|
||||
queueId: string,
|
||||
domain: string,
|
||||
): Promise<{ uuid: string }> {
|
||||
return provider.originate({
|
||||
destination: "null/dummy",
|
||||
application: "callcenter",
|
||||
applicationArgs: `${queueId}@${domain}`,
|
||||
channelVariables: channelVars(ids),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Perna PSTN real (agente.md secao 80-83) — `bgapi originate` via Sofia
|
||||
* Gateway. Só é chamada quando `DIALER_SIMULATION=false` E
|
||||
* `ALLOW_REAL_OUTBOUND_CALLS=true` (secao 186, checado em main.ts antes de
|
||||
* sequer construir o tick). **Nunca exercitada nesta sessão** — não há
|
||||
* trunk/operadora real disponível neste laboratório; ver
|
||||
* docs/PREDICTIVE_DIALER.md.
|
||||
*/
|
||||
export async function originateRealPstnLeg(
|
||||
provider: FreeSwitchTelephonyProvider,
|
||||
ids: OriginateIdentifiers,
|
||||
params: {
|
||||
trunkId: string;
|
||||
phoneNumber: string;
|
||||
queueId: string;
|
||||
domain: string;
|
||||
callerIdName?: string;
|
||||
callerIdNumber?: string;
|
||||
ringTimeoutSeconds: number;
|
||||
},
|
||||
): Promise<{ uuid: string }> {
|
||||
return provider.originate({
|
||||
destination: `sofia/gateway/${params.trunkId}/${params.phoneNumber}`,
|
||||
application: "callcenter",
|
||||
applicationArgs: `${params.queueId}@${params.domain}`,
|
||||
channelVariables: channelVars(ids),
|
||||
callerIdName: params.callerIdName,
|
||||
callerIdNumber: params.callerIdNumber,
|
||||
timeoutSeconds: params.ringTimeoutSeconds,
|
||||
});
|
||||
}
|
||||
155
apps/predictive-dialer/src/pacing.ts
Normal file
155
apps/predictive-dialer/src/pacing.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import type { Campaign, CampaignStats, Prisma } from "@b2bcall/database";
|
||||
|
||||
/**
|
||||
* Dados em tempo real considerados pelo motor (agente.md secao 73) —
|
||||
* derivados na hora a partir de Agent.state (fonte de verdade já mantida
|
||||
* pelas fases Agents/Realtime Monitoring), não persistidos separadamente.
|
||||
*/
|
||||
export interface CapacitySnapshot {
|
||||
availableAgents: number;
|
||||
reservedAgents: number;
|
||||
ringingAgents: number;
|
||||
agentsInCall: number;
|
||||
agentsInWrapup: number;
|
||||
agentsPaused: number;
|
||||
predictedBecomingAvailable: number;
|
||||
callsInFlight: number;
|
||||
}
|
||||
|
||||
const PREDICTION_HORIZON_SECONDS = 15;
|
||||
|
||||
/**
|
||||
* Previsão de liberação (agente.md secao 74) — versão determinística e
|
||||
* explicável, sem Machine Learning: pra cada agente em IN_CALL/WRAP_UP,
|
||||
* estima o tempo restante (average_talk_time ou wrap_up_time menos o
|
||||
* tempo já decorrido desde `stateUpdatedAt`) e conta quantos cruzam o
|
||||
* horizonte de previsão. Simplificação deliberada da tabela de 4 buckets
|
||||
* (5/10/15/20s) da especificação — um único horizonte de 15s, documentado
|
||||
* em docs/PREDICTIVE_DIALER.md; refinar pros 4 buckets é trabalho futuro.
|
||||
*/
|
||||
export async function computeCapacity(
|
||||
tx: Prisma.TransactionClient,
|
||||
tenantId: string,
|
||||
campaign: Campaign,
|
||||
stats: CampaignStats,
|
||||
): Promise<CapacitySnapshot> {
|
||||
const agents = await tx.agent.findMany({
|
||||
where: { tenantId, enabled: true, deletedAt: null, tiers: { some: { queueId: campaign.queueId } } },
|
||||
select: { state: true, stateUpdatedAt: true, wrapUpTime: true },
|
||||
});
|
||||
|
||||
const now = Date.now();
|
||||
let availableAgents = 0;
|
||||
let reservedAgents = 0;
|
||||
let ringingAgents = 0;
|
||||
let agentsInCall = 0;
|
||||
let agentsInWrapup = 0;
|
||||
let agentsPaused = 0;
|
||||
let predictedBecomingAvailable = 0;
|
||||
|
||||
for (const agent of agents) {
|
||||
const elapsedSeconds = agent.stateUpdatedAt ? (now - agent.stateUpdatedAt.getTime()) / 1000 : Infinity;
|
||||
|
||||
switch (agent.state) {
|
||||
case "AVAILABLE":
|
||||
availableAgents++;
|
||||
break;
|
||||
case "RESERVED":
|
||||
reservedAgents++;
|
||||
break;
|
||||
case "RINGING":
|
||||
ringingAgents++;
|
||||
break;
|
||||
case "IN_CALL": {
|
||||
agentsInCall++;
|
||||
const remaining = stats.averageTalkTime - elapsedSeconds;
|
||||
if (remaining <= PREDICTION_HORIZON_SECONDS) predictedBecomingAvailable++;
|
||||
break;
|
||||
}
|
||||
case "WRAP_UP": {
|
||||
agentsInWrapup++;
|
||||
const remaining = agent.wrapUpTime - elapsedSeconds;
|
||||
if (remaining <= PREDICTION_HORIZON_SECONDS) predictedBecomingAvailable++;
|
||||
break;
|
||||
}
|
||||
case "PAUSED":
|
||||
agentsPaused++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const callsInFlight = await tx.callAttempt.count({
|
||||
where: {
|
||||
tenantId,
|
||||
campaignId: campaign.id,
|
||||
status: { in: ["CREATED", "RESERVED", "ORIGINATING", "ORIGINATED", "RINGING", "ANSWERED", "QUEUEING"] },
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
availableAgents,
|
||||
reservedAgents,
|
||||
ringingAgents,
|
||||
agentsInCall,
|
||||
agentsInWrapup,
|
||||
agentsPaused,
|
||||
predictedBecomingAvailable,
|
||||
callsInFlight,
|
||||
};
|
||||
}
|
||||
|
||||
export interface PacingDecision {
|
||||
callsToOriginate: number;
|
||||
newPacingFactor: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cálculo conceitual (agente.md secao 76): expected_agent_capacity =
|
||||
* available + predicted_becoming_available; expected_answers = calls *
|
||||
* answer_probability; objetivo expected_answers ≈ expected_agent_capacity,
|
||||
* aplicando pacing_factor e limites. Controle de abandono (secao 84):
|
||||
* abandon_rate acima do alvo reduz o pacing; acima de 2x entra em modo
|
||||
* conservador (pacing mínimo); acima de 3x suspende originações neste
|
||||
* tick. Nunca discar sem capacidade prevista (secao 85).
|
||||
*/
|
||||
export function decidePacing(
|
||||
campaign: Campaign,
|
||||
stats: CampaignStats,
|
||||
capacity: CapacitySnapshot,
|
||||
): PacingDecision {
|
||||
let pacingFactor = stats.pacingFactor;
|
||||
|
||||
if (stats.abandonRate > campaign.targetAbandonRate * 3) {
|
||||
// Modo crítico: suspende originações neste tick, mas não zera o
|
||||
// pacingFactor guardado (evita ficar preso no mínimo por uma amostra
|
||||
// ruim isolada — a próxima leitura de abandonRate decide de novo).
|
||||
return { callsToOriginate: 0, newPacingFactor: campaign.pacingMin };
|
||||
}
|
||||
if (stats.abandonRate > campaign.targetAbandonRate * 2) {
|
||||
pacingFactor = campaign.pacingMin;
|
||||
} else if (stats.abandonRate > campaign.targetAbandonRate) {
|
||||
pacingFactor = Math.max(campaign.pacingMin, pacingFactor * 0.8);
|
||||
} else if (pacingFactor < campaign.pacingMax) {
|
||||
pacingFactor = Math.min(campaign.pacingMax, pacingFactor * 1.05);
|
||||
}
|
||||
|
||||
const expectedAgentCapacity = capacity.availableAgents + capacity.predictedBecomingAvailable;
|
||||
if (expectedAgentCapacity <= 0) {
|
||||
// Secao 85: não originar agressivamente sem capacidade prevista.
|
||||
return { callsToOriginate: 0, newPacingFactor: pacingFactor };
|
||||
}
|
||||
|
||||
const targetOriginations = expectedAgentCapacity * pacingFactor;
|
||||
const answerProbability = Math.max(0.01, stats.answerProbability);
|
||||
let callsToOriginate = Math.round(targetOriginations / answerProbability) - capacity.callsInFlight;
|
||||
callsToOriginate = Math.max(0, callsToOriginate);
|
||||
|
||||
if (campaign.maxConcurrentCalls != null) {
|
||||
const room = campaign.maxConcurrentCalls - capacity.callsInFlight;
|
||||
callsToOriginate = Math.min(callsToOriginate, Math.max(0, room));
|
||||
}
|
||||
|
||||
return { callsToOriginate, newPacingFactor: pacingFactor };
|
||||
}
|
||||
44
apps/predictive-dialer/src/queued-attempts-registry.ts
Normal file
44
apps/predictive-dialer/src/queued-attempts-registry.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Correlaciona eventos reais do FreeSWITCH (chegando via Redis
|
||||
* `b2bcall:events`, publicados por b2bcall-fs-events) de volta pra um
|
||||
* CallAttempt em andamento — registry em memória, chave é o
|
||||
* `origination_uuid` da perna sintética (simulada) ou real que entrou na
|
||||
* fila. Não precisa persistir: se o worker reiniciar no meio de uma
|
||||
* chamada em curso, essa chamada específica fica "órfã" (perde a
|
||||
* correlação, mas o CallAttempt já teria os timestamps que existiam até
|
||||
* ali) — aceitável nesta fase, mesma classe de limitação já documentada
|
||||
* pra outros processos de curta duração deste projeto.
|
||||
*/
|
||||
export interface QueuedAttemptInfo {
|
||||
attemptId: string;
|
||||
tenantId: string;
|
||||
campaignId: string;
|
||||
leadId: string;
|
||||
maxAttempts: number;
|
||||
queuedAtMs: number;
|
||||
// Conhecido de antemão no modo simulação (o delay já foi sorteado antes
|
||||
// de originar); no caminho PSTN real, fica undefined até answeredAtMs
|
||||
// ser preenchido pelo evento CALL_ANSWERED real.
|
||||
answerDelaySeconds?: number;
|
||||
answeredAtMs?: number;
|
||||
agentId?: string;
|
||||
bridgedAtMs?: number;
|
||||
}
|
||||
|
||||
const registry = new Map<string, QueuedAttemptInfo>();
|
||||
|
||||
export function registerQueuedAttempt(originationUuid: string, info: QueuedAttemptInfo): void {
|
||||
registry.set(originationUuid, info);
|
||||
}
|
||||
|
||||
export function getQueuedAttempt(originationUuid: string): QueuedAttemptInfo | undefined {
|
||||
return registry.get(originationUuid);
|
||||
}
|
||||
|
||||
export function unregisterQueuedAttempt(originationUuid: string): void {
|
||||
registry.delete(originationUuid);
|
||||
}
|
||||
|
||||
export function pendingCount(): number {
|
||||
return registry.size;
|
||||
}
|
||||
98
apps/predictive-dialer/src/redis-primitives.ts
Normal file
98
apps/predictive-dialer/src/redis-primitives.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import type Redis from "ioredis";
|
||||
|
||||
/**
|
||||
* CPS distribuído (agente.md secao 77): "token bucket ou equivalente,
|
||||
* Redis, múltiplos workers, nunca sleep() como controle." Implementado
|
||||
* como um contador de janela fixa de 1s por chave (INCR + PEXPIRE), checado
|
||||
* e incrementado num único script Lua — atômico mesmo com N workers
|
||||
* concorrentes, sem sleep nenhum.
|
||||
*
|
||||
* A hierarquia (agente.md secao 62: GLOBAL → NODE → TENANT → TRUNK →
|
||||
* CAMPAIGN) é uma única chamada com várias chaves: só incrementa TODAS se
|
||||
* TODAS tiverem espaço — nunca incrementa parcialmente e desfaz depois.
|
||||
*/
|
||||
const CPS_WINDOW_SCRIPT = `
|
||||
local n = #KEYS
|
||||
for i = 1, n do
|
||||
local limit = tonumber(ARGV[i])
|
||||
local current = tonumber(redis.call('GET', KEYS[i]) or '0')
|
||||
if current >= limit then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
for i = 1, n do
|
||||
local newval = redis.call('INCR', KEYS[i])
|
||||
if newval == 1 then
|
||||
redis.call('PEXPIRE', KEYS[i], 1000)
|
||||
end
|
||||
end
|
||||
return 1
|
||||
`;
|
||||
|
||||
export interface CpsCheck {
|
||||
key: string;
|
||||
maxPerSecond: number;
|
||||
}
|
||||
|
||||
/** Tenta consumir 1 slot de CPS em TODOS os níveis da hierarquia de uma vez
|
||||
* (só chaves com limite definido — null/undefined = sem limite nesse
|
||||
* nível, nem entra no script). Retorna false se qualquer nível estourar. */
|
||||
export async function tryAcquireCps(redis: Redis, checks: CpsCheck[]): Promise<boolean> {
|
||||
const applicable = checks.filter((c) => c.maxPerSecond > 0);
|
||||
if (applicable.length === 0) return true;
|
||||
const keys = applicable.map((c) => c.key);
|
||||
const args = applicable.map((c) => String(c.maxPerSecond));
|
||||
const result = await redis.eval(CPS_WINDOW_SCRIPT, keys.length, ...keys, ...args);
|
||||
return result === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock de campanha (agente.md secao 79): `dialer:campaign:{id}`, TTL,
|
||||
* ownership token (só quem detém o token renova/libera), renewal, safe
|
||||
* release (compare-and-delete via Lua — nunca libera o lock de outro dono
|
||||
* por engano numa corrida entre "TTL expirou" e "release chegou atrasado").
|
||||
*/
|
||||
function lockKey(campaignId: string): string {
|
||||
return `dialer:campaign:${campaignId}`;
|
||||
}
|
||||
|
||||
export async function acquireCampaignLock(
|
||||
redis: Redis,
|
||||
campaignId: string,
|
||||
ownerToken: string,
|
||||
ttlMs: number,
|
||||
): Promise<boolean> {
|
||||
const result = await redis.set(lockKey(campaignId), ownerToken, "PX", ttlMs, "NX");
|
||||
return result === "OK";
|
||||
}
|
||||
|
||||
const RENEW_SCRIPT = `
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
return redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`;
|
||||
|
||||
export async function renewCampaignLock(
|
||||
redis: Redis,
|
||||
campaignId: string,
|
||||
ownerToken: string,
|
||||
ttlMs: number,
|
||||
): Promise<boolean> {
|
||||
const result = await redis.eval(RENEW_SCRIPT, 1, lockKey(campaignId), ownerToken, String(ttlMs));
|
||||
return result === 1;
|
||||
}
|
||||
|
||||
const RELEASE_SCRIPT = `
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
return redis.call('DEL', KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`;
|
||||
|
||||
export async function releaseCampaignLock(redis: Redis, campaignId: string, ownerToken: string): Promise<boolean> {
|
||||
const result = await redis.eval(RELEASE_SCRIPT, 1, lockKey(campaignId), ownerToken);
|
||||
return result === 1;
|
||||
}
|
||||
16
apps/predictive-dialer/src/retry-rules.ts
Normal file
16
apps/predictive-dialer/src/retry-rules.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Regras de retry configuráveis (agente.md secao 86) — nunca retry
|
||||
* infinito, `Campaign.maxAttempts` é o teto absoluto (aplicado por quem
|
||||
* chama, ver call-attempt.ts).
|
||||
*/
|
||||
const RETRY_DELAY_MINUTES: Record<string, number> = {
|
||||
BUSY: 15,
|
||||
NO_ANSWER: 60,
|
||||
FAILED: 30,
|
||||
ABANDONED: 30,
|
||||
};
|
||||
|
||||
export function computeNextAttemptAt(outcome: keyof typeof RETRY_DELAY_MINUTES, now: Date): Date {
|
||||
const minutes = RETRY_DELAY_MINUTES[outcome] ?? 60;
|
||||
return new Date(now.getTime() + minutes * 60_000);
|
||||
}
|
||||
43
apps/predictive-dialer/src/schedule.ts
Normal file
43
apps/predictive-dialer/src/schedule.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import type { Campaign } from "@b2bcall/database";
|
||||
|
||||
/**
|
||||
* Janela de funcionamento da campanha (agente.md secao 63-64: timezone,
|
||||
* days_of_week, start/end_date, start/end_time — status vira
|
||||
* WAITING_SCHEDULE quando fora da janela). Usa `Intl.DateTimeFormat` com
|
||||
* `timeZone` em vez de trazer uma lib de datas só pra isso — o Node já sabe
|
||||
* converter pra qualquer timezone IANA nativamente.
|
||||
*/
|
||||
export function isWithinSchedule(campaign: Campaign, now: Date = new Date()): boolean {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: campaign.timezone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
weekday: "short",
|
||||
}).formatToParts(now);
|
||||
|
||||
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "";
|
||||
const dateStr = `${get("year")}-${get("month")}-${get("day")}`;
|
||||
const timeStr = `${get("hour")}:${get("minute")}`;
|
||||
const weekdayMap: Record<string, number> = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 };
|
||||
const isoWeekday = weekdayMap[get("weekday")];
|
||||
|
||||
if (campaign.startDate) {
|
||||
const startStr = campaign.startDate.toISOString().slice(0, 10);
|
||||
if (dateStr < startStr) return false;
|
||||
}
|
||||
if (campaign.endDate) {
|
||||
const endStr = campaign.endDate.toISOString().slice(0, 10);
|
||||
if (dateStr > endStr) return false;
|
||||
}
|
||||
if (campaign.daysOfWeek.length > 0 && !campaign.daysOfWeek.includes(isoWeekday)) {
|
||||
return false;
|
||||
}
|
||||
if (campaign.startTime && timeStr < campaign.startTime) return false;
|
||||
if (campaign.endTime && timeStr > campaign.endTime) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
53
apps/predictive-dialer/src/simulation.ts
Normal file
53
apps/predictive-dialer/src/simulation.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Modo simulação (agente.md secao 185): `DIALER_SIMULATION=true` (default)
|
||||
* — nenhuma chamada PSTN real acontece. Simula ANSWER/BUSY/NO_ANSWER/
|
||||
* FAILED/RINGING com delay e talk time sorteados, tudo em software, sem
|
||||
* originar nada pro trunk real. Habilitar chamadas reais exige as DUAS
|
||||
* condições da secao 186 (`DIALER_SIMULATION=false` E
|
||||
* `ALLOW_REAL_OUTBOUND_CALLS=true`) — nunca ativado automaticamente, ver
|
||||
* main.ts.
|
||||
*/
|
||||
export type SimulatedOutcomeType = "ANSWERED" | "BUSY" | "NO_ANSWER" | "FAILED";
|
||||
|
||||
export interface SimulatedOutcome {
|
||||
type: SimulatedOutcomeType;
|
||||
ringDelayMs: number;
|
||||
talkTimeSeconds?: number;
|
||||
}
|
||||
|
||||
const OUTCOME_PROBABILITIES: [SimulatedOutcomeType, number][] = [
|
||||
["ANSWERED", 0.4],
|
||||
["BUSY", 0.15],
|
||||
["NO_ANSWER", 0.35],
|
||||
["FAILED", 0.1],
|
||||
];
|
||||
|
||||
function randomBetween(min: number, max: number): number {
|
||||
return min + Math.random() * (max - min);
|
||||
}
|
||||
|
||||
export function simulateOutcome(ringTimeoutSeconds: number, averageTalkTimeSeconds: number): SimulatedOutcome {
|
||||
const roll = Math.random();
|
||||
let cumulative = 0;
|
||||
let type: SimulatedOutcomeType = "FAILED";
|
||||
for (const [candidate, probability] of OUTCOME_PROBABILITIES) {
|
||||
cumulative += probability;
|
||||
if (roll <= cumulative) {
|
||||
type = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === "ANSWERED") {
|
||||
const ringDelayMs = randomBetween(1000, Math.min(8000, ringTimeoutSeconds * 1000 * 0.6));
|
||||
// Talk time varia +-40% em torno da média corrente da campanha (EWMA) —
|
||||
// sem distribuição estatística real por trás (não existe histórico de
|
||||
// chamadas de verdade ainda), só o suficiente pra exercitar o pipeline
|
||||
// com valores plausíveis.
|
||||
const talkTimeSeconds = Math.max(10, randomBetween(averageTalkTimeSeconds * 0.6, averageTalkTimeSeconds * 1.4));
|
||||
return { type, ringDelayMs, talkTimeSeconds };
|
||||
}
|
||||
|
||||
const ringDelayMs = randomBetween(1000, ringTimeoutSeconds * 1000);
|
||||
return { type, ringDelayMs };
|
||||
}
|
||||
244
apps/predictive-dialer/src/tick.ts
Normal file
244
apps/predictive-dialer/src/tick.ts
Normal file
@@ -0,0 +1,244 @@
|
||||
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 ?? "",
|
||||
);
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
|
||||
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 }));
|
||||
}
|
||||
Reference in New Issue
Block a user