diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 3ad6b5d..473e99a 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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: | diff --git a/app/api/health.py b/app/api/health.py index 6af7c42..d7923b9 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -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): diff --git a/tests/test_health.py b/tests/test_health.py new file mode 100644 index 0000000..bde51aa --- /dev/null +++ b/tests/test_health.py @@ -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()