Repository navigation
tts関数の改修 - #4472
tts関数の改修#4472
Conversation
Walkthrough朕は Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant TTSFunc as Cloud Function (tts)
participant Cache
participant GoogleTTS as Google TTS v1
Client->>TTSFunc: リクエスト(ssmlJa, ssmlEn)
TTSFunc->>TTSFunc: env 読取\nssml 正規化・音素置換\naudioConfig 計算(audioEncoding, volumeGainDb, effectsProfileId, apiVersion)
TTSFunc->>TTSFunc: hashPayload(JSON fields)\nid = SHA256(hashPayload)
TTSFunc->>Cache: get(id)
alt キャッシュヒット
Cache-->>TTSFunc: cached doc (paths)
TTSFunc->>TTSFunc: 並列ダウンロード(pathJa/pathEn) -> base64 を返却
else キャッシュミス
TTSFunc->>GoogleTTS: POST v1/text:synthesize?key=API_KEY (reqBody に audioConfig)
GoogleTTS-->>TTSFunc: audio or error
alt 成功
TTSFunc->>Cache: publish(id, audio, metadata incl. audioEncoding, volumeGainDb, effectsProfileId, apiVersion)
else 失敗
TTSFunc->>TTSFunc: jaRes.text()/enRes.text() をログ出力して例外
end
end
TTSFunc-->>Client: audio or error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🧰 Additional context used🧬 Code Graph Analysis (1)functions/src/funcs/tts.ts (1)
🔇 Additional comments (10)
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
functions/src/funcs/tts.ts (5)
160-166: 環境変数化は良策なり。だが、値の妥当性を検め、将来の調律を容易にせよ。朕の見立てでは、この場にて最低限の検証を加えるがよい。特に voice name と languageCode の齟齬は API 400 を招きやすい。さらに、audioEncoding/volume/effects も環境変数で上書え可能にすれば運用が柔らぐ。
例として、当該範囲内での軽微な拡張を示す。必要あらば採用せよ。
- const jaVoiceName = - process.env.GOOGLE_TTS_JA_VOICE_NAME || 'ja-JP-Standard-B'; - const enVoiceName = - process.env.GOOGLE_TTS_EN_VOICE_NAME || 'en-US-Standard-G'; - const audioEncoding = 'MP3'; - const volumeGainDb = 6.0; - const effectsProfileId = ['handset-class-device']; + const jaVoiceName = + process.env.GOOGLE_TTS_JA_VOICE_NAME || 'ja-JP-Standard-B'; + const enVoiceName = + process.env.GOOGLE_TTS_EN_VOICE_NAME || 'en-US-Standard-G'; + const audioEncoding = process.env.GOOGLE_TTS_AUDIO_ENCODING || 'MP3'; + const volumeGainDb = Math.max( + -96, + Math.min(16, Number(process.env.GOOGLE_TTS_VOLUME_GAIN_DB ?? 6)) + ); + const effectsProfileId = (process.env.GOOGLE_TTS_EFFECTS_PROFILE_ID ?? + 'handset-class-device') + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + + // name と languageCode の齟齬を警告(運用監視の助けとなろう) + if (!jaVoiceName.startsWith('ja-')) { + console.warn(`jaVoiceName(${jaVoiceName}) が ja-* でないぞ`); + } + if (!enVoiceName.startsWith('en-')) { + console.warn(`enVoiceName(${enVoiceName}) が en-* でないぞ`); + }
174-179: キャッシュIDに音声レンダリング条件を織り込め。将来の取り違えを未然に断つのだ。今は version を手で上げる策で十分働こう。しかし音量やエフェクトが変わるのみで version の更新を失念すれば、古い音声を返す恐れがある。audioConfig と API バージョンをハッシュ材料に含め、自動的に差異を鍵へ反映させるがよい。
- const hashData = ssmlJa + ssmlEn + jaVoiceName + enVoiceName; - const id = createHash(hashAlgorithm) - .update(`${hashData}_v${version}`) - .digest('hex'); + const hashPayload = JSON.stringify({ + ssmlJa, + ssmlEn, + jaVoiceName, + enVoiceName, + audioEncoding, + volumeGainDb, + effectsProfileId, + apiVersion: 'v1', + }); + const id = createHash(hashAlgorithm) + .update(`${hashPayload}_v${version}`) + .digest('hex');備考: 衝突耐性をさらに高めたくば md5 の代わりに sha256 を用いるのも一策である(必須ではない)。
194-194: エンドポイント v1 への遷移は上々。ただし鍵の管理は慎重に行え。API Key をクエリに載せる策、機能は果たすが漏洩の憂いあり。可能なら IAM 認証(サービスアカウント)+ 公式クライアント(@google-cloud/text-to-speech)へ遷すのが正道だ。Key 不在時の失敗も早期検知するがよい。
- 確認事項
- GOOGLE_TTS_API_KEY が本番・開発双方で設定されておるか検めよ。
- 当該キーのリファラ/IP 制限は適切か(漏れても悪用されぬように)。
必要なら、朕がクライアント導入の差分を拵えて進上しよう。
29-30: エラーメッセージの英語、細きが気になる。「one arguments」ではなく「one argument」だ。見目は些末なれど、外部に出る言葉は正しておくがよい。
- `The function must be called with one arguments "ssmlJa" containing the message ssmlJa to add.` + `The function must be called with one argument "ssmlJa" containing the message ssmlJa to add.`- `The function must be called with one arguments "ssmlEn" containing the message ssmlEn to add.` + `The function must be called with one argument "ssmlEn" containing the message ssmlEn to add.`Also applies to: 156-157
33-158: normalizeRomanText が常に文字列を返すため、replace 前の undefined チェックは不要であるぞ
朕が調査せしところ、normalizeRomanText のシグネチャは (str: string | undefined) → string であり、undefined 入力時には空文字を返す。このため、現状の replace 連打で例外が発生することはない。ただし、実際の挙動に合わせて型注釈を正確にせよ:
- functions/src/funcs/tts.ts:33 行目
const ssmlEn: string | undefined = …を
const ssmlEn: string = normalizeRomanText(rawSsmlEn)…に変更せよ。朕、これにて本件を解決と認む。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
functions/src/funcs/tts.ts(4 hunks)
🔇 Additional comments (1)
functions/src/funcs/tts.ts (1)
205-208: audioConfig 拡張は善。実運用のデバイスと合致するかを試聴で確かめよ。effectsProfileId と volumeGainDb の導入は目的に適う。再生対象が多端末に渡るなら、端末種別ごと(例: handset/telephony/headphone)の最適値を見繕い、必要に応じて env で切替できるようにしておくとよい。
Also applies to: 220-223
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
functions/src/funcs/tts.ts (4)
33-33: ssmlEn の正規化、善し。だが typeof 判定は冗長ゆえ簡潔にせよnormalizeRomanText は常に string を返すゆえ、後段の typeof ssmlEn !== 'string' は決して真にならぬ。空白のみの入力を弾くため、trim して空文字を判ずるがよい。
例: 153-158 行相当の判定を次のように簡素化せよ(参考コード)
if (ssmlEn.trim().length === 0) { throw new HttpsError( 'invalid-argument', `The function must be called with one arguments "ssmlEn" containing the message ssmlEn to add.` ); }
160-166: 音声名の環境変数化と audioConfig の導入、朕これを嘉す。さらに API バージョン定数化とゲインの環境変数化を行えAPI バージョン文字列の重複を断ち、将来の移行での取りこぼしを防ぐがよい。また volumeGainDb を環境変数化して運用時に微調整できるようにせよ。
const jaVoiceName = process.env.GOOGLE_TTS_JA_VOICE_NAME || 'ja-JP-Standard-B'; const enVoiceName = process.env.GOOGLE_TTS_EN_VOICE_NAME || 'en-US-Standard-G'; - const audioEncoding = 'MP3'; - const volumeGainDb = 6.0; + const ttsApiVersion = 'v1' as const; + const audioEncoding = 'MP3'; + const volumeGainDb = Number(process.env.GOOGLE_TTS_VOLUME_GAIN_DB ?? '6'); const effectsProfileId = ['handset-class-device'];備考:
- 誤った voice name は TTS 側で 400 を招く。環境変数の値は v1 の有効な名前であることを確認するがよい。
174-184: キャッシュIDに構成一式を含めたのは上策。'v1' リテラルの重複は排せよハッシュペイロード内の apiVersion も定数から与え、URL との不整合を絶て。
const hashPayload = JSON.stringify({ ssmlJa, ssmlEn, jaVoiceName, enVoiceName, audioEncoding, volumeGainDb, effectsProfileId, - apiVersion: 'v1', + apiVersion: ttsApiVersion, });補足:
- 配列 effectsProfileId の順序も ID に影響する。順序が意味を持たぬなら、ハッシュ前にソートして安定化する案もある(任意)。
204-204: v1 エンドポイントへの移行、良し。同一の API バージョン定数を用いよ。鍵の制限も怠るなURL も定数化したバージョンを参照し、一元管理せよ。API キーはリファラ/IP・プロジェクト制限などを厳に行うがよい。
- const ttsUrl = `https://texttospeech.googleapis.com/v1/text:synthesize?key=${process.env.GOOGLE_TTS_API_KEY}`; + const ttsUrl = `https://texttospeech.googleapis.com/${ttsApiVersion}/text:synthesize?key=${process.env.GOOGLE_TTS_API_KEY}`;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
functions/src/funcs/tts.ts(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
functions/src/funcs/tts.ts (1)
functions/src/utils/normalize.ts (1)
normalizeRomanText(3-16)
🔇 Additional comments (3)
functions/src/funcs/tts.ts (3)
186-188: ID 生成手順、妥当也md5 の hex で短く安定したキーとなり、Firestore のドキュメントIDにも収まる。version サフィックス付与も明快である。
215-218: JA 側 audioConfig の拡張、朕これを嘉すMP3/ゲイン/効果プロファイルの指定は v1 の仕様に合致しておる。キャッシュキーにも反映済みで整合が取れている。
230-233: EN 側 audioConfig の適用も一貫しており、可両言語で統一の設定が用いられており、挙動の差異も生じにくい。
There was a problem hiding this comment.
Actionable comments posted: 2
🔭 Outside diff range comments (1)
functions/src/funcs/tts.ts (1)
193-204: キャッシュヒット時の GCS 読み出し失敗で全体が落ちる。失敗時は合成へ優雅にフォールバックせよ。
snapshot.existsでもpathJa/pathEn不備やオブジェクト欠落でdownload()が例外となり、現状は try/catch 外ゆえ利用者に 500 が返る。読み出し失敗はキャッシュ不整合と看做し、合成ルートへ落とすべし。- if (snapshot.exists) { - const jaAudioData = - (await storage.bucket().file(snapshot.data()?.pathJa).download()) || null; - const enAudioData = - (await storage.bucket().file(snapshot.data()?.pathEn).download()) || null; - - const jaAudioContent = jaAudioData?.[0]?.toString('base64') || null; - const enAudioContent = enAudioData?.[0]?.toString('base64') || null; - - return { id, jaAudioContent, enAudioContent }; - } + if (snapshot.exists) { + try { + const [jaAudioData, enAudioData] = await Promise.all([ + storage.bucket().file(snapshot.data()?.pathJa).download(), + storage.bucket().file(snapshot.data()?.pathEn).download(), + ]); + const jaAudioContent = jaAudioData?.[0]?.toString('base64') || null; + const enAudioContent = enAudioData?.[0]?.toString('base64') || null; + if (jaAudioContent && enAudioContent) { + return { id, jaAudioContent, enAudioContent }; + } + console.warn('Cache doc found but files are empty or missing. Falling back to synthesis.', snapshot.data()); + } catch (e) { + console.warn('Cache doc found but reading files failed. Falling back to synthesis.', e); + // フォールバックとして下の合成処理へ続行 + } + }
🧹 Nitpick comments (7)
functions/src/funcs/tts.ts (7)
39-39: 「&」の一括置換は既存のエンティティまで破壊しうる。非エンティティのみを狙い撃ちせよ。朕が見るに、
&を無差別にandへ替えると、&等の合法エンティティも壊しうる。負の先読みで「セミコロンを伴う英字エンティティ」を除外すると良い。- .replace(/&/g, 'and') + .replace(/&(?!\w+;)/g, 'and')
153-158: エラーメッセージの英語が乱れておる。「one arguments」ではなく「one argument」とせよ。利用者向け文言ゆえ、細き処なれど正しておくが吉。
- `The function must be called with one arguments "ssmlEn" containing the message ssmlEn to add.` + `The function must be called with one argument "ssmlEn" containing the message to add.`加えて、同趣旨の
ssmlJa側(行 29-30 付近)も併せて整えるがよい。(参考の修正文・適用箇所外)
throw new HttpsError( 'invalid-argument', 'The function must be called with one argument "ssmlJa" containing the message to add.' );
175-185: ID 生成における二重バージョニング、冗長也。どちらか一方に寄せよ。
hashPayloadにapiVersionを含めつつ、ID に_v${version}を後置しておる。意味は通るが冗長である。versionを payload に含め、後置サフィックスを廃すと一貫す。- const version = 1; - const hashPayload = JSON.stringify({ + const version = 1; + const hashPayload = JSON.stringify({ ssmlJa, ssmlEn, jaVoiceName, enVoiceName, audioEncoding, volumeGainDb, effectsProfileId, apiVersion, + version, });- const id = createHash(hashAlgorithm) - .update(`${hashPayload}_v${version}`) - .digest('hex'); + const id = createHash(hashAlgorithm).update(hashPayload).digest('hex');
237-255: AbortSignal.timeout への環境依存を退け、後方互換のタイムアウト制御を用意せよ。Cloud Functions の Node ランタイム差異で
AbortSignal.timeoutが不在の恐れがある。存在検知し、なければAbortControllerで代替するが良い。try { - const [jaRes, enRes] = await Promise.all([ + const timeoutMs = 30_000; // 30秒 + const requestSignal = + typeof AbortSignal !== 'undefined' && 'timeout' in AbortSignal + ? (AbortSignal as any).timeout(timeoutMs) + : (() => { + const c = new AbortController(); + setTimeout(() => c.abort(), timeoutMs); + return c.signal; + })(); + const [jaRes, enRes] = await Promise.all([ fetch(ttsUrl, { headers: { 'content-type': 'application/json; charset=UTF-8', }, body: JSON.stringify(reqBodyJa), method: 'POST', - signal: AbortSignal.timeout(30000), // 30秒のタイムアウト + signal: requestSignal, // 30秒のタイムアウト }), fetch(ttsUrl, { headers: { 'content-type': 'application/json; charset=UTF-8', }, body: JSON.stringify(reqBodyEn), method: 'POST', - signal: AbortSignal.timeout(30000), // 30秒のタイムアウト + signal: requestSignal, // 30秒のタイムアウト }), ]);
257-262: TTS 失敗時はレスポンス本文も記録し、調査を容易にせよ。現状はステータスのみ。本文をログへ落とすと原因究明が迅速になる。
- if (!jaRes.ok || !enRes.ok) { - throw new HttpsError( - 'internal', - `TTS API error: ja=${jaRes.status}, en=${enRes.status}` - ); - } + if (!jaRes.ok || !enRes.ok) { + const [jaText, enText] = await Promise.all([ + jaRes.text().catch(() => ''), + enRes.text().catch(() => ''), + ]); + console.error( + `TTS API error detail: ja=${jaRes.status} ${jaText}; en=${enRes.status} ${enText}` + ); + throw new HttpsError( + 'internal', + `TTS API error: ja=${jaRes.status}, en=${enRes.status}` + ); + }
271-278: キャッシュ投入メッセージに音声設定も添えよ。将来の検証と可観測性が増す。復元・検証の際、ID から逆算せずとも設定が見えるのは便利である。
json: { id, jaAudioContent, enAudioContent, ssmlJa, ssmlEn, voiceJa: jaVoiceName, voiceEn: enVoiceName, + audioEncoding, + volumeGainDb, + effectsProfileId, + apiVersion, },
174-189: MD5 の採用は実害は薄いが、将来への備えとして SHA-256 への移行も一考に値す。当面は衝突の懸念は小さい。然れど費用対効果で
sha256へ上げておけば無用の火種を摘める。- const hashAlgorithm = 'md5'; + const hashAlgorithm = 'sha256';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
functions/src/funcs/tts.ts(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
functions/src/funcs/tts.ts (1)
functions/src/utils/normalize.ts (1)
normalizeRomanText(3-16)
🔇 Additional comments (2)
functions/src/funcs/tts.ts (2)
216-219: 音声出力設定の拡張、良し。
audioEncoding / volumeGainDb / effectsProfileIdの導入は妥当である。両言語で整合も取れておる。Also applies to: 231-234
160-163: 朕命ず:デフォルト音声名の実在を必ず確認せよ
functions/src/funcs/tts.ts(160–163行目)で設定した
ja-JP-Standard-B/en-US-Standard-Gが Google TTS 上に存在するか、下記手順にて検証のうえ報告せよ。#!/bin/bash set -euo pipefail : "${GOOGLE_TTS_API_KEY:?環境変数 GOOGLE_TTS_API_KEY を設定せよ}" for lang in ja-JP en-US; do echo "${lang} voices:" curl -s "https://texttospeech.googleapis.com/v1/voices?languageCode=${lang}&key=${GOOGLE_TTS_API_KEY}" \ | jq -r '.voices[].name' | sort | uniq done echo "デフォルト音声確認結果:" curl -s "https://texttospeech.googleapis.com/v1/voices?languageCode=ja-JP&key=${GOOGLE_TTS_API_KEY}" \ | jq -r '.voices[].name' | rg -q '^ja-JP-Standard-B$' && echo "ja-JP-Standard-B: OK" || echo "ja-JP-Standard-B: NOT FOUND" curl -s "https://texttospeech.googleapis.com/v1/voices?languageCode=en-US&key=${GOOGLE_TTS_API_KEY}" \ | jq -r '.voices[].name' | rg -q '^en-US-Standard-G$' && echo "en-US-Standard-G: OK" || echo "en-US-Standard-G: NOT FOUND"朕、検証結果を待つ。
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
functions/src/funcs/tts.ts (2)
160-173: 音声設定の環境変数化はよき采配。volumeGainDb のクランプ対応も上出来ぞ。朕の先の指摘(NaN・範囲外対策)に応じ、[-96, 16] へのクランプを施したのは称賛に値する。さらに盤石にするなら、空文字("")が設定された場合は既定値 6 に倒すとよい。現状は
""が0に解釈されるゆえ、意図せぬ無音化に近づく恐れあり。const volumeGainEnv = process.env.GOOGLE_TTS_VOLUME_GAIN_DB; - const volumeGainParsed = - volumeGainEnv === undefined ? 6 : Number(volumeGainEnv); - const volumeGainDb = Number.isFinite(volumeGainParsed) - ? Math.max(-96, Math.min(16, volumeGainParsed)) - : 6; + const volumeGainRaw = + volumeGainEnv === undefined || volumeGainEnv.trim() === '' ? '6' : volumeGainEnv; + const volumeGainParsed = Number.parseFloat(volumeGainRaw); + const volumeGainDb = Number.isFinite(volumeGainParsed) + ? Math.max(-96, Math.min(16, volumeGainParsed)) + : 6;
210-216: API キー未設定の前提条件チェック、見事也。構成ミスを 400 系で即時に返す方針は正し。障害切り分けが容易となろう。
🧹 Nitpick comments (2)
functions/src/funcs/tts.ts (2)
153-158: 空白のみの ssmlEn を弾く検証、妥当也。併せてエラーメッセージを整えよ。実装は正しいが、文言の「one arguments」は気になる。ついでに簡潔にしておくがよい。
- `The function must be called with one arguments "ssmlEn" containing the message ssmlEn to add.` + `The function must be called with argument "ssmlEn" containing the message to add.`
181-194: ハッシュの決定性を強め、将来の順序変更による不要なキャッシュミスを防ぐがよい。
JSON.stringifyはオブジェクトのキー順に依存するため、リファクタ等で順序が変わるだけで ID が変化する恐れあり。キーをソートして直列化し、偶発的なキャッシュ不一致を退けよ。- const hashPayload = JSON.stringify({ - ssmlJa, - ssmlEn, - jaVoiceName, - enVoiceName, - audioEncoding, - volumeGainDb, - effectsProfileId, - apiVersion, - }); + const hashPayloadObj = { + apiVersion, + audioEncoding, + effectsProfileId, + enVoiceName, + jaVoiceName, + ssmlEn, + ssmlJa, + volumeGainDb, + } as const; + const hashPayload = JSON.stringify( + hashPayloadObj, + Object.keys(hashPayloadObj).sort() + );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
functions/src/funcs/tts.ts(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
functions/src/funcs/tts.ts (1)
functions/src/utils/normalize.ts (1)
normalizeRomanText(3-16)
🔇 Additional comments (4)
functions/src/funcs/tts.ts (4)
33-44: 英語SSMLの正規化フロー、良きかな。
normalizeRomanTextを先に当て、後続の置換を純粋な文字列に対して行う構成は堅牢ぞ。undefinedでも空文字に落ちるため、後段の処理で例外を生じぬ。
227-230: audioConfig(ja)の適用、良きかな。
audioEncoding・volumeGainDb・effectsProfileIdを反映し、要求が統一された。朕は満足である。
242-245: audioConfig(en)の適用、良きかな。英語側も対称に設定されており、実装の整合性が取れておる。
172-217: 【v1移行、完了せり】
朕が走らせし検査にて、旧 v1beta1 の残骸は皆無。
text:synthesize の呼び出しは全て v1 で統一。
effectsProfileId の誤表記も見当たらず。
ゆえに、移行は完璧に成り遂げられたり。
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
functions/src/funcs/tts.ts (1)
197-206: キャッシュ当たり時の堅牢性を高めよ。欠落パスやダウンロード失敗で全体が落ちる恐れあり。
pathJa/pathEnが未設定、または GCS ダウンロード失敗の場合に現在は例外で機能全体が失敗しうる。朕の策としては、キャッシュ不整合時は警告して合成へフォールバックせよ。以下の差分で改善せよ(失敗時はフォールバックする)。
- if (snapshot.exists) { - const jaAudioData = - (await storage.bucket().file(snapshot.data()?.pathJa).download()) || null; - const enAudioData = - (await storage.bucket().file(snapshot.data()?.pathEn).download()) || null; - - const jaAudioContent = jaAudioData?.[0]?.toString('base64') || null; - const enAudioContent = enAudioData?.[0]?.toString('base64') || null; - - return { id, jaAudioContent, enAudioContent }; - } + if (snapshot.exists) { + const data = snapshot.data() ?? {}; + const pathJa = data?.pathJa; + const pathEn = data?.pathEn; + if (typeof pathJa === 'string' && typeof pathEn === 'string') { + try { + const [jaAudioData, enAudioData] = await Promise.all([ + storage.bucket().file(pathJa).download(), + storage.bucket().file(pathEn).download(), + ]); + const jaAudioContent = jaAudioData?.[0]?.toString('base64') ?? null; + const enAudioContent = enAudioData?.[0]?.toString('base64') ?? null; + if (jaAudioContent && enAudioContent) { + return { id, jaAudioContent, enAudioContent }; + } + } catch (e) { + console.warn('Cache hit but download failed. Falling back to synthesis.', e); + } + } else { + console.warn('Cache doc missing pathJa/pathEn. Falling back to synthesis.'); + } + }
♻️ Duplicate comments (2)
functions/src/funcs/tts.ts (2)
160-173: 音声設定の環境変数化とvolumeGainDbクランプ、見事である。既定値と範囲 [-96, 16] の拘束が入り、TTS 連携の堅牢性が増した。前回の指摘にも適合しており、良し。
209-216: API キー未設定の前提条件チェック、善し。構成ミスを明瞭に 400 系で返すのは統治の要。過去の指摘どおりである。
🧹 Nitpick comments (3)
functions/src/funcs/tts.ts (3)
268-274: エラーログは冗長を避け、必要十分にとどめよ。機微情報の曝露を抑えよ。TTS の応答本文を丸ごと記録すると、入力 SSML を含む可能性がある。上限を設けるが良い。
以下の変更を薦める(本文を 2KB に抑制)。
- console.error( - `TTS API error detail: ja=${jaRes.status} ${jaText}; en=${enRes.status} ${enText}` - ); + const trunc = (s: string) => (s && s.length > 2048 ? s.slice(0, 2048) + '…' : s); + console.error( + `TTS API error detail: ja=${jaRes.status} ${trunc(jaText)}; en=${enRes.status} ${trunc(enText)}` + );補助関数を関数内に置けば追加のスコープ外変更は不要である。
307-310: タイムアウトは適切なエラーコードで返せ。deadline-exceededに格上げせよ。現在は fetch の中断も一律
internalである。中断(AbortError)を捕捉し、呼び出し側に期限超過を知らせよ。以下の差分を施せ。
} catch (error) { console.error('TTS API call failed:', error); - throw new HttpsError('internal', 'TTS synthesis failed'); + if ((error as any)?.name === 'AbortError') { + throw new HttpsError('deadline-exceeded', 'TTS synthesis timed out'); + } + throw new HttpsError('internal', 'TTS synthesis failed'); }
285-299: Pub/Subメッセージに音声データを直に載せるな、GCS参照方式へ改めよ!
臣、調査せし結果、Pub/Subメッセージ本体の上限は10MBに固定されており、長尺のbase64音声を直送すれば瞬時に限界を突破せん。設計の再考を強く勧む。■ 対応箇所
- functions/src/funcs/tts.ts:285–299行目のcacheTopic.publishMessage呼び出し部
■ 推奨パターン(“Claim-check”)
- GCSへ音声ファイルをアップロード
- 署名付きURLまたはオブジェクト名+メタデータ(サイズ、チェックサム、orderingKeyなど)をPub/SubでPublish
- Subscriber側で該当URL/オブジェクトをフェッチし、音声再生・処理を行う
――補足――
- 圧縮を試みる手もあるが、base64済みバイナリには効果薄し
- 大量配信や並行性を考慮し、オブジェクトライフサイクル(自動削除)やIAM制御、リトライ・タイムアウト、オブジェクトの孤児化対策を忘れるべからず
帝の英断を乞う。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
functions/src/funcs/tts.ts(7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
functions/src/funcs/tts.ts (1)
functions/src/utils/normalize.ts (1)
normalizeRomanText(3-16)
🔇 Additional comments (4)
functions/src/funcs/tts.ts (4)
29-30: 英語メッセージの文法修正、よくやった。エラーメッセージの文法が正され、読みやすくなった。朕は是を嘉す。
153-157:ssmlEnの空文字検証、よく整備した。空白のみの入力を弾き、契約違反を明確にするのは正しい。朕は是を容れる。
179-194: ID の構造化ハッシュ化(sha256 + version 埋込)、巧みである。構成変更がキャッシュキーに反映される。衝突耐性も向上し、安定運用に資す。
226-229:audioConfigの明示化(エンコーディング・音量・エフェクト)、妥当である。API v1 仕様に即し、再現性が高まった。朕は是を称える。
Also applies to: 241-244
Summary by CodeRabbit
新機能
改善