Skip to content

tts関数の改修 - #4472

Merged
TinyKitten merged 9 commits into
devfrom
feature/tts-gain
Aug 17, 2025
Merged

TinyKitten merged 9 commits into
devfrom
feature/tts-gain

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Aug 17, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • 新機能

    • 日本語/英語の音声を環境変数で切替可能に(既存デフォルト継続)。
    • 音声出力設定を拡張(MP3、音量ゲイン調整(デフォルト6、範囲制限あり)、ハンドセット向けプロファイル)。
    • 生成音声の識別にバージョニング付きSHA-256ハッシュを導入し、設定変更後も一貫したキャッシュ管理を実現。
    • 安定版のTTS API(v1)へ移行、APIキー必須化。
  • 改善

    • SSML整形を強化(HTMLエンティティ保護、発音マッピング拡張、不要記号除去)で音声品質向上。
    • キャッシュ取得で並列ダウンロード&フォールバック処理を導入。
    • TTS呼び出し失敗時のログを詳細化。

@TinyKitten TinyKitten self-assigned this Aug 17, 2025
@coderabbitai

coderabbitai Bot commented Aug 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

朕は functions/src/funcs/tts.ts を改め、SSML 正規化と発音置換を拡張し、音声名・音量・エフェクト・API バージョンを環境変数/定数化、ハッシュID を SHA-256 かつ構造化 payload へ変更し、Google TTS を v1 エンドポイントへ移行した。

Changes

Cohort / File(s) 変更概要
TTS 実装更新
functions/src/funcs/tts.ts
- エラーメッセージ修正("one arguments" → "one argument")
- ssmlEn を normalizeRomanText(req.data.ssmlEn) で生成、& 置換を HTML エンティティ保護に変更 (&(?!\w+;))、バッククォート除去追加
- ssmlJa の発音変換を大幅拡張(多数の音素マッピング追加)
- jaVoiceName/enVoiceName を env GOOGLE_TTS_JA_VOICE_NAME/GOOGLE_TTS_EN_VOICE_NAME(デフォルト有り)から取得
- audioEncoding='MP3'、volumeGainDb を GOOGLE_TTS_VOLUME_GAIN_DB(デフォルト6、クランプ -96〜16)、effectsProfileId=['handset-class-device']、apiVersion='v1' を導入し reqBody に反映
- ハッシュ方式を md5 → SHA-256 に変更、version=1 と構造化 hashPayload(json) を用い id を生成(キャッシュキー構造化)
- キャッシュヒット時は保存ドキュメントの pathJa/pathEn を並列ダウンロードして base64 を返却、失敗時はワーニング後に合成へフォールバック
- GOOGLE_TTS_API_KEY の存在チェック追加(未設定で failed-precondition を返す)
- TTS エンドポイントを v1(https://texttospeech.googleapis.com/v1/text:synthesize)へ切替、非 OK 応答時に ja/en のレスポンステキストを取得して詳細ログ出力
- キャッシュ公開ペイロードに audioEncoding・volumeGainDb・effectsProfileId・apiVersion を追加

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • TTS IPA追加 #4436: 同様の TTS 発音マッピング(駅名・地名の音素追加)を変更しておりコードレベルで重複する可能性大。
  • ttsのcloud functionの堅牢化 #4451: tts.ts とキャッシュ周りの公開/IO/エラーハンドリング改善を扱っており、実装が密接に関連。
  • TTS系の修正 #4049: normalizeRomanText の変更・利用に関する PR で、ssmlEn 正規化の依存先が一致するため関連。

Poem

吾が声よ、文字を磨け、環より名を得よ。
SHA の印を刻みて鍵となし、v1 の門に音を請う。
キャッシュは番兵、失せれば詳報を示せ。
音量を揃え、効果を添え、声は速やかに応えん。 🎺


📜 Recent 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 4723237 and 7f8e8f8.

📒 Files selected for processing (1)
  • functions/src/funcs/tts.ts (6 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 (10)
functions/src/funcs/tts.ts (10)

29-29: 文法修正は適切なり。

"one arguments" から "one argument" への修正は正しい。英語の文法に従い、単数形が適用されている。


33-43: SSML正規化の実装、朕の目に適う。

normalizeRomanText 関数の使用により型安全性が向上し、バッククォート除去の追加も適切である。HTMLエンティティ保護の負先読み正規表現も過去の指摘通り改修されており、優れた実装である。


55-151: 音素マッピングの大幅拡張、音声品質向上に資する。

駅名・地名の発音修正が大幅に追加され、日本の交通機関で使用される際の音声品質が大きく向上する。IPAによる音素記法も正確であり、実用性が高い。


153-158: エラーメッセージの文法修正、一貫性を保つ。

ssmlEnのエラーメッセージも "one argument" に修正され、ssmlJaと一貫性が保たれている。


160-172: 音声設定の環境変数化、構成管理の向上なり。

音声名、音量、エフェクト設定が環境変数化され、デプロイメント間での柔軟な設定変更が可能となった。volumeGainDbの範囲制限とNaN処理も過去の指摘通り実装されており、堅牢性が向上している。


179-197: ハッシュ化の改良、構造化されたペイロードは優秀なり。

SHA-256への変更とバージョン管理の導入により、ハッシュ衝突のリスクが軽減され、将来的な変更への対応も可能となった。構造化されたペイロードによる一貫したハッシュ生成も適切である。


201-227: キャッシュ処理の並列化、効率性の向上を見る。

Promise.allによる並列ダウンロードと適切なエラーハンドリングにより、キャッシュヒット時の応答性能が向上している。フォールバック処理も適切に実装されている。


246-248: 音声設定の統一、一貫性を保つ。

日本語・英語両方のリクエストボディで同一の音声設定が使用され、一貫したオーディオ品質が保証されている。

Also applies to: 261-263


287-299: エラー詳細の取得、デバッグ支援に有効。

API エラー時に応答テキストを取得してログ出力することで、問題の特定が容易になった。適切なエラーハンドリングの実装である。


315-318: キャッシュメッセージの拡張、メタデータ保存の完備。

音声設定とAPIバージョン情報がキャッシュに含まれることで、将来的な互換性確認や設定変更の追跡が可能となった。

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/tts-gain

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between db13001 and 505cfeb.

📒 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 505cfeb and c7424c1.

📒 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 の適用も一貫しており、可

両言語で統一の設定が用いられており、挙動の差異も生じにくい。

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 へ替えると、&amp; 等の合法エンティティも壊しうる。負の先読みで「セミコロンを伴う英字エンティティ」を除外すると良い。

-    .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.

📥 Commits

Reviewing files that changed from the base of the PR and between c7424c1 and dab0b29.

📒 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"

朕、検証結果を待つ。

Comment thread functions/src/funcs/tts.ts Resolved
Comment thread functions/src/funcs/tts.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between dab0b29 and 43e8af9.

📒 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 の誤表記も見当たらず。
ゆえに、移行は完璧に成り遂げられたり。

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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”)

  1. GCSへ音声ファイルをアップロード
  2. 署名付きURLまたはオブジェクト名+メタデータ(サイズ、チェックサム、orderingKeyなど)をPub/SubでPublish
  3. 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 43e8af9 and 4723237.

📒 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

Comment thread functions/src/funcs/tts.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant