feat: add Event Socket integration (b2bcall-fs-events)

- packages/telephony: TelephonyProvider interface (agente.md secao 25) and
  FreeSwitchTelephonyProvider implementation over the 'esl' library
  (actively maintained, TypeScript-native, built-in reconnect-with-backoff
  satisfying secao 195); normalizeEslEvent() translates raw ESL events into
  the internal vocabulary (secao 24)
- apps/freeswitch-events (b2bcall-fs-events): permanent ESL connection,
  resubscribes on every reconnect, publishes normalized events to the
  'b2bcall:events' Redis pub/sub channel; containerized (Dockerfile +
  docker-compose service) since its whole job is reaching the freeswitch
  container by internal hostname
- packages/shared: reusable createLogger() (structured JSON per secao 189),
  fixed a BigInt serialization crash surfaced by the esl library's error
  stats
- found and fixed a real FreeSWITCH 1.11 default: without an explicit
  apply-inbound-acl, mod_event_socket silently rejects any non-loopback
  connection ('Access Denied, go away.') even with the correct password —
  added a dedicated ACL (loopback + the Docker Compose network range, never
  0.0.0.0/0) in infrastructure/freeswitch/overrides/autoload_configs/
- verified end-to-end with a local loopback test call: CALL_CREATED ->
  CALL_ANSWERED -> CALL_ENDED observed on the Redis channel with the
  correct callUuid and hangup cause
- docs/EVENT_SOCKET.md
This commit is contained in:
2026-08-28 06:47:28 -03:00
parent b3b0aaacb3
commit 60e9f6838e
22 changed files with 762 additions and 15 deletions

View File

@@ -0,0 +1,23 @@
# syntax=docker/dockerfile:1.7
#
# Build a partir da raiz do monorepo (context: .), só com os pacotes que
# este serviço realmente usa. Roda via `tsx` direto (sem etapa de `tsc build`
# nem dist/): os pacotes internos (@b2bcall/shared, @b2bcall/telephony) ainda
# não tem pipeline de build próprio — ver docs/FREESWITCH_EVENTS.md.
FROM node:22-slim
RUN corepack enable && corepack prepare pnpm@11.24.0 --activate
WORKDIR /repo
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml tsconfig.base.json ./
COPY packages/types packages/types
COPY packages/shared packages/shared
COPY packages/telephony packages/telephony
COPY apps/freeswitch-events apps/freeswitch-events
RUN pnpm install --frozen-lockfile --filter @b2bcall/freeswitch-events...
WORKDIR /repo/apps/freeswitch-events
CMD ["pnpm", "exec", "tsx", "src/main.ts"]

View File

@@ -0,0 +1,22 @@
{
"name": "@b2bcall/freeswitch-events",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "tsx watch src/main.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/main.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@b2bcall/shared": "workspace:*",
"@b2bcall/telephony": "workspace:*",
"esl": "11.2.1",
"ioredis": "^6.0.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"tsx": "^4.23.12",
"typescript": "^5.7.0"
}
}

View File

@@ -0,0 +1,112 @@
import Redis from "ioredis";
import type { FreeSwitchEventData } from "esl";
import { FreeSwitchTelephonyProvider, normalizeEslEvent } from "@b2bcall/telephony";
import { createLogger } from "@b2bcall/shared";
const logger = createLogger("b2bcall-fs-events");
const REDIS_CHANNEL = "b2bcall:events";
// Eventos consumidos (agente.md secao 23). HEARTBEAT só é logado, nunca
// normalizado/publicado — não representa uma chamada.
const SUBSCRIBED_EVENTS = [
"HEARTBEAT",
"CHANNEL_CREATE",
"CHANNEL_ORIGINATE",
"CHANNEL_PROGRESS",
"CHANNEL_PROGRESS_MEDIA",
"CHANNEL_ANSWER",
"CHANNEL_BRIDGE",
"CHANNEL_UNBRIDGE",
"CHANNEL_HANGUP",
"CHANNEL_HANGUP_COMPLETE",
"CHANNEL_DESTROY",
"CHANNEL_STATE",
"CHANNEL_CALLSTATE",
"BACKGROUND_JOB",
"CUSTOM",
] as const;
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`${name} nao definido no ambiente`);
}
return value;
}
async function main() {
const redis = new Redis(requireEnv("REDIS_URL"));
redis.on("error", (err) => logger.error("erro na conexao com 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 }),
},
});
const client = provider.eslClient;
client.on("connect", async (call) => {
logger.info("conectado ao FreeSWITCH via ESL");
// Re-executado a cada reconexao (secao 195: "resubscribe" apos reconectar).
await call.event_json(...SUBSCRIBED_EVENTS);
call.on("HEARTBEAT", () => logger.debug("heartbeat"));
for (const eventName of SUBSCRIBED_EVENTS) {
if (eventName === "HEARTBEAT") continue;
call.on(eventName, (raw) => handleEvent(eventName, raw));
}
});
client.on("reconnecting", (retryMs) => {
logger.warn("reconectando ao FreeSWITCH apos perda de conexao", { retryMs });
});
client.on("error", (err) => {
logger.error("erro no client ESL", { error: String(err) });
});
function handleEvent(eventName: string, raw: FreeSwitchEventData) {
// Para eventos JSON (event_json), os campos reais do evento FreeSWITCH
// (Event-Name, Unique-ID, Event-Subclass, variable_*, ...) vem em
// `raw.body`; `raw.headers` são só os headers do protocolo ESL.
const normalized = normalizeEslEvent(eventName, raw.body);
if (!normalized) {
logger.debug("evento sem mapeamento normalizado", { eventName });
return;
}
redis.publish(REDIS_CHANNEL, JSON.stringify(normalized)).catch((err) => {
logger.error("falha ao publicar evento normalizado no Redis", { error: String(err) });
});
logger.info(`evento: ${normalized.type}`, {
callUuid: normalized.callUuid,
tenantId: normalized.tenantId,
});
}
provider.connect();
const shutdown = async () => {
logger.info("encerrando b2bcall-fs-events");
await provider.disconnect();
redis.disconnect();
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
}
main().catch((err) => {
logger.error("falha fatal ao iniciar b2bcall-fs-events", { error: String(err) });
process.exit(1);
});

View File

@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"types": ["node"]
},
"include": ["src"]
}