fix(tts): parallel synth, request timeouts, token cache, voice diagnostics
- Chzzk: 3s/8s axios timeouts; cache token (5m ok / 10m fail) with in-flight dedup so an expired cookie no longer costs a 401 round trip per message - TTSClient: synthesize signature-split parts concurrently (order kept); log per-message part count, failures and synth time; stop silently swallowing Chzzk errors - VoiceSession: decide "latest" by message arrival order so a slow older synth can no longer overwrite a newer message already playing; log voice connection state changes/errors and player (Auto)Paused events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,6 +35,9 @@ export class TTSClient {
|
|||||||
private map: Map<string, VoiceSession> = new Map();
|
private map: Map<string, VoiceSession> = new Map();
|
||||||
private maxLength = 300;
|
private maxLength = 300;
|
||||||
private leaveTime = 1000*60*10; // 10분
|
private leaveTime = 1000*60*10; // 10분
|
||||||
|
// 채팅이 도착한 순서. 합성이 늦게 끝난 이전 채팅이 이미 재생 중인
|
||||||
|
// 최신 채팅을 덮어쓰지 않도록 VoiceSession.play()에 함께 넘긴다.
|
||||||
|
private seq = 0;
|
||||||
|
|
||||||
public findSession(guildId: string) {
|
public findSession(guildId: string) {
|
||||||
return this.map.get(guildId);
|
return this.map.get(guildId);
|
||||||
@@ -66,13 +69,16 @@ export class TTSClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const seq = ++this.seq;
|
||||||
|
const startedAt = Date.now();
|
||||||
text = this.textEditor(channel.guild, text);
|
text = this.textEditor(channel.guild, text);
|
||||||
const voice = this.resolveUserVoice(channel.guild.id, member.id);
|
const voice = this.resolveUserVoice(channel.guild.id, member.id);
|
||||||
const buf = await this.getSource(text, voice);
|
const { buf, parts, failed } = await this.getSource(text, voice);
|
||||||
|
Logger.info(`[TTS] guild=${channel.guild.id} seq=${seq} parts=${parts} failed=${failed} synth=${Date.now() - startedAt}ms`);
|
||||||
if (!buf) return;
|
if (!buf) return;
|
||||||
|
|
||||||
const session = this.getSession(channel.guild, voiceChannel);
|
const session = this.getSession(channel.guild, voiceChannel);
|
||||||
session.play(buf);
|
session.play(buf, seq);
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly onSessionEnd = (guildId: string) => {
|
private readonly onSessionEnd = (guildId: string) => {
|
||||||
@@ -105,32 +111,30 @@ export class TTSClient {
|
|||||||
return DEFAULT_VOICE;
|
return DEFAULT_VOICE;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getSource(text: string, voice: VoiceType): Promise<Buffer | null> {
|
private async getSource(text: string, voice: VoiceType): Promise<{ buf: Buffer | null; parts: number; failed: number }> {
|
||||||
// 시그니처 목록이 비어 있으면 split을 건너뛰고 원문을 한 번에 합성한다.
|
// 시그니처 목록이 비어 있으면 split을 건너뛰고 원문을 한 번에 합성한다.
|
||||||
// (SignatureClient.regex가 빈 목록일 때 never-match 패턴을 돌려주지만,
|
// (SignatureClient.regex가 빈 목록일 때 never-match 패턴을 돌려주지만,
|
||||||
// 소비자 측에서도 명시적으로 가드해 의도를 분명히 한다.)
|
// 소비자 측에서도 명시적으로 가드해 의도를 분명히 한다.)
|
||||||
const names = signature.nameSet;
|
const names = signature.nameSet;
|
||||||
const parts = names.size === 0 ? [text] : text.split(signature.regex);
|
const parts = (names.size === 0 ? [text] : text.split(signature.regex)).filter(Boolean);
|
||||||
const bufferList: Buffer[] = [];
|
let failed = 0;
|
||||||
|
const synth = (part: string) => textToSpeech(this.textReplace(part), voice).catch((err) => {
|
||||||
|
failed++;
|
||||||
|
Logger.warn(String(err?.message ?? err));
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
for (const part of parts) {
|
// 조각을 동시에 합성하고 결과는 원래 순서대로 이어 붙인다.
|
||||||
if (!part) continue;
|
const bufferList = await Promise.all(parts.map(async (part) => {
|
||||||
if (signature.nameSet.has(part)) {
|
if (names.has(part)) {
|
||||||
const buf = await signature.getBuffer(part);
|
const buf = await signature.getBuffer(part);
|
||||||
if (buf) {
|
if (buf) return buf;
|
||||||
bufferList.push(buf);
|
|
||||||
} else {
|
|
||||||
const buf = await textToSpeech(this.textReplace(part), voice).catch(() => null);
|
|
||||||
if (buf) bufferList.push(buf);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const buf = await textToSpeech(this.textReplace(part), voice).catch(() => null);
|
|
||||||
if (buf) bufferList.push(buf);
|
|
||||||
}
|
}
|
||||||
}
|
return synth(part);
|
||||||
|
}));
|
||||||
|
|
||||||
if (bufferList.length === 0) return null;
|
const valid = bufferList.filter((b): b is Buffer => !!b);
|
||||||
return Buffer.concat(bufferList);
|
return { buf: valid.length === 0 ? null : Buffer.concat(valid), parts: parts.length, failed };
|
||||||
}
|
}
|
||||||
|
|
||||||
private textEditor(guild: Guild, text: string): string {
|
private textEditor(guild: Guild, text: string): string {
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import { createResourceFromMp3Buffer } from "../utils/Transcode";
|
|||||||
export class VoiceSession {
|
export class VoiceSession {
|
||||||
private player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
|
private player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
|
||||||
|
|
||||||
private generation = 0;
|
// 마지막으로 재생을 시작한 채팅의 도착 순번(TTSClient.seq).
|
||||||
|
private lastPlayedSeq = 0;
|
||||||
private isSessionEnd = false;
|
private isSessionEnd = false;
|
||||||
private lastTime = Date.now();
|
private lastTime = Date.now();
|
||||||
private endTimer?: NodeJS.Timeout | null;
|
private endTimer?: NodeJS.Timeout | null;
|
||||||
@@ -29,7 +30,33 @@ export class VoiceSession {
|
|||||||
this.init();
|
this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private get tag() {
|
||||||
|
return `[Voice] guild=${this.guild.id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 끊김 원인 추적용: 음성 연결 상태 변화와 오류를 남긴다.
|
||||||
|
private watchConnection(connection: VoiceConnection) {
|
||||||
|
connection.on("stateChange", (oldState, newState) => {
|
||||||
|
if (oldState.status === newState.status) return;
|
||||||
|
const reason = newState.status === VoiceConnectionStatus.Disconnected
|
||||||
|
? ` reason=${newState.reason} closeCode=${"closeCode" in newState ? newState.closeCode : "-"}`
|
||||||
|
: "";
|
||||||
|
Logger.info(`${this.tag} connection ${oldState.status} -> ${newState.status}${reason}`);
|
||||||
|
});
|
||||||
|
connection.on("error", (e) => {
|
||||||
|
Logger.error(`${this.tag} connection error: ${String(e)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async init() {
|
private async init() {
|
||||||
|
this.watchConnection(this.connection);
|
||||||
|
// 재생 중 일시정지(연결 미준비로 AutoPaused 등)는 음성이 끊기는 직접 신호다.
|
||||||
|
this.player.on("stateChange", (oldState, newState) => {
|
||||||
|
const s = [oldState.status, newState.status];
|
||||||
|
if (s.includes(AudioPlayerStatus.AutoPaused) || s.includes(AudioPlayerStatus.Paused)) {
|
||||||
|
Logger.info(`${this.tag} player ${oldState.status} -> ${newState.status}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
this.connection.subscribe(this.player);
|
this.connection.subscribe(this.player);
|
||||||
await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {});
|
await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {});
|
||||||
this.player.on(AudioPlayerStatus.Playing, () => {
|
this.player.on(AudioPlayerStatus.Playing, () => {
|
||||||
@@ -64,18 +91,23 @@ export class VoiceSession {
|
|||||||
* 새 TTS가 들어오면 이전 재생을 의도적으로 interrupt한다 (큐잉 없음).
|
* 새 TTS가 들어오면 이전 재생을 의도적으로 interrupt한다 (큐잉 없음).
|
||||||
* 다중 사용자 환경에서 모든 메시지를 큐로 쌓으면 자기 발화가 수십 초
|
* 다중 사용자 환경에서 모든 메시지를 큐로 쌓으면 자기 발화가 수십 초
|
||||||
* 밀려 채팅 맥락과 어긋나므로, "최신 발화 우선, 앞건 잘림"을 정책으로
|
* 밀려 채팅 맥락과 어긋나므로, "최신 발화 우선, 앞건 잘림"을 정책으로
|
||||||
* 채택했다. generation 카운터는 같은 메시지에 대해 한 번만 play 되도록
|
* 채택했다. 이전 mp3가 잘리는 동작 자체는 설계 의도이다.
|
||||||
* 보호하는 용도이고, 이전 mp3가 잘리는 동작 자체는 설계 의도이다.
|
* 단, "최신"은 합성 완료 순서가 아니라 채팅 도착 순서(seq)로 판단한다.
|
||||||
|
* 먼저 온 채팅의 합성이 늦게 끝났다면, 이미 재생을 시작한 더 최신
|
||||||
|
* 채팅을 덮어쓰지 않고 버린다.
|
||||||
*/
|
*/
|
||||||
public async play(mp3Buf: Buffer) {
|
public async play(mp3Buf: Buffer, seq: number) {
|
||||||
if (this.isSessionEnd) return;
|
if (this.isSessionEnd) return;
|
||||||
const myGen = ++this.generation;
|
if (seq <= this.lastPlayedSeq) {
|
||||||
|
Logger.info(`${this.tag} seq=${seq} dropped (newer seq=${this.lastPlayedSeq} already playing)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.lastPlayedSeq = seq;
|
||||||
|
|
||||||
this.lastTime = Date.now();
|
this.lastTime = Date.now();
|
||||||
this.startEndTimer();
|
this.startEndTimer();
|
||||||
|
|
||||||
const res = createResourceFromMp3Buffer(mp3Buf);
|
const res = createResourceFromMp3Buffer(mp3Buf);
|
||||||
if (myGen !== this.generation || this.isSessionEnd) return;
|
|
||||||
// try { this.player.stop(true); } catch {};
|
// try { this.player.stop(true); } catch {};
|
||||||
try { this.player.play(res); } catch {};
|
try { this.player.play(res); } catch {};
|
||||||
}
|
}
|
||||||
@@ -94,6 +126,7 @@ export class VoiceSession {
|
|||||||
selfDeaf: true,
|
selfDeaf: true,
|
||||||
selfMute: false,
|
selfMute: false,
|
||||||
});
|
});
|
||||||
|
this.watchConnection(this.connection);
|
||||||
this.connection.subscribe(this.player);
|
this.connection.subscribe(this.player);
|
||||||
await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {});
|
await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { Config } from "../Config";
|
import { Config } from "../Config";
|
||||||
|
import { Logger } from "../Logger";
|
||||||
|
|
||||||
export enum VoiceType {
|
export enum VoiceType {
|
||||||
// 현재(25.08.27)
|
// 현재(25.08.27)
|
||||||
@@ -22,30 +23,64 @@ const defHeaders = {
|
|||||||
"Cookie": Object.entries(Config.chzzk).map(([key, value]) => key+'='+value).join(';'),
|
"Cookie": Object.entries(Config.chzzk).map(([key, value]) => key+'='+value).join(';'),
|
||||||
};
|
};
|
||||||
|
|
||||||
const getToken = () => new Promise<string>((res, rej) => {
|
// 치지직이 응답하지 않을 때 봇이 무한정 기다리지 않도록 요청마다 타임아웃을 둔다.
|
||||||
axios.get("https://api.chzzk.naver.com/service/v1/alerts/token", {
|
const TOKEN_TIMEOUT_MS = 3_000;
|
||||||
headers: defHeaders,
|
const TTS_TIMEOUT_MS = 8_000;
|
||||||
responseType: "json"
|
|
||||||
}).then((val) => {
|
|
||||||
if (!val.data?.content?.token) return rej(val.data?.message || "오류");
|
|
||||||
return res(val.data.content.token);
|
|
||||||
}).catch((err) => {
|
|
||||||
return rej(err.response?.data?.message || "오류");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
export const textToSpeech = (text: string, voice: VoiceType) => new Promise<Buffer>(async (res, rej) => {
|
// 토큰 발급 결과 캐시. 성공하면 잠시 재사용하고, 실패(쿠키 만료 등)하면
|
||||||
axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", {
|
// 한동안 발급 요청 자체를 건너뛴다. 토큰 없이도 TTS 요청은 동작하므로
|
||||||
message: text,
|
// 실패 시에는 기존과 같이 "undefined" 토큰으로 보낸다.
|
||||||
token: await getToken().catch(() => "undefined"),
|
const TOKEN_OK_TTL_MS = 5 * 60_000;
|
||||||
type: "n"+voice
|
const TOKEN_FAIL_TTL_MS = 10 * 60_000;
|
||||||
}, {
|
const NO_TOKEN = "undefined";
|
||||||
headers: defHeaders,
|
let tokenCache: { token: string; expiresAt: number } | null = null;
|
||||||
responseType: "arraybuffer"
|
let tokenInflight: Promise<string> | null = null;
|
||||||
}).then((val) => {
|
|
||||||
if (val.status !== 200) return rej(val.data?.message || "오류");
|
const errMessage = (err: any): string => {
|
||||||
return res(val.data);
|
const status = err?.response?.status;
|
||||||
}).catch((err) => {
|
const code = err?.code;
|
||||||
return rej(err.response?.data?.message || "오류");
|
return [status && `status=${status}`, code && `code=${code}`, err?.message].filter(Boolean).join(" ") || "오류";
|
||||||
});
|
};
|
||||||
});
|
|
||||||
|
const fetchToken = async (): Promise<string> => {
|
||||||
|
try {
|
||||||
|
const val = await axios.get("https://api.chzzk.naver.com/service/v1/alerts/token", {
|
||||||
|
headers: defHeaders,
|
||||||
|
responseType: "json",
|
||||||
|
timeout: TOKEN_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
const token = val.data?.content?.token;
|
||||||
|
if (!token) throw new Error(val.data?.message || "토큰 없음");
|
||||||
|
tokenCache = { token, expiresAt: Date.now() + TOKEN_OK_TTL_MS };
|
||||||
|
return token;
|
||||||
|
} catch (err) {
|
||||||
|
Logger.warn(`[Chzzk] 토큰 발급 실패(${errMessage(err)}), ${TOKEN_FAIL_TTL_MS / 60_000}분간 토큰 없이 요청`);
|
||||||
|
tokenCache = { token: NO_TOKEN, expiresAt: Date.now() + TOKEN_FAIL_TTL_MS };
|
||||||
|
return NO_TOKEN;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getToken = (): Promise<string> => {
|
||||||
|
if (tokenCache && tokenCache.expiresAt > Date.now()) return Promise.resolve(tokenCache.token);
|
||||||
|
// 동시에 여러 채팅이 와도 발급 요청은 한 번만 보낸다.
|
||||||
|
if (!tokenInflight) tokenInflight = fetchToken().finally(() => { tokenInflight = null; });
|
||||||
|
return tokenInflight;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const textToSpeech = async (text: string, voice: VoiceType): Promise<Buffer> => {
|
||||||
|
const token = await getToken();
|
||||||
|
try {
|
||||||
|
const val = await axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", {
|
||||||
|
message: text,
|
||||||
|
token,
|
||||||
|
type: "n"+voice
|
||||||
|
}, {
|
||||||
|
headers: defHeaders,
|
||||||
|
responseType: "arraybuffer",
|
||||||
|
timeout: TTS_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
return Buffer.from(val.data);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`[Chzzk] TTS 요청 실패(${errMessage(err)})`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user