fix: an R2 blip no longer makes /health a 503; storage down for 5 minutes does, reported once (DTF-API-B)
All checks were successful
Build and deploy / Validate source (push) Successful in 13s
Build and deploy / Integration suite on a real stack (push) Successful in 8m1s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m27s

R2 answered HeadBucket with a 500 now and then (34 times from 20/11) and
/health answered "Database or storage unavailable" although the database
was fine. The database down is still a 503 at once. Storage is asked
twice, 0,3 s apart, within the container check's 3 s; failing, the
answer says "storage": "unavailable" with 200 and logs a warning; after
5 minutes in a row it is a 503 and one error for Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-23 13:18:31 -03:00
parent d51fe24eea
commit 242a56aae8
3 changed files with 110 additions and 5 deletions

View File

@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v
- name: Runtime and retention regressions
run: |

View File

@@ -1,6 +1,8 @@
"""Health, session bootstrap, freight quoting and the address of a CEP."""
import logging
import os
import re
import time
import httpx
from fastapi import APIRouter, HTTPException, Request, Response
@@ -16,17 +18,53 @@ from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_se
router = APIRouter()
# Since when storage has failed the check, and whether Sentry heard of it.
# R2 answers HeadBucket with a 500 now and then (Sentry DTF-API-B, 34 times
# from 20/11): a blip is not the API being down.
STORAGE_DOWN_AFTER = 300
_storage = {'down_since': None, 'reported': False}
def storage_answers():
"""Whether storage answers, trying twice in well under the 3 s the
container's health check allows."""
for attempt in range(2):
try:
storage.health()
return True
except Exception as exc:
error = exc
if attempt == 0:
time.sleep(0.3)
logging.warning('Storage health check failed: %s', error)
return False
@router.get('/health')
@router.get('/api/health')
def health():
"""The database down is the API down: 503 at once. Storage failing is
reported in the answer and is a 503, with one error for Sentry, only when
it has lasted STORAGE_DOWN_AFTER seconds."""
try:
with db.connect() as c:
c.execute('SELECT 1')
storage.health()
except Exception:
raise HTTPException(503, 'Database or storage unavailable')
return {'status': 'ok', 'environment': ENVIRONMENT,
'storage': 'minio' if ENVIRONMENT == 'local' else 'r2', 'integrations': 'fake'}
raise HTTPException(503, 'Database unavailable')
if storage_answers():
_storage.update(down_since=None, reported=False)
state = 'minio' if ENVIRONMENT == 'local' else 'r2'
else:
if _storage['down_since'] is None:
_storage['down_since'] = time.monotonic()
since = _storage['down_since']
if time.monotonic() - since >= STORAGE_DOWN_AFTER:
if not _storage['reported']:
_storage['reported'] = True
logging.error('Storage has failed the health check for %d minutes', STORAGE_DOWN_AFTER // 60)
raise HTTPException(503, 'Storage unavailable')
state = 'unavailable'
return {'status': 'ok', 'environment': ENVIRONMENT, 'storage': state, 'integrations': 'fake'}
@router.get('/api/session')
def session(request: Request, response: Response):

67
tests/test_health.py Normal file
View File

@@ -0,0 +1,67 @@
"""The health check (Sentry DTF-API-B): an R2 blip is not the API down.
Runs in the API image: python -m unittest tests.test_health -v.
"""
import unittest
from contextlib import contextmanager
from unittest import mock
from fastapi import HTTPException
from app.api import health as module
@contextmanager
def database(up=True):
if not up:
raise RuntimeError('no database')
yield mock.MagicMock()
class HealthTests(unittest.TestCase):
def setUp(self):
module._storage.update(down_since=None, reported=False)
patches = [mock.patch.object(module.db, 'connect', database), mock.patch.object(module.time, 'sleep')]
for patch in patches:
patch.start()
self.addCleanup(patch.stop)
def check(self, storage_up, now=0):
storage = mock.MagicMock()
if not storage_up:
storage.health.side_effect = RuntimeError('R2 500')
with mock.patch.object(module, 'storage', storage), \
mock.patch.object(module.time, 'monotonic', return_value=now), \
mock.patch.object(module.logging, 'error') as error:
try:
return module.health(), error.call_count
except HTTPException as exc:
return exc.status_code, error.call_count
def test_a_storage_blip_is_reported_but_not_a_503(self):
answer, errors = self.check(storage_up=False, now=100)
self.assertEqual((answer['storage'], errors), ('unavailable', 0))
answer, _ = self.check(storage_up=True, now=150)
self.assertNotEqual(answer['storage'], 'unavailable')
def test_storage_down_for_five_minutes_is_a_503_reported_once(self):
self.check(storage_up=False, now=0)
self.assertEqual(self.check(storage_up=False, now=299)[0]['storage'], 'unavailable')
self.assertEqual(self.check(storage_up=False, now=300), (503, 1))
self.assertEqual(self.check(storage_up=False, now=400), (503, 0))
def test_one_retry_rides_out_a_single_failure(self):
storage = mock.MagicMock()
storage.health.side_effect = [RuntimeError('R2 500'), None]
with mock.patch.object(module, 'storage', storage):
self.assertTrue(module.storage_answers())
def test_the_database_down_is_a_503_at_once(self):
with mock.patch.object(module.db, 'connect', lambda: database(up=False)):
with self.assertRaises(HTTPException) as caught:
module.health()
self.assertEqual(caught.exception.status_code, 503)
if __name__ == '__main__':
unittest.main()