import { type Msg, type NatsConnection, StringCodec, connect, type Subscription, } from "nats"; import { getSecret } from "@common/secret-manager"; import { getNatsAclMode } from "../config.js"; import { getContext } from "../observability/context.js"; import { getLogger } from "@obs/logger"; import { checkPublishAllowed, checkSubscribeAllowed, } from "./nats-skill-acl.js"; export interface NatsMessageContext { data: T; raw: Msg; reply: string | undefined; subject: string; subscriptionSubject: string; } export class NatsClient { private client: NatsConnection | null = null; private readonly stringCodec = StringCodec(); private readonly logger = getLogger(); private getConnection(): NatsConnection { if (!this.client) { throw new Error("NATS client not connected"); } return this.client; } private decodeMessage(msg: Msg): T { return JSON.parse(this.stringCodec.decode(msg.data)) as T; } async connect(): Promise { const endpoint = getSecret("NATS_ENDPOINT"); const user = getSecret("NATS_USER"); const password = getSecret("NATS_PASS"); if (!endpoint || !user || !password) { throw new Error("Missing NATS credentials in secrets"); } this.client = await connect({ name: process.env["SERVICE_NAME"] || "lolympus-agent", servers: [endpoint], tls: {}, maxReconnectAttempts: -1, reconnectTimeWait: 500, reconnect: true, pingInterval: 20000, timeout: 5000, user: user, pass: password, }); this.logger.info("✓ NATS connected"); } async subscribe( subject: string, handler: ( data: T, context: NatsMessageContext, ) => void | Promise, ): Promise { return this.subscribeRaw(subject, async (msg) => { const data = this.decodeMessage(msg); await handler(data, { data, raw: msg, reply: msg.reply || undefined, subject: msg.subject, subscriptionSubject: subject, }); }); } subscribeRaw( subject: string, handler: (msg: Msg) => void | Promise, ): Promise { this.checkSubjectAcl("subscribe", subject); const subscription = this.getConnection().subscribe(subject); void (async () => { for await (const msg of subscription) { try { await handler(msg); } catch (error) { this.logger.error( { err: error, subject: msg.subject }, "[NATS] Error processing message", ); } } })(); this.logger.info({ subject }, "✓ Subscribed to subject"); return Promise.resolve(subscription); } async publish(subject: string, data: T): Promise { this.checkSubjectAcl("publish", subject); const client = this.getConnection(); client.publish(subject, this.stringCodec.encode(JSON.stringify(data))); await client.flush(); } async request( subject: string, data: TRequest, options?: { timeoutMs?: number | undefined }, ): Promise { this.checkSubjectAcl("publish", subject); const requestOptions = options?.timeoutMs !== undefined ? { timeout: options.timeoutMs, } : undefined; const response = await this.getConnection().request( subject, this.stringCodec.encode(JSON.stringify(data)), requestOptions, ); return this.decodeMessage(response); } private checkSubjectAcl( operation: "publish" | "subscribe", subject: string, ): void { const mode = getNatsAclMode(); if (mode === "off") { return; } const skill = getContext()?.skill; if (!skill) { return; } const allowed = operation === "publish" ? checkPublishAllowed(skill, subject) : checkSubscribeAllowed(skill, subject); if (allowed) { return; } const payload = { mode, operation, skill, subject }; if (mode === "enforce") { this.logger.error(payload, "[NATS ACL] Subject denied"); throw new Error( `NATS ${operation} denied for skill ${skill} on subject ${subject}`, ); } this.logger.warn(payload, "[NATS ACL] Subject would be denied"); } respond(msg: Msg, data: unknown): Promise { if (!msg.reply) { this.logger.warn( { subject: msg.subject }, "[NATS] Cannot respond: no reply subject", ); return Promise.resolve(); } msg.respond(this.stringCodec.encode(JSON.stringify(data))); return Promise.resolve(); } async close(): Promise { if (!this.client) return; try { const closed = this.client.closed(); await this.client.drain(); const err = await closed; if (err) { this.logger.error({ err }, "[NATS] Closed with error"); } } catch { try { await this.client.close(); } catch {} } } }