"""Загрузка больших вложений частями (чанками) для сайта, приложения и мини-аппа. Зачем: прокси Vercel (/api/relay/*), через который ходят сайт и приложение, отвечает 413 на телах больше ~4.5 МБ, а файл в base64 это +33%. Раньше всё, что больше ~2.7 МБ, не отправлялось. Теперь клиент режет файл на куски по CHUNK_SIZE (2 МиБ, это сырые байты без base64) и отправляет их по одному, а в /api/file_b64 вместо поля data передаёт upload_id. Лимиты вложений (20 МБ на файл, 30 МБ на сообщение) не менялись. Протокол (везде Authorization: Bearer ): 1. POST /api/upload/init JSON {name, type?, size} -> {ok, upload_id, chunk_size, chunks} 2. POST /api/upload// тело = сырые байты куска -> {ok, received, chunks} (index с 0; каждый кусок ровно chunk_size байт, кроме последнего; повторная отправка куска допустима) 3. POST /api/upload//complete (тело не нужно) -> {ok, size} 4. POST /api/file_b64 {files:[{name, type, upload_id}], ...} (можно мешать с inline-файлами {data}) 5. POST /api/upload//cancel освободить место раньше TTL Хранение: временные файлы на диске (tempfile), метаданные в памяти процесса. Незавершённые и неиспользованные загрузки удаляются через TTL_SECONDS; при старте процесса каталог очищается. Один процесс сервера: при переходе на несколько экземпляров (пункт 3.x роадмапа) хранилище нужно вынести в общее место. Загрузка принадлежит пользователю: чужой upload_id не читается и не отменяется (ответ как при несуществующем). """ import os import re import time import math import shutil import secrets import tempfile import threading from flask import Blueprint, request, jsonify from runtime import is_privileged, MAX_ATTACHMENT_BYTES from session_auth import _require_authed_user_id uploads_bp = Blueprint("uploads", __name__) CHUNK_SIZE = 2 * 1024 * 1024 # сырых байт на кусок: после запаса остаётся далеко под лимитом прокси (~4.5 МБ) TTL_SECONDS = 30 * 60 # неиспользованная загрузка живёт 30 минут MAX_ACTIVE_PER_USER = 8 # одновременных загрузок на пользователя MAX_PENDING_BYTES_PER_USER = 80 * 1024 * 1024 MAX_PENDING_BYTES_TOTAL = 400 * 1024 * 1024 # потолок диска под загрузки на весь сервер _ROOT = os.path.join(tempfile.gettempdir(), "elyon_uploads") _lock = threading.RLock() _uploads: dict = {} # upload_id -> meta _started = False # ── Служебное ───────────────────────────────────────────────────────────── def _udir(upload_id: str) -> str: return os.path.join(_ROOT, upload_id) def _drop(upload_id: str) -> None: """Удаляет загрузку из реестра и с диска (вызывать под _lock).""" _uploads.pop(upload_id, None) shutil.rmtree(_udir(upload_id), ignore_errors=True) def cleanup_expired(now: float | None = None) -> int: now = time.time() if now is None else now with _lock: dead = [uid for uid, m in _uploads.items() if now - m["touched"] > TTL_SECONDS] for uid in dead: _drop(uid) return len(dead) def _janitor() -> None: while True: time.sleep(300) try: cleanup_expired() except Exception as e: print(f"[uploads] cleanup: {e}", flush=True) def _ensure_started() -> None: global _started with _lock: if _started: return _started = True shutil.rmtree(_ROOT, ignore_errors=True) # хвосты предыдущего процесса не нужны os.makedirs(_ROOT, exist_ok=True) threading.Thread(target=_janitor, daemon=True).start() def _pending_bytes(user_id=None) -> int: return sum(m["size"] for m in _uploads.values() if user_id is None or m["user_id"] == user_id) def _get_owned(upload_id: str, user_id: int): m = _uploads.get(upload_id) return m if m and m["user_id"] == user_id else None def _err(msg: str, status: int, code: str): return jsonify({"ok": False, "error": msg, "code": code}), status def _gate(): """Авторизация + техработы. Возвращает (user_id, None) или (None, response).""" uid, err = _require_authed_user_id() if err: return None, err from database import is_maintenance if is_maintenance() and not is_privileged(uid): return None, (jsonify({"error": "Maintenance in progress"}), 503) return uid, None # ── Использование из /api/file_b64 ──────────────────────────────────────── class UploadError(Exception): def __init__(self, message: str, status: int, code: str): super().__init__(message) self.message, self.status, self.code = message, status, code def read_upload(user_id: int, upload_id: str) -> bytes: """Собирает завершённую загрузку в байты. Загрузка НЕ удаляется (если ИИ ответит ошибкой, клиент повторит с тем же upload_id); после успешного ответа вызывающий делает discard_upload.""" if not isinstance(upload_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{8,64}", upload_id): raise UploadError("Bad upload id", 400, "bad_upload_id") with _lock: m = _get_owned(upload_id, user_id) if not m: raise UploadError("Upload not found or expired", 404, "upload_not_found") if not m["complete"]: raise UploadError("Upload is not complete", 409, "upload_incomplete") m["touched"] = time.time() parts = [] for i in range(m["chunks"]): with open(os.path.join(_udir(upload_id), f"{i:05d}.part"), "rb") as f: parts.append(f.read()) blob = b"".join(parts) if len(blob) != m["size"]: raise UploadError("Upload is corrupted", 409, "upload_corrupted") return blob def discard_upload(user_id: int, upload_id: str) -> None: with _lock: if _get_owned(upload_id, user_id): _drop(upload_id) # ── Эндпоинты ───────────────────────────────────────────────────────────── @uploads_bp.route("/api/upload/init", methods=["POST", "OPTIONS"]) def api_upload_init(): if request.method == "OPTIONS": return "", 204 uid, err = _gate() if err: return err data = request.get_json(silent=True) if not isinstance(data, dict): return _err("JSON body required", 400, "bad_request") name = str(data.get("name") or "file").strip()[:200] or "file" mime = str(data.get("type") or "")[:100] size = data.get("size") if isinstance(size, bool) or not isinstance(size, int) or size <= 0: return _err("'size' must be a positive integer (bytes)", 400, "bad_size") if size > MAX_ATTACHMENT_BYTES: return _err(f"File too large (max {MAX_ATTACHMENT_BYTES // (1024 * 1024)} MB): {name}", 413, "file_too_large") _ensure_started() cleanup_expired() with _lock: mine = [m for m in _uploads.values() if m["user_id"] == uid] if len(mine) >= MAX_ACTIVE_PER_USER or _pending_bytes(uid) + size > MAX_PENDING_BYTES_PER_USER: return _err("Too many unfinished uploads, try again in a few minutes", 429, "too_many_uploads") if _pending_bytes() + size > MAX_PENDING_BYTES_TOTAL: return _err("Server is busy, try again in a few minutes", 503, "server_busy") upload_id = secrets.token_urlsafe(16) chunks = math.ceil(size / CHUNK_SIZE) now = time.time() _uploads[upload_id] = {"user_id": uid, "name": name, "type": mime, "size": size, "chunks": chunks, "received": set(), "complete": False, "created": now, "touched": now} os.makedirs(_udir(upload_id), exist_ok=True) return jsonify({"ok": True, "upload_id": upload_id, "chunk_size": CHUNK_SIZE, "chunks": chunks}) @uploads_bp.route("/api/upload//", methods=["POST", "OPTIONS"]) def api_upload_chunk(upload_id, index): if request.method == "OPTIONS": return "", 204 uid, err = _gate() if err: return err with _lock: m = _get_owned(upload_id, uid) if not m: return _err("Upload not found or expired", 404, "upload_not_found") if m["complete"]: return _err("Upload is already complete", 409, "upload_complete") if not 0 <= index < m["chunks"]: return _err("Chunk index out of range", 400, "bad_index") expected = CHUNK_SIZE if index < m["chunks"] - 1 else m["size"] - CHUNK_SIZE * (m["chunks"] - 1) if request.content_length is not None and request.content_length != expected: return _err(f"Chunk must be exactly {expected} bytes", 400, "bad_chunk_size") body = request.get_data() if len(body) != expected: return _err(f"Chunk must be exactly {expected} bytes", 400, "bad_chunk_size") path = os.path.join(_udir(upload_id), f"{index:05d}.part") tmp = path + ".tmp" with open(tmp, "wb") as f: f.write(body) with _lock: m = _get_owned(upload_id, uid) # могли удалить, пока писали if not m: try: os.remove(tmp) except OSError: pass return _err("Upload not found or expired", 404, "upload_not_found") os.replace(tmp, path) m["received"].add(index) m["touched"] = time.time() received = len(m["received"]) return jsonify({"ok": True, "received": received, "chunks": m["chunks"]}) @uploads_bp.route("/api/upload//complete", methods=["POST", "OPTIONS"]) def api_upload_complete(upload_id): if request.method == "OPTIONS": return "", 204 uid, err = _gate() if err: return err with _lock: m = _get_owned(upload_id, uid) if not m: return _err("Upload not found or expired", 404, "upload_not_found") missing = [i for i in range(m["chunks"]) if i not in m["received"]] if missing: return jsonify({"ok": False, "error": "Some chunks are missing", "code": "chunks_missing", "missing": missing[:50]}), 409 m["complete"] = True m["touched"] = time.time() return jsonify({"ok": True, "size": m["size"]}) @uploads_bp.route("/api/upload//cancel", methods=["POST", "OPTIONS"]) def api_upload_cancel(upload_id): if request.method == "OPTIONS": return "", 204 uid, err = _require_authed_user_id() if err: return err discard_upload(uid, upload_id) return jsonify({"ok": True})