Merge render limit per part (order #20)
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m29s
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m29s
This commit is contained in:
@@ -173,8 +173,8 @@ def with_print_files(c, orders):
|
||||
ids = [o['id'] for o in orders]
|
||||
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at,
|
||||
p.created_at,
|
||||
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out,
|
||||
p.claimed_at+%s AS timeout_at,u.name
|
||||
(p.status='rendering' AND COALESCE(p.deadline_at,p.claimed_at+%s)<now()) AS timed_out,
|
||||
COALESCE(p.deadline_at,p.claimed_at+%s) AS timeout_at,u.name
|
||||
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
|
||||
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
|
||||
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']
|
||||
|
||||
3
app/migrations/202611121500_print-deadline.sql
Normal file
3
app/migrations/202611121500_print-deadline.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
-- A print file's render limit grows with its film (RENDER_SECONDS per 15 m
|
||||
-- part, app/printjobs.py): each claim records when it counts as abandoned.
|
||||
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS deadline_at timestamptz;
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
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.
|
||||
lock or a database connection. A claim past its deadline (the render limit
|
||||
plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) 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
|
||||
@@ -36,21 +37,36 @@ from .cart_pricing import needs_designer
|
||||
from .core.auth import audit
|
||||
from .core.db import connect
|
||||
from .printfile import Unsupported
|
||||
from .printpng import render
|
||||
from .printpng import part_cuts, render
|
||||
from .proof import PROOF_SHEET_CM
|
||||
from .tiny import purchase_order
|
||||
|
||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||
|
||||
# A 15 m part takes minutes to write; a long film, several parts.
|
||||
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
|
||||
CLAIM_TIMEOUT = timedelta(minutes=18)
|
||||
# A 15 m part takes about 7 min to write on a fast core; a long film, several
|
||||
# parts. The limit is per part: order #20's 23.6 m film (2026-11-12) ran past a
|
||||
# single 15 min limit for the whole film.
|
||||
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '1200'))
|
||||
CLAIM_MARGIN = timedelta(minutes=3)
|
||||
CLAIM_TIMEOUT = timedelta(seconds=RENDER_SECONDS) + CLAIM_MARGIN
|
||||
# A claim is stale once past its deadline.
|
||||
STALE = 'COALESCE({p}.deadline_at, {p}.claimed_at + %s) < now()'
|
||||
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 render_seconds(item):
|
||||
"""The render limit of one item: RENDER_SECONDS for each part of its film."""
|
||||
production = item.get('production') or {}
|
||||
try:
|
||||
parts = len(part_cuts(production)) - 1 if production.get('placements') else 1
|
||||
except (KeyError, TypeError, ValueError, ArithmeticError):
|
||||
parts = 1
|
||||
return RENDER_SECONDS * max(1, parts)
|
||||
|
||||
|
||||
def generated_identity(order_id):
|
||||
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
|
||||
|
||||
@@ -93,7 +109,8 @@ def queue(c, order_id, items, only_missing=False):
|
||||
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||
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)''',
|
||||
(dtf_local.print_files.status='rendering' AND '''
|
||||
+ STALE.format(p='dtf_local.print_files') + ')',
|
||||
(uuid4(), order_id, index, CLAIM_TIMEOUT))
|
||||
else:
|
||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||
@@ -103,7 +120,7 @@ def queue(c, order_id, items, only_missing=False):
|
||||
def claim(c):
|
||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, 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)
|
||||
WHERE p.status='pending' OR (p.status='rendering' AND ''' + STALE.format(p='p') + ''')
|
||||
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()
|
||||
|
||||
@@ -120,13 +137,13 @@ def _render_child(result_queue, job, item, uploads):
|
||||
result_queue.put(('error', type(exc).__name__))
|
||||
|
||||
|
||||
def render_with_timeout(job, item, uploads):
|
||||
def render_with_timeout(job, item, uploads, seconds=RENDER_SECONDS):
|
||||
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)
|
||||
process.join(seconds)
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(5)
|
||||
@@ -149,10 +166,12 @@ def render_one(storage):
|
||||
if not job:
|
||||
return False
|
||||
token = uuid4()
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
|
||||
job['claim_token'] = token
|
||||
item = job['snapshot']['items'][job['item_index']]
|
||||
seconds = render_seconds(item)
|
||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||
deadline_at=now()+%s, attempts=attempts+1,claim_token=%s WHERE id=%s''',
|
||||
(timedelta(seconds=seconds) + CLAIM_MARGIN, token, job['id']))
|
||||
job['claim_token'] = token
|
||||
source_ids = [UUID(u) for u in item['uploads']]
|
||||
# A format such as CDR needs a human to prepare the full-size final on
|
||||
# the parent. The child still generates its own 15 cm proof from that PNG,
|
||||
@@ -195,17 +214,23 @@ 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
|
||||
outcome, result = render_with_timeout(job, item, by_id)
|
||||
outcome, result = render_with_timeout(job, item, by_id, seconds)
|
||||
if outcome == 'manual':
|
||||
finish(job, 'manual', {'reason': result})
|
||||
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
|
||||
return True
|
||||
if outcome == 'timeout':
|
||||
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
|
||||
finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
|
||||
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||
# The card says so too, but Sentry (and the Vigia) hear of it first.
|
||||
logging.error('Print file generation timed out after %s min: order #%s item %s',
|
||||
seconds // 60, job['number'], job['item_index'] + 1)
|
||||
return True
|
||||
if outcome == 'error':
|
||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||
if final:
|
||||
logging.error('Print file generation failed: order #%s item %s: %s',
|
||||
job['number'], job['item_index'] + 1, result)
|
||||
finish(job, 'failed' if final else 'pending', {'error': result,
|
||||
'reason': 'A geração falhou. Gere de novo.' if final else ''})
|
||||
return True
|
||||
|
||||
@@ -38,5 +38,20 @@ class ProofCutTests(unittest.TestCase):
|
||||
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
|
||||
|
||||
|
||||
class RenderLimitTests(unittest.TestCase):
|
||||
"""Order #20 (2026-11-12): a 23.6 m film ran past one 15 min limit."""
|
||||
|
||||
def test_the_limit_grows_with_the_parts(self):
|
||||
from app.printjobs import RENDER_SECONDS, render_seconds
|
||||
|
||||
def film(height):
|
||||
return {'production': {'height_cm': height, 'placements': [
|
||||
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
|
||||
self.assertEqual(render_seconds(film(800)), RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds(film(2359.2)), 2 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds(film(4600)), 4 * RENDER_SECONDS)
|
||||
self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user