upload_limits_test sent a 60 px PNG recorded at 300 DPI (0,5 cm) as a ready
sheet and site_admin_test a 2400 px one (20,3 cm) described as a 57 cm sheet;
the 57 cm rule (7111995) refused both, as it should. Without pHYs they are
stretched to the film, which is what both tests are about. All 32
integration suites pass on the local stack.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
6.9 KiB
Python
139 lines
6.9 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,
|
|
'sources': [{'upload_id': uid, 'kind': 'sheet', 'width_cm': 0.5, 'length_cm': 0.25,
|
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
|
'measurement': 'file'} for uid in uploads],
|
|
'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 0,
|
|
'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()
|