fix(async): chiamate bloccanti in asyncio.to_thread (#36 punto 1)

kaleido (pio.to_image), WeasyPrint (write_pdf), pdfplumber (extract_text_from_pdf)
e la scrittura del CSV di produzione giravano sincrone dentro handler async:
un PDF pesante o un run grande fermava il worker per tutte le altre richieste.
Ora avvolte in await asyncio.to_thread(...) in report_service.py,
ai_service.py e production_export_service.py.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 22:38:28 +02:00
parent 78970c69b0
commit 3f70f99a40
3 changed files with 27 additions and 9 deletions
@@ -9,6 +9,7 @@ The CSV uses the delimiters configured in system_settings, the same ones the man
export honours, so a shop floor set to the Italian convention (';' and ',') gets
files that open correctly in their Excel.
"""
import asyncio
import csv
import io
import logging
@@ -192,7 +193,11 @@ async def export_run_statistics(db: AsyncSession, run: ProductionRun) -> str | N
stamp = (run.closed_at or datetime.now()).strftime("%Y%m%d_%H%M%S")
filename = f"production_{run.id}_{stamp}.csv"
(directory / filename).write_text(content, encoding="utf-8-sig")
# A large run's file can take a moment to write: off the event loop, so
# closing one run does not stall every other request being served.
await asyncio.to_thread(
(directory / filename).write_text, content, encoding="utf-8-sig"
)
# utf-8-sig: the BOM is what makes Excel read accented characters correctly,
# and these files are opened in Excel on the shop floor.