Files
dtf-system/tests/upload_limits_test.py
Cauê Faleiros 41126a42fd
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 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m43s
feat: a ready sheet prints at its real size, centred on the film, with the customer's confirmation (Marcus, 2026-12-02)
Replaces 7111995 (only 57,0 cm entered; a whole order of 56,5-56,9 cm
sheets was refused, DTF-WEB-2C). Marcus's rules, for Arquivo por metro,
Premium (57 cm) and UV (27 cm):
1. A known width up to the film (PNG recording 200 DPI or more, or a PDF
   page) enters at its real size, centred, billed by its real height.
2. Narrower: his warning before the cart, confirmation required
   (Imprimir no tamanho real / Enviar outro arquivo); recorded in the
   Prumo report ("cliente confirmou folha de 35,8 cm no tamanho real") and
   shown in the cart and payment summaries.
3. Wider than the film: refused with his message.
4. Unknown width: taken as the film's, DPI from the pixels; 200 or more
   with a confirmation, under 200 refused with the artes avulsas hint.
Within 0,1 cm of the film counts as the film. The server checks it all
again at checkout (sheet_width_issue, centred placement, size_confirmed).

Also ops.stretched_sheets: the ready-sheet orders since 16/10 laid out
wider than their real width (number, real width, factor), for Marcus.
Contract: output/revisao/contrato-folha-real.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 09:51:38 -03:00

142 lines
7.1 KiB
Python

"""The upload limits: a 66-file cart fits, the per-source bucket still
refuses above its own limit (Marcus's bugs of 2026-11-11, B1), and a quote
takes up to 200 files per item (Sentry DTF-WEB-1).
Run against the local stack: python -m tests.upload_limits_test
"""
import io
import json
import os
import secrets
import time
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request
from uuid import UUID, uuid4
from fastapi import HTTPException
from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
from app.core import db
from app.core.auth import rate_limit
from tests.smoke_test import BASE, Client, upload_bytes, with_host
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
def without_dpi(data):
"""The fixture records 300 DPI: as a ready sheet it would be 0,5 cm wide and
refused (output/revisao/contrato-largura-folha.md). Without pHYs it is
stretched to the film, which is all the sheet-count limit needs."""
from PIL import Image
out = io.BytesIO()
Image.open(io.BytesIO(data)).save(out, 'PNG')
return out.getvalue()
SHEET_PNG = without_dpi(PNG)
TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.'
def item_with(uploads):
"""One ready-sheet item: one source per upload, stacked in a row, 8 mm
apart (models.SHEET_GAP_CM)."""
count = len(uploads)
step = 0.25 + 0.8
height = round(count * step - 0.8, 4)
return {
'mode': 'file', 'metres': round(height / 100, 4), 'grade': 100, 'uploads': uploads,
'production': {
'version': 3, 'film_width_cm': 57, 'height_cm': height,
# Measured by the customer (as a CDR's typed length): this test counts
# sheets; the real-size rule (contrato-folha-real.md) is not its business.
'sources': [{'upload_id': uid, 'kind': 'sheet', 'width_cm': 0.5, 'length_cm': 0.25,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'customer'} for uid in uploads],
# A sheet narrower than the film is centred on it.
'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 28.25,
'y_cm': round(index * step, 4), 'width_cm': 0.5, 'length_cm': 0.25,
'rotation_degrees': 0, 'mirrored': False} for index in range(count)]},
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
def run():
assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000)
client = Client()
scope = client.call('/session')['cart_scope']
try:
# A 66-file cart, with retries, fits in one session. Each reservation is
# cancelled so the pending-upload quota (unchanged) does not stop the test.
for index in range(70):
uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id']
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
# The per-source bucket, exercised directly with a small limit: 3000 real
# starts would only slow CI. A unique key keeps other suites out of it.
key = 'upload-start-ip-test-' + secrets.token_hex(8)
for _ in range(3):
rate_limit('upload-start-ip', key, 3, 900)
try:
rate_limit('upload-start-ip', key, 3, 900)
except HTTPException as error:
assert error.status_code == 429, error
assert error.headers.get('Retry-After') == '900', error.headers
else:
raise AssertionError('the per-source upload bucket accepted above its limit')
# DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start
# answers 429 with Retry-After 15, so the Site waits and retries alone.
assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30
# The gateway allows 20 requests a second with a burst of 100
# (infra/nginx.conf.template): after the starts above, a fast runner
# meets nginx's 429 before the API's (CI run 393). Let it refill.
time.sleep(6)
pending = []
for index in range(30):
pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id'])
burst = Request(BASE + '/api/uploads',
data=json.dumps({'name': 'PENDING-31.png', 'size': 1}).encode(),
headers=with_host({'Content-Type': 'application/json'}), method='POST')
try:
with client.opener.open(burst, timeout=30) as response:
raise AssertionError('the pending-upload cap accepted the 31st upload')
except HTTPError as error:
assert error.code == 429, error
assert error.headers.get('Retry-After') == '15', error.headers
assert json.load(error)['detail'] == 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.'
# DTF-WEB-14: reservations left by interrupted uploads, idle for 20
# minutes, no longer hold the cap; the next start goes through.
with db.connect() as c:
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 minutes' WHERE id=ANY(%s)",
([UUID(uid) for uid in pending],))
pending.append(client.call('/uploads', {'name': 'PENDING-AFTER-IDLE.png', 'size': 1})['id'])
for uid in pending:
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
# Sentry DTF-WEB-1: 66 sheets in one ready-sheet item is quoted and
# approved; the old cap of 20 refused it with a generic 422.
uploads = [upload_bytes(client, SHEET_PNG, name=f'SHEET66-{index}.png') for index in range(66)]
body = {'request_key': str(uuid4()), 'customer': {'name': 'Carrinho Grande',
'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'sheet66@example.test'},
'items': [item_with(uploads)], 'freight': {'service': 'pickup'}}
quote = client.call('/quotes', body)
assert quote['status'] == 'approved', quote
approved = client.call('/quotes/' + quote['id'])['approved']['items'][0]
assert (len(approved['uploads']), len(approved['production']['sources']),
len(approved['production']['placements'])) == (66, 66, 66), approved
# The old cap's message: one more file is refused with a readable text.
too_many = {**body, 'request_key': str(uuid4()),
'items': [{**item_with(uploads), 'uploads': [str(uuid4()) for _ in range(201)]}]}
detail = client.call('/quotes', too_many, expected=422)['detail']
messages = [entry.get('msg', '') for entry in detail if isinstance(entry, dict)]
assert any(TOO_MANY in message for message in messages), detail
print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit; '
'a 66-sheet item is quoted and 201 is refused with the readable message')
finally:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.quotes WHERE owner=%s', (UUID(scope),))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (UUID(scope),))
if __name__ == '__main__':
run()