Files
dtf-system/app/api/health.py
Cauê Faleiros 242a56aae8
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
fix: an R2 blip no longer makes /health a 503; storage down for 5 minutes does, reported once (DTF-API-B)
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>
2026-11-23 13:18:31 -03:00

157 lines
7.4 KiB
Python

"""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
from ..core import db
from .. import catalog, grade_rules, mail, observability
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
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')
except Exception:
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):
try:
session_id = owner(request)
except HTTPException:
# Per source, not per deployment: keyed on the environment name this was a
# single global bucket, so ~8 new visitors a minute exhausted it site-wide.
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
with db.connect() as c:
session_id = new_session(c, response)
with db.connect() as c:
products = catalog.current(c)
rules = grade_rules.current_rules(c)
treatment = products['tratamento']
redesign = products['redesenho']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
# Zero keeps Ajuste Fino hidden, as an off product does. Its bands
# are counted in arts, not metres.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
'treatment_bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in treatment['bands']] if treatment['enabled'] else [],
# Zero keeps Redesenho hidden, as an off product does. One price
# per art, never a band (front 1b).
'redesign_cents': redesign['unit_cents'] if redesign['enabled'] else 0,
# The grade rules the Site needs for the treatment requirement
# (front 8.5): {} when nothing is configured.
'grade_rules': rules,
# What the Site sells now: a switched-off product is hidden there.
# Bands travel with the price; the Site reads them as numbers.
'products': {mode: {**products[mode],
'bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in products[mode]['bands']]}
for mode in catalog.MODES},
# Public by design: the browser initialises Sentry with these; empty is off.
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
'sentry_release': observability.release() or '',
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.
'freight_services': delivery_services()}
@router.post('/api/freight')
def quote_freight(body: FreightEstimate):
require_delivery_available(body.service)
try:
return freight.quote(body.service, body.postal_code, body.metres, body.declared_cents)
except ValueError as exc:
raise HTTPException(422, str(exc))
@router.post('/api/freight/options')
def freight_options(body: FreightAsk, request: Request):
"""Every delivery option for the cart, cheapest first. Each asks a carrier,
so a source asking too often is held back."""
rate_limit('freight-options', client_ip(request), 120, 900)
if not delivery_services():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
found = freight.options(body.postal_code, body.metres, body.declared_cents)
if not found['options']:
reasons = '; '.join(item['error'] for item in found['unavailable'])
raise HTTPException(422, 'Não foi possível cotar a entrega para este CEP agora.' + (f' ({reasons})' if reasons else ''))
return found
# The address of a CEP, so the cart fills it in. Looked up here rather than in
# the browser, which keeps the Site's CSP to its own origin.
VIACEP = 'https://viacep.com.br/ws/{}/json/'
CEP_LIMIT = 120
@router.get('/api/cep/{cep}')
def cep_address(cep: str, request: Request):
if not re.fullmatch(r'[0-9]{8}', cep):
raise HTTPException(422, 'CEP must have eight digits')
rate_limit('cep-lookup', client_ip(request), CEP_LIMIT, 900)
try:
response = httpx.get(VIACEP.format(cep), timeout=5)
data = response.json() if response.status_code == 200 else {}
except (httpx.HTTPError, ValueError):
raise HTTPException(503, 'Consulta de CEP indisponível')
if not data or data.get('erro'):
raise HTTPException(404, 'CEP não encontrado')
return {'street': data.get('logradouro') or '', 'district': data.get('bairro') or '',
'city': data.get('localidade') or '', 'state': data.get('uf') or ''}