Merge Critical Corrections plan 002: two API processes, worker drains its queue
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m11s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m11s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -94,7 +94,7 @@ jobs:
|
|||||||
# the generator's geometry. The provider suites use a fake transport: they
|
# the generator's geometry. The provider suites use a fake transport: they
|
||||||
# prove the documented contract, not the integration.
|
# prove the documented contract, not the integration.
|
||||||
- name: Print-file geometry and provider adapters
|
- 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_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats -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_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v
|
||||||
|
|
||||||
- name: Runtime and retention regressions
|
- name: Runtime and retention regressions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -53,10 +53,13 @@ def cleanup():
|
|||||||
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
|
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
|
||||||
|
|
||||||
def tick():
|
def tick():
|
||||||
|
"""Deliver at most one outbox job; True when there was one, False otherwise."""
|
||||||
global last_tick
|
global last_tick
|
||||||
|
processed = False
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
|
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
|
||||||
if job:
|
if job:
|
||||||
|
processed = True
|
||||||
try:
|
try:
|
||||||
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
|
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
|
||||||
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
|
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
|
||||||
@@ -64,6 +67,14 @@ def tick():
|
|||||||
delay = min(1800, 2**min(job['attempts']+1, 10))
|
delay = min(1800, 2**min(job['attempts']+1, 10))
|
||||||
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
|
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
|
||||||
last_tick = time.monotonic()
|
last_tick = time.monotonic()
|
||||||
|
return processed
|
||||||
|
|
||||||
|
def drain(limit=50):
|
||||||
|
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
|
||||||
|
once instead of one job per second (Critical Corrections item 9)."""
|
||||||
|
for _ in range(limit):
|
||||||
|
if not tick():
|
||||||
|
return
|
||||||
|
|
||||||
def tiny_keepalive():
|
def tiny_keepalive():
|
||||||
"""Keep a connected Tiny authorised even while no orders are sent.
|
"""Keep a connected Tiny authorised even while no orders are sent.
|
||||||
@@ -118,7 +129,7 @@ def loop():
|
|||||||
global last_cleanup
|
global last_cleanup
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
tick()
|
drain()
|
||||||
if time.monotonic()-last_cleanup > 60:
|
if time.monotonic()-last_cleanup > 60:
|
||||||
cleanup()
|
cleanup()
|
||||||
# Approved quotes unpaid for 24 h expire on their own (front 9).
|
# Approved quotes unpaid for 24 h expire on their own (front 9).
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ PUBLIC_HOST=dtf.example.invalid
|
|||||||
KANBAN_HOST=kanban-dtf.example.invalid
|
KANBAN_HOST=kanban-dtf.example.invalid
|
||||||
SITE_PORT=8080
|
SITE_PORT=8080
|
||||||
KANBAN_PORT=8081
|
KANBAN_PORT=8081
|
||||||
|
# API processes: 2 by default; 1 runs one process, as before. API only.
|
||||||
|
API_WORKERS=2
|
||||||
|
|
||||||
R2_ENDPOINT=TBD
|
R2_ENDPOINT=TBD
|
||||||
R2_PUBLIC_ENDPOINT=TBD
|
R2_PUBLIC_ENDPOINT=TBD
|
||||||
|
|||||||
@@ -213,13 +213,20 @@ services:
|
|||||||
|
|
||||||
api:
|
api:
|
||||||
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
|
||||||
environment: *app-environment
|
environment:
|
||||||
|
<<: *app-environment
|
||||||
|
# Two uvicorn processes by default (Critical Corrections item 2, step 1):
|
||||||
|
# a slow 150 MB PDF check no longer holds every request in the only one.
|
||||||
|
# API_WORKERS=1 restores one process without a new image.
|
||||||
|
WEB_CONCURRENCY: "${API_WORKERS:-2}"
|
||||||
networks: [backend, egress]
|
networks: [backend, egress]
|
||||||
read_only: true
|
read_only: true
|
||||||
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
|
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
|
||||||
# writable /tmp at all. The long volume syntax is what a stack honours.
|
# writable /tmp at all. The long volume syntax is what a stack honours.
|
||||||
|
# 512 MiB, not 256: with two processes each may write a 150 MB PDF from the
|
||||||
|
# grade check at the same time.
|
||||||
volumes:
|
volumes:
|
||||||
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
|
- {type: tmpfs, target: /tmp, tmpfs: {size: 536870912}}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
|
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
|
||||||
interval: 15s
|
interval: 15s
|
||||||
|
|||||||
@@ -226,6 +226,15 @@ If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
|
|||||||
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
|
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
|
||||||
package weights must be set (they already are for Jadlog).
|
package weights must be set (they already are for Jadlog).
|
||||||
|
|
||||||
|
## 9. API processes
|
||||||
|
|
||||||
|
`API_WORKERS` is how many uvicorn processes the API container runs (default 2;
|
||||||
|
`1` runs one process, as before). More than one keeps a slow checkout, such as
|
||||||
|
a PDF of up to 150 MB being checked, from holding every other request in the
|
||||||
|
only process; the API's `/tmp` is sized for two such checks at once. It applies
|
||||||
|
to the API only, never to the worker. Set it in the stack's environment and
|
||||||
|
redeploy.
|
||||||
|
|
||||||
## Current blocker
|
## Current blocker
|
||||||
|
|
||||||
This is the final deployment shape, but it is not authorized for production
|
This is the final deployment shape, but it is not authorized for production
|
||||||
|
|||||||
27
tests/test_worker_drain.py
Normal file
27
tests/test_worker_drain.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
"""The outbox worker drains a backlog instead of one job per second (item 9).
|
||||||
|
|
||||||
|
Run from the repository root: python3 -m unittest tests.test_worker_drain -v.
|
||||||
|
The worker imports psycopg and boto3, so a host without the API image's
|
||||||
|
dependencies cannot import it; CI runs this in the api container.
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from app import worker
|
||||||
|
|
||||||
|
|
||||||
|
class WorkerDrainTest(unittest.TestCase):
|
||||||
|
def test_drain_stops_when_the_queue_is_empty(self):
|
||||||
|
with mock.patch.object(worker, 'tick',
|
||||||
|
side_effect=[True, True, True, False]) as tick:
|
||||||
|
worker.drain()
|
||||||
|
self.assertEqual(tick.call_count, 4)
|
||||||
|
|
||||||
|
def test_drain_stops_at_the_limit(self):
|
||||||
|
with mock.patch.object(worker, 'tick', return_value=True) as tick:
|
||||||
|
worker.drain()
|
||||||
|
self.assertEqual(tick.call_count, 50)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user