fix(brain): retry 503 once, don't persist failure message to DB

- analyzeWithGemini: 503(一時高負荷)は4秒後に1回リトライ
- 失敗時は null を返し、呼び出し側で DB を更新しない
  → 「AI分析に失敗しました」がsummaryとして永続化されなくなる

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
posimai 2026-04-14 23:39:46 +09:00
parent b0e77839c2
commit 47f82586d2
1 changed files with 11 additions and 7 deletions

View File

@ -428,8 +428,8 @@ function smartExtract(text, maxLen) {
return front + '\n\n[...中略...]\n\n' + back; return front + '\n\n[...中略...]\n\n' + back;
} }
async function analyzeWithGemini(title, fullText, url) { async function analyzeWithGemini(title, fullText, url, _retry = false) {
if (!genAI) return { summary: (fullText || '').slice(0, 120) || '(要約なし)', topics: ['その他'], readingTime: 3 }; if (!genAI) return null;
try { try {
const model = genAI.getGenerativeModel({ const model = genAI.getGenerativeModel({
model: 'gemini-2.5-flash', model: 'gemini-2.5-flash',
@ -471,11 +471,13 @@ ${smartExtract(fullText || '', 5000)}
if (typeof result !== 'undefined' && result?.response) { if (typeof result !== 'undefined' && result?.response) {
console.error('[Gemini] Raw response:', result.response.text()); console.error('[Gemini] Raw response:', result.response.text());
} }
return { // 503一時的高負荷は1回だけリトライ
summary: 'AI分析に失敗しました。しばらく後にお試しください。', if (!_retry && e.status === 503) {
topics: ['その他'], console.warn('[Gemini] 503 detected, retrying in 4s...');
readingTime: 3 await new Promise(r => setTimeout(r, 4000));
}; return analyzeWithGemini(title, fullText, url, true);
}
return null;
} }
} }
@ -1463,6 +1465,7 @@ function buildRouter() {
if (checkRateLimit('gemini_analyze', savedUserId, 50, 60 * 60 * 1000)) { if (checkRateLimit('gemini_analyze', savedUserId, 50, 60 * 60 * 1000)) {
analyzeWithGemini(finalTitle, fullText || meta.desc, url).then(async (ai) => { analyzeWithGemini(finalTitle, fullText || meta.desc, url).then(async (ai) => {
if (!ai) { console.warn(`[Brain API] AI analysis skipped (null) for ${url}`); return; }
await pool.query(` await pool.query(`
UPDATE articles SET summary=$1, topics=$2, reading_time=$3 UPDATE articles SET summary=$1, topics=$2, reading_time=$3
WHERE user_id=$4 AND url=$5 WHERE user_id=$4 AND url=$5
@ -1563,6 +1566,7 @@ function buildRouter() {
if (checkRateLimit('gemini_analyze', savedUserId, 50, 60 * 60 * 1000)) { if (checkRateLimit('gemini_analyze', savedUserId, 50, 60 * 60 * 1000)) {
analyzeWithGemini(meta.title, fullText, url).then(async (ai) => { analyzeWithGemini(meta.title, fullText, url).then(async (ai) => {
if (!ai) { console.warn(`[Brain API] AI analysis skipped (null) for ${url}`); return; }
await pool.query(` await pool.query(`
UPDATE articles SET summary=$1, topics=$2, reading_time=$3 UPDATE articles SET summary=$1, topics=$2, reading_time=$3
WHERE user_id=$4 AND url=$5 WHERE user_id=$4 AND url=$5