#!/usr/bin/env python3 """Python 3.10+ stdlib example. POST spends API credits; GET polling does not. Persist ARTWORK_IDEMPOTENCY_KEY with the original bytes/dimensions before running. Direct admission remains chargeable. For confirmed PDF totals use POST /quote and paired confirmation headers from quickstart.md; the dashboard does this. Run: python3 submit.py /local/artwork.png 254 127 mm Optional --curl uses curl transport with this same bounded retry policy. """ import email.utils import http.client import json import math import os from pathlib import Path import re import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request import uuid class Stop(Exception): pass class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None def main(): args = sys.argv[1:] use_curl = bool(args and args[0] == '--curl') if use_curl: args.pop(0) if len(args) != 4: raise Stop('Usage: submit.py [--curl] LOCAL_FILE WIDTH HEIGHT in|mm') file, width, height, unit = args key = os.environ.get('ARTWORK_API_KEY', '') idem = os.environ.get('ARTWORK_IDEMPOTENCY_KEY', '') base = os.environ.get('ARTWORK_API_BASE_URL', '').rstrip('/') parsed = urllib.parse.urlsplit(base) if not key or not re.fullmatch(r'[!-~]{1,200}', idem) or not re.fullmatch(r'[!-~]+', key): raise Stop('Set API key and a persisted owner-generated idempotency key in the environment.') if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path or not parsed.hostname: raise Stop('Base URL must be an HTTPS origin, without credentials, path or query.') if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('127.0.0.1', 'localhost', '::1')): raise Stop('HTTPS required; HTTP allowed only for a local test fixture.') if unit not in ('in', 'mm') or not all(math.isfinite(float(v)) and float(v) > 0 for v in (width, height)): raise Stop('Use finite positive physical dimensions and in or mm.') raw = Path(file).read_bytes() if not 0 < len(raw) <= 25 * 1024 * 1024: raise Stop('File must be nonempty and at most 25 MiB.') boundary = 'artwork-' + uuid.uuid4().hex body = b'' for name, value in (('width', width), ('height', height), ('unit', unit)): body += f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() body += f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="artwork"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + raw + f'\r\n--{boundary}--\r\n'.encode() deadline = time.monotonic() + 180 opener = urllib.request.build_opener(NoRedirect) def pause(seconds): if not math.isfinite(seconds) or seconds < 0 or time.monotonic() + seconds >= deadline: raise Stop('Retry budget exhausted. Preserve the original idempotency key and inputs; check dashboard before retrying.') time.sleep(seconds) def request(method, route): if not re.fullmatch(r'/api/v1/artwork-checks(?:/[0-9a-fA-F-]{36})?', route): raise Stop('Unexpected report route; refusing to forward credentials.') for attempt in range(5): remaining = deadline - time.monotonic() if remaining <= 0: raise Stop('Time budget exhausted; preserve original key and inputs.') headers = {'Authorization': 'Bearer ' + key, 'Accept': 'application/json'} if method == 'POST': headers.update({'Idempotency-Key': idem, 'Content-Type': 'multipart/form-data; boundary=' + boundary}) status, response_headers, data = 0, {}, b'' try: if use_curl: # Secrets go over stdin, not argv; private temp files are cleaned. with tempfile.TemporaryDirectory() as folder: payload, head = Path(folder) / 'payload', Path(folder) / 'headers' payload.write_bytes(body) cmd = ['curl', '--silent', '--max-time', str(min(20, remaining)), '--request', method, '--header', '@-', '--dump-header', str(head), '--write-out', '\n%{http_code}', base + route] if method == 'POST': cmd += ['--data-binary', '@' + str(payload)] result = subprocess.run(cmd, input=''.join(f'{k}: {v}\n' for k, v in headers.items()).encode(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=min(21, remaining + 1)) if result.returncode: raise OSError() data, code = result.stdout.rsplit(b'\n', 1) status = int(code) # read_text normalizes CRLF/LF. Skip interim/proxy blocks # and trailers: only a matching final status starts headers. for block in head.read_text().split('\n\n'): status_line, _, fields = block.partition('\n') if re.fullmatch(rf'HTTP/\S+ {status}(?: .*)?', status_line): response_headers = email.message_from_string(fields) else: req = urllib.request.Request(base + route, data=body if method == 'POST' else None, headers=headers, method=method) try: response = opener.open(req, timeout=min(20, remaining)) except urllib.error.HTTPError as error: response = error with response: status, response_headers, data = int(response.status or 0), response.headers, response.read(2 * 1024 * 1024) except (OSError, http.client.HTTPException, subprocess.SubprocessError): pass # Ambiguous response loss: retry ONLY identical POST/key or this GET. if 200 <= status < 300: try: return json.loads(data) except (ValueError, UnicodeError): status = 0 # Incomplete success body: ambiguous, same-key retry. if status not in (0, 429, 503): # No raw error text, credentials, signed media URLs or upload data in logs. request_id = '' try: candidate = json.loads(data).get('request_id', '') request_id = str(uuid.UUID(candidate)) except (ValueError, TypeError, AttributeError): pass raise Stop(f'HTTP {status}; stop and resolve before retrying. Request ID: {request_id}') if attempt == 4: raise Stop('Retry attempts exhausted. Keep original key/inputs; inspect dashboard. No automatic purchase or new submission.') wait = min(2 ** attempt, 8) retry_after = response_headers.get('Retry-After') if retry_after: try: wait = max(wait, float(retry_after)) except ValueError: wait = max(wait, email.utils.parsedate_to_datetime(retry_after).timestamp() - time.time()) pause(wait) raise Stop('Retry budget exhausted.') accepted = request('POST', '/api/v1/artwork-checks') job_id = str(uuid.UUID(accepted['id'])) print('Check:', job_id) route = '/api/v1/artwork-checks/' + job_id for poll in range(12): detail = request('GET', route) status = detail.get('processing_status') if status == 'completed': readiness = (detail.get('report') or {}).get('readiness') print('completed', readiness if readiness in ('no_flags', 'issues_found', 'inconclusive') else 'report unavailable') return if status == 'failed': raise Stop('Check failed; stop polling. Inspect dashboard reservation status; do not resubmit automatically.') if status not in ('queued', 'running'): raise Stop('Unexpected status; inspect dashboard without creating another check.') if poll < 11: pause(min(2 ** poll, 8)) raise Stop('Polling budget exhausted. Resume GET for this check; never create a new key to poll.') if __name__ == '__main__': try: main() except Stop as error: print(str(error), file=sys.stderr) sys.exit(1) except Exception: print('Example stopped safely. Preserve key and original inputs; check dashboard. No raw errors logged.', file=sys.stderr) sys.exit(1)