feat: the proof card, machine pull and print file corrections (Dropstar, 05/11)
The proof card owns its final PNG, keeps its parent locked until the seller answers, enters the queue first, and shares one machine with the parent. The board no longer assigns a machine at payment; the puller records it. A stalled print file times out with a card warning and a retry, finished orders sort by completion, and finals are stored as PNG. The original download carries the order number (items 0.1, 0.4 to 0.7 and 0.9).
This commit is contained in:
@@ -17,10 +17,12 @@ band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
|
||||
is prepared by hand from the original.
|
||||
"""
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from queue import Empty
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -38,7 +40,8 @@ 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)
|
||||
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
|
||||
CLAIM_TIMEOUT = timedelta(minutes=18)
|
||||
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.
|
||||
@@ -55,9 +58,10 @@ def queue(c, order_id, items, only_missing=False):
|
||||
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))
|
||||
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
|
||||
WHERE dtf_local.print_files.status IN ('failed','manual') OR
|
||||
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''',
|
||||
(uuid4(), order_id, index, CLAIM_TIMEOUT))
|
||||
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))
|
||||
@@ -67,7 +71,43 @@ 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()
|
||||
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
|
||||
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
||||
|
||||
|
||||
def _render_child(result_queue, job, item, uploads):
|
||||
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
|
||||
from .adapters import LocalS3Storage
|
||||
try:
|
||||
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
|
||||
except Unsupported as reason:
|
||||
result_queue.put(('manual', str(reason)))
|
||||
except BaseException as exc:
|
||||
logging.exception('Print file generation failed')
|
||||
result_queue.put(('error', type(exc).__name__))
|
||||
|
||||
|
||||
def render_with_timeout(job, item, uploads):
|
||||
ctx = multiprocessing.get_context('spawn')
|
||||
result_queue = ctx.Queue()
|
||||
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
|
||||
process.start()
|
||||
try:
|
||||
process.join(RENDER_SECONDS)
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
return 'timeout', None
|
||||
try:
|
||||
return result_queue.get(timeout=5)
|
||||
except Empty:
|
||||
return 'error', f'processo encerrou com código {process.exitcode}'
|
||||
finally:
|
||||
result_queue.close()
|
||||
result_queue.join_thread()
|
||||
|
||||
|
||||
def render_one(storage):
|
||||
@@ -75,8 +115,10 @@ def render_one(storage):
|
||||
job = claim(c)
|
||||
if not job:
|
||||
return False
|
||||
token = uuid4()
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
||||
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
|
||||
job['claim_token'] = token
|
||||
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)''',
|
||||
@@ -90,16 +132,19 @@ def render_one(storage):
|
||||
'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)})
|
||||
outcome, result = render_with_timeout(job, item, by_id)
|
||||
if outcome == 'manual':
|
||||
finish(job, 'manual', {'reason': result})
|
||||
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')
|
||||
if outcome == 'timeout':
|
||||
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
|
||||
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||
return True
|
||||
if outcome == 'error':
|
||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
||||
finish(job, 'failed' if final else 'pending', {'error': result,
|
||||
'reason': 'A geração falhou. Gere de novo.' if final else ''})
|
||||
return True
|
||||
scratch, parts, detail = result
|
||||
stored = []
|
||||
@@ -120,18 +165,30 @@ def render_one(storage):
|
||||
for part, (uid, _, size, _) in zip(detail['parts'], stored):
|
||||
part.update(upload_id=str(uid), size=size)
|
||||
with connect() as c:
|
||||
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
|
||||
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
|
||||
if not current:
|
||||
return True
|
||||
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']))
|
||||
finished_at=now(),claim_token=NULL,claimed_at=NULL 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))
|
||||
if job['snapshot'].get('proof_of'):
|
||||
c.execute('''UPDATE dtf_local.order_files SET active=false
|
||||
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
|
||||
(job['order_id'], job['item_index']))
|
||||
c.execute('''INSERT INTO dtf_local.order_files
|
||||
(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
|
||||
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
|
||||
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
|
||||
return True
|
||||
|
||||
@@ -162,8 +219,8 @@ def footer(job, item):
|
||||
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
|
||||
proof_of = job['snapshot'].get('proof_of')
|
||||
if proof_of:
|
||||
return ' · '.join(['DROPSTAR', f'Prova do pedido {purchase_order(proof_of)}',
|
||||
f'Item {job["item_index"] + 1}/{count}', day])
|
||||
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
|
||||
f'Classe {item.get("stroke_class") or "C3"}', day])
|
||||
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
|
||||
@@ -193,8 +250,8 @@ def produce(storage, job, item, uploads):
|
||||
storage.fetch(uploads[upload_id]['object_key'], local)
|
||||
files[index] = (local, uploads[upload_id]['name'])
|
||||
proof_of = job['snapshot'].get('proof_of')
|
||||
# A proof card's file: the first 30 cm, DTF-N-item-1-prova.png (app/proof.py).
|
||||
prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of
|
||||
# The child owns its final file; the class names its proof.
|
||||
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
|
||||
else file_prefix(job['number'], job['item_index']))
|
||||
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
|
||||
limit_cm=PROOF_SHEET_CM if proof_of else None)
|
||||
@@ -208,7 +265,8 @@ 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']))
|
||||
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
|
||||
(status, Jsonb(detail), status, job['id'], job['claim_token']))
|
||||
|
||||
|
||||
def render_loop(storage):
|
||||
|
||||
Reference in New Issue
Block a user