All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m17s
The card's "Abrir e conferir" opens the order's print file full screen (Dropstar's third round, item 7): zoom up to 100% real (one file pixel, one screen pixel), the position in cm, the order's files one after the other without closing, and the background behind the transparency light, dark or checkered, remembered (Dropstar, 2026-10-30). Closed in Arte recebida, it asks "Está OK?": the class of each item, prefilled with the measure, then "Mover para Arte conferida" (the final approved, the class kept, the card moved) or "Tratar a arte". A 15 m film is loaded like a map: while the PNG is written, its strips of 512 rows go to storage at 100% and at each halving (app/printtiles.py, originals/tiles/<upload>/), and the viewer (web/kanban-viewer.js) fetches only those on screen. They go when their file expires. Storing a print file that fails is now an attempt like a failed render, not a claim held for an hour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
211 lines
9.9 KiB
Python
211 lines
9.9 KiB
Python
"""Generating print files in the background, one order item at a time.
|
|
|
|
A paid order queues one job per item. The worker claims a job, commits the
|
|
claim, and renders outside any transaction, so a long render never holds a row
|
|
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
|
|
belong to a worker that died and is taken again.
|
|
|
|
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
|
|
film over 15 m: ordinary upload rows owned by an identity derived from the
|
|
order, already marked clean, since their only inputs are artwork that passed
|
|
the malware scan and the bytes are written here. dtf_local.print_parts lists
|
|
them in order. The operator still decides whether they become the final
|
|
file; generation never approves anything.
|
|
|
|
Sheets of several GB are the normal order: a PNG or a PDF is read band by
|
|
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
|
|
is prepared by hand from the original.
|
|
"""
|
|
import logging
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
import time
|
|
from datetime import timedelta
|
|
from decimal import Decimal
|
|
from zoneinfo import ZoneInfo
|
|
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
|
|
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from .core.auth import audit
|
|
from .core.db import connect
|
|
from .printfile import Unsupported
|
|
from .printpng import render
|
|
from .tiny import purchase_order
|
|
|
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
|
|
|
# A 15 m part takes minutes to write; a long film, several parts.
|
|
CLAIM_TIMEOUT = timedelta(minutes=60)
|
|
MAX_ATTEMPTS = 3
|
|
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
|
|
# Read band by band, whatever their size.
|
|
STREAMED = ('.png', '.pdf')
|
|
|
|
|
|
def generated_identity(order_id):
|
|
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
|
|
|
|
|
def queue(c, order_id, items, only_missing=False):
|
|
"""Queue (or re-queue) generation for every item of an order."""
|
|
for index in range(items):
|
|
if only_missing:
|
|
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
|
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
|
claimed_at=NULL, finished_at=NULL, detail='{}'
|
|
WHERE dtf_local.print_files.status IN ('failed','manual')''',
|
|
(uuid4(), order_id, index))
|
|
else:
|
|
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
|
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
|
|
|
|
|
|
def claim(c):
|
|
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
|
JOIN dtf_local.orders o ON o.id=p.order_id
|
|
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
|
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
|
|
|
|
|
def render_one(storage):
|
|
with connect() as c:
|
|
job = claim(c)
|
|
if not job:
|
|
return False
|
|
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
|
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
|
item = job['snapshot']['items'][job['item_index']]
|
|
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
|
|
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
|
|
([UUID(u) for u in item['uploads']],)).fetchall()
|
|
# Every generated file shares its order's artwork retention deadline.
|
|
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
|
|
([UUID(u) for u in item['uploads']],)).fetchone()['e']
|
|
by_id = {str(row['id']): row for row in uploads}
|
|
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
|
|
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
|
|
'monte a folha a partir do original'})
|
|
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
|
return True
|
|
try:
|
|
result = produce(storage, job, item, by_id)
|
|
except Unsupported as reason:
|
|
finish(job, 'manual', {'reason': str(reason)})
|
|
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
|
return True
|
|
except Exception as exc:
|
|
logging.exception('Print file generation failed')
|
|
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
|
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
|
return True
|
|
scratch, parts, detail = result
|
|
stored = []
|
|
try:
|
|
for path, name in parts:
|
|
uid = uuid4()
|
|
key = f'originals/{uid}'
|
|
storage.store(key, path, 'image/png')
|
|
stored.append((uid, name, os.path.getsize(path), key))
|
|
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
|
|
except Exception as exc:
|
|
# Storage failing is an attempt like any other, not a claim held for an hour.
|
|
logging.exception('Storing the print file failed')
|
|
finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__})
|
|
return True
|
|
finally:
|
|
shutil.rmtree(scratch, ignore_errors=True)
|
|
for part, (uid, _, size, _) in zip(detail['parts'], stored):
|
|
part.update(upload_id=str(uid), size=size)
|
|
with connect() as c:
|
|
for uid, name, size, key in stored:
|
|
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
|
expires_at,scan_state,scan_reason,scanned_at)
|
|
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
|
|
(uid, generated_identity(job['order_id']), name, size, key, expiry))
|
|
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
|
|
finished_at=now() WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
|
|
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
|
|
(job['order_id'], job['item_index']))
|
|
for number, (uid, _, _, _) in enumerate(stored, 1):
|
|
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)',
|
|
(job['order_id'], job['item_index'], number, uid))
|
|
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
|
|
return True
|
|
|
|
|
|
def store_tiles(storage, folder, upload_id):
|
|
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
|
|
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
|
|
if not os.path.isdir(folder):
|
|
return
|
|
for level in sorted(os.listdir(folder)):
|
|
for strip in sorted(os.listdir(os.path.join(folder, level))):
|
|
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
|
|
|
|
|
|
def file_prefix(number, item_index):
|
|
"""How an order's files are named: DTF-23-item-1, the code the Kanban
|
|
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
|
|
return f'DTF-{number}-item-{item_index + 1}'
|
|
|
|
|
|
def footer(job, item):
|
|
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
|
|
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
|
|
order is named by its Kanban number, which Tiny keeps; the length is the
|
|
one billed."""
|
|
count = len(job['snapshot']['items'])
|
|
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
|
|
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
|
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
|
|
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
|
|
# A mirrored artwork (UV only) is named on the sheet, for the room to see
|
|
# before printing (Dropstar, 2026-10-23).
|
|
if any(source.get('mirrored') for source in item['production']['sources']):
|
|
fields.append('ESPELHADO')
|
|
return ' · '.join(fields)
|
|
|
|
|
|
def produce(storage, job, item, uploads):
|
|
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
|
|
name)], evidence); the caller removes the folder."""
|
|
for upload_id in item['uploads']:
|
|
row = uploads.get(upload_id)
|
|
if not row or row['scan_state'] != 'clean':
|
|
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
|
|
if row['purged_at'] or row['expired']:
|
|
raise Unsupported('um arquivo original passou do prazo de guarda')
|
|
output = tempfile.mkdtemp(prefix='print-')
|
|
try:
|
|
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
|
|
files = {}
|
|
for index, upload_id in enumerate(item['uploads']):
|
|
local = os.path.join(scratch, f'source-{index}')
|
|
storage.fetch(uploads[upload_id]['object_key'], local)
|
|
files[index] = (local, uploads[upload_id]['name'])
|
|
parts, detail = render(item, files, output, file_prefix(job['number'], job['item_index']),
|
|
footer=footer(job, item), tiles=True)
|
|
except BaseException:
|
|
shutil.rmtree(output, ignore_errors=True)
|
|
raise
|
|
return output, parts, detail
|
|
|
|
|
|
def finish(job, status, detail):
|
|
with connect() as c:
|
|
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
|
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
|
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
|
|
|
|
|
|
def render_loop(storage):
|
|
while True:
|
|
try:
|
|
if render_one(storage):
|
|
continue
|
|
except Exception:
|
|
logging.exception('Print render worker tick failed')
|
|
time.sleep(2)
|