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:
@@ -1,5 +1,6 @@
|
||||
import axios from "axios";
|
||||
import { Config } from "../Config";
|
||||
import { Logger } from "../Logger";
|
||||
|
||||
export enum VoiceType {
|
||||
// 현재(25.08.27)
|
||||
@@ -22,30 +23,64 @@ const defHeaders = {
|
||||
"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", {
|
||||
headers: defHeaders,
|
||||
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 || "오류");
|
||||
});
|
||||
});
|
||||
// 치지직이 응답하지 않을 때 봇이 무한정 기다리지 않도록 요청마다 타임아웃을 둔다.
|
||||
const TOKEN_TIMEOUT_MS = 3_000;
|
||||
const TTS_TIMEOUT_MS = 8_000;
|
||||
|
||||
export const textToSpeech = (text: string, voice: VoiceType) => new Promise<Buffer>(async (res, rej) => {
|
||||
axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", {
|
||||
message: text,
|
||||
token: await getToken().catch(() => "undefined"),
|
||||
type: "n"+voice
|
||||
}, {
|
||||
headers: defHeaders,
|
||||
responseType: "arraybuffer"
|
||||
}).then((val) => {
|
||||
if (val.status !== 200) return rej(val.data?.message || "오류");
|
||||
return res(val.data);
|
||||
}).catch((err) => {
|
||||
return rej(err.response?.data?.message || "오류");
|
||||
});
|
||||
});
|
||||
// 토큰 발급 결과 캐시. 성공하면 잠시 재사용하고, 실패(쿠키 만료 등)하면
|
||||
// 한동안 발급 요청 자체를 건너뛴다. 토큰 없이도 TTS 요청은 동작하므로
|
||||
// 실패 시에는 기존과 같이 "undefined" 토큰으로 보낸다.
|
||||
const TOKEN_OK_TTL_MS = 5 * 60_000;
|
||||
const TOKEN_FAIL_TTL_MS = 10 * 60_000;
|
||||
const NO_TOKEN = "undefined";
|
||||
let tokenCache: { token: string; expiresAt: number } | null = null;
|
||||
let tokenInflight: Promise<string> | null = null;
|
||||
|
||||
const errMessage = (err: any): string => {
|
||||
const status = err?.response?.status;
|
||||
const code = err?.code;
|
||||
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