diff --git a/apps/admin/services.py b/apps/admin/services.py index 0e38902..5dca580 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -1,6 +1,7 @@ import hashlib import os import time +import uuid from datetime import datetime, timedelta from typing import Any, Optional @@ -15,6 +16,7 @@ from core.config import refresh_settings from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret from apps.base.models import FileCodes, KeyValue from apps.base.utils import get_expire_info, get_file_path_name +from apps.base.quota import release_storage, reserve_storage from fastapi import HTTPException from core.settings import data_root from core.utils import get_now, hash_password, is_password_hashed @@ -1472,25 +1474,36 @@ class FileService: if not await local_file.exists(): raise HTTPException(status_code=404, detail="文件不存在") - text = await local_file.read() - expired_at, expired_count, used_count, code = await get_expire_info( - item.expire_value, item.expire_style - ) - path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(item) - - await self.file_storage.save_file(text, save_path) - - await FileCodes.create( - code=code, - prefix=prefix, - suffix=suffix, - uuid_file_name=uuid_file_name, - file_path=path, - size=local_file.size, - expired_at=expired_at, - expired_count=expired_count, - used_count=used_count, - ) + reservation_token = f"local:{uuid.uuid4().hex}" + await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600) + try: + text = await local_file.read() + expired_at, expired_count, used_count, code = await get_expire_info( + item.expire_value, item.expire_style + ) + path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name( + item + ) + await self.file_storage.save_file(text, save_path) + try: + await FileCodes.create( + code=code, + prefix=prefix, + suffix=suffix, + uuid_file_name=uuid_file_name, + file_path=path, + size=local_file.size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + ) + except Exception: + await self.file_storage.delete_file( + FileCodes(file_path=path, uuid_file_name=uuid_file_name) + ) + raise + finally: + await release_storage(reservation_token) return { "code": code, @@ -1512,6 +1525,7 @@ class ConfigService: "serverPort", "serverWorkers", "showAdminAddr", + "storageLimit", "uploadCount", "uploadMinute", "uploadSize", @@ -1576,6 +1590,12 @@ class ConfigService: ) next_config["adminSessionExpire"] = session_expire + if int(next_config.get("storageLimit", 0)) < 0: + raise HTTPException( + status_code=400, + detail="storageLimit 不能小于 0", + ) + if admin_password_changed: next_config["jwt_secret"] = generate_jwt_secret() diff --git a/apps/base/migrations/migrations_006.py b/apps/base/migrations/migrations_006.py new file mode 100644 index 0000000..5d37d3e --- /dev/null +++ b/apps/base/migrations/migrations_006.py @@ -0,0 +1,19 @@ +from tortoise import connections + + +async def migrate(): + conn = connections.get("default") + await conn.execute_script( + """ + CREATE TABLE IF NOT EXISTS storagereservation ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + token VARCHAR(64) NOT NULL UNIQUE, + size BIGINT NOT NULL, + expires_at TIMESTAMP NOT NULL + ); + CREATE UNIQUE INDEX IF NOT EXISTS idx_storagereservation_token + ON storagereservation (token); + CREATE INDEX IF NOT EXISTS idx_storagereservation_expires_at + ON storagereservation (expires_at); + """ + ) diff --git a/apps/base/models.py b/apps/base/models.py index 2d299c4..a43aa71 100644 --- a/apps/base/models.py +++ b/apps/base/models.py @@ -84,6 +84,15 @@ class PresignUploadSession(models.Model): return self.expires_at < await get_now() +class StorageReservation(models.Model): + """尚未写入 FileCodes 的上传容量预留。""" + + id = fields.IntField(pk=True) + token = fields.CharField(max_length=64, unique=True, index=True) + size = fields.BigIntField() + expires_at = fields.DatetimeField(index=True) + + file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes") upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk") key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue") diff --git a/apps/base/quota.py b/apps/base/quota.py new file mode 100644 index 0000000..4d38e79 --- /dev/null +++ b/apps/base/quota.py @@ -0,0 +1,81 @@ +import datetime + +from fastapi import HTTPException +from tortoise import connections + +from apps.base.models import FileCodes, StorageReservation +from core.settings import settings +from core.utils import get_now + + +def get_storage_limit() -> int: + try: + return max(0, int(getattr(settings, "storageLimit", 0))) + except (TypeError, ValueError): + return 0 + + +async def get_storage_usage() -> dict[str, int | None]: + now = await get_now() + used = await FileCodes.all().values_list("size", flat=True) + reserved = await StorageReservation.filter(expires_at__gt=now).values_list( + "size", flat=True + ) + limit = get_storage_limit() + used_bytes = sum(used) + reserved_bytes = sum(reserved) + return { + "limit": limit, + "used": used_bytes, + "reserved": reserved_bytes, + "available": max(0, limit - used_bytes - reserved_bytes) if limit else None, + } + + +async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None: + requested_size = max(0, int(size)) + limit = get_storage_limit() + if not limit or requested_size == 0: + return + + now = await get_now() + expires_at = now + datetime.timedelta(seconds=ttl_seconds) + conn = connections.get("default") + await StorageReservation.filter(token=token, expires_at__lte=now).delete() + existing = await StorageReservation.filter(token=token, expires_at__gt=now).first() + if existing: + if existing.size == requested_size: + return + raise HTTPException(status_code=409, detail="上传容量预留信息不一致") + + try: + affected, _ = await conn.execute_query( + """ + INSERT INTO storagereservation (token, size, expires_at) + SELECT ?, ?, ? + WHERE ( + COALESCE((SELECT SUM(size) FROM filecodes), 0) + + COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > ?), 0) + + ? + ) <= ? + """, + [token, requested_size, expires_at, now, requested_size, limit], + ) + except Exception: + concurrent = await StorageReservation.filter( + token=token, size=requested_size, expires_at__gt=now + ).exists() + if concurrent: + return + raise + if affected != 1: + concurrent = await StorageReservation.filter( + token=token, size=requested_size, expires_at__gt=now + ).exists() + if concurrent: + return + raise HTTPException(status_code=507, detail="存储空间已达到管理员设置的容量上限") + + +async def release_storage(token: str) -> None: + await StorageReservation.filter(token=token).delete() diff --git a/apps/base/views.py b/apps/base/views.py index 3433f57..d87a426 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -15,6 +15,7 @@ from tortoise.expressions import Case, F, Q, When from apps.admin.dependencies import share_required_login from apps.base.models import FileCodes, UploadChunk, PresignUploadSession +from apps.base.quota import release_storage, reserve_storage from apps.base.schemas import ( SelectFileModel, InitChunkUploadModel, @@ -155,18 +156,23 @@ async def share_text( if text_size > max_txt_size: raise HTTPException(status_code=403, detail="内容过多,建议采用文件形式") - expired_at, expired_count, used_count, code = await get_expire_info( - expire_value, expire_style - ) - await create_file_code( - code=code, - text=text, - expired_at=expired_at, - expired_count=expired_count, - used_count=used_count, - size=len(text), - prefix="Text", - ) + reservation_token = f"text:{uuid.uuid4().hex}" + await reserve_storage(reservation_token, text_size, ttl_seconds=300) + try: + expired_at, expired_count, used_count, code = await get_expire_info( + expire_value, expire_style + ) + await create_file_code( + code=code, + text=text, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + size=text_size, + prefix="Text", + ) + finally: + await release_storage(reservation_token) ip_limit["upload"].add_ip(ip) return APIResponse(detail={"code": code}) @@ -182,23 +188,36 @@ async def share_file( validate_file_type(file.filename or "", file.content_type) if expire_style not in settings.expireStyle: raise HTTPException(status_code=400, detail="过期时间类型错误") - expired_at, expired_count, used_count, code = await get_expire_info( - expire_value, expire_style - ) path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file) + reservation_token = f"file:{uuid.uuid4().hex}" + await reserve_storage(reservation_token, file_size, ttl_seconds=3600) file_storage: FileStorageInterface = storages[settings.file_storage]() - await file_storage.save_file(file, save_path) - await create_file_code( - code=code, - prefix=prefix, - suffix=suffix, - uuid_file_name=uuid_file_name, - file_path=path, - size=file_size, - expired_at=expired_at, - expired_count=expired_count, - used_count=used_count, - ) + try: + expired_at, expired_count, used_count, code = await get_expire_info( + expire_value, expire_style + ) + await file_storage.save_file(file, save_path) + await create_file_code( + code=code, + prefix=prefix, + suffix=suffix, + uuid_file_name=uuid_file_name, + file_path=path, + size=file_size, + expired_at=expired_at, + expired_count=expired_count, + used_count=used_count, + ) + except Exception: + try: + await file_storage.delete_file( + FileCodes(file_path=path, uuid_file_name=uuid_file_name) + ) + except Exception: + pass + raise + finally: + await release_storage(reservation_token) ip_limit["upload"].add_ip(ip) return APIResponse(detail={"code": code, "name": file.filename}) @@ -422,7 +441,16 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun if existing_session: if not existing_session.save_path: await UploadChunk.filter(upload_id=existing_session.upload_id).delete() + await release_storage(f"chunk:{existing_session.upload_id}") else: + await reserve_storage( + f"chunk:{existing_session.upload_id}", + existing_session.file_size, + ttl_seconds=max( + 1, int(getattr(settings, "chunk_expire_hours", 24)) + ) + * 3600, + ) uploaded_chunks = await UploadChunk.filter( upload_id=existing_session.upload_id, completed=True ).values_list("chunk_index", flat=True) @@ -438,17 +466,26 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun # 创建新的上传会话 upload_id = uuid.uuid4().hex - _, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id) - await UploadChunk.create( - upload_id=upload_id, - chunk_index=-1, - total_chunks=total_chunks, - file_size=data.file_size, - chunk_size=data.chunk_size, - chunk_hash=data.file_hash, - file_name=data.file_name, - save_path=save_path, + reservation_token = f"chunk:{upload_id}" + chunk_expire_seconds = max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600 + await reserve_storage( + reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds ) + _, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id) + try: + await UploadChunk.create( + upload_id=upload_id, + chunk_index=-1, + total_chunks=total_chunks, + file_size=data.file_size, + chunk_size=data.chunk_size, + chunk_hash=data.file_hash, + file_name=data.file_name, + save_path=save_path, + ) + except Exception: + await release_storage(reservation_token) + raise return APIResponse( detail={ "existed": False, @@ -473,6 +510,11 @@ async def upload_chunk( chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() if not chunk_info: raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + await reserve_storage( + f"chunk:{upload_id}", + chunk_info.file_size, + ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600, + ) # 检查分片索引有效性 if chunk_index < 0 or chunk_index >= chunk_info.total_chunks: @@ -561,6 +603,7 @@ async def cancel_upload(upload_id: str): # 清理数据库记录 await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") return APIResponse(detail={"message": "上传已取消"}) @@ -604,6 +647,11 @@ async def complete_upload( chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() if not chunk_info: raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + await reserve_storage( + f"chunk:{upload_id}", + chunk_info.file_size, + ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600, + ) storage = storages[settings.file_storage]() # 验证所有分片 @@ -623,6 +671,7 @@ async def complete_upload( except Exception: pass await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") max_size_mb = settings.uploadSize / (1024 * 1024) raise HTTPException( status_code=403, detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB" @@ -657,6 +706,7 @@ async def complete_upload( await storage.clean_chunks(upload_id, save_path) # 清理数据库中的分片记录 await UploadChunk.filter(upload_id=upload_id).delete() + await release_storage(f"chunk:{upload_id}") ip_limit["upload"].add_ip(ip) return APIResponse(detail={"code": code, "name": chunk_info.file_name}) except ValueError as e: @@ -695,6 +745,7 @@ async def _get_valid_session( raise HTTPException(404, "上传会话不存在") if await session.is_expired(): await session.delete() + await release_storage(f"presign:{upload_id}") raise HTTPException(404, "上传会话已过期") if expected_mode and session.mode != expected_mode: raise HTTPException(400, f"此会话不支持{expected_mode}模式") @@ -716,29 +767,34 @@ async def presign_upload_init( raise HTTPException(400, "过期时间类型错误") upload_id = uuid.uuid4().hex - path, _, _, filename, save_path = await FileUploadService.generate_file_path( - data.file_name, upload_id - ) - - storage: FileStorageInterface = storages[settings.file_storage]() - presigned_url = await storage.generate_presigned_upload_url( - save_path, PRESIGN_SESSION_EXPIRES - ) - - mode = "direct" if presigned_url else "proxy" - proxy_urls = build_proxy_upload_urls(upload_id) - upload_url = presigned_url or proxy_urls["proxy_upload_url"] - - await PresignUploadSession.create( - upload_id=upload_id, - file_name=filename, - file_size=data.file_size, - save_path=save_path, - mode=mode, - expire_value=data.expire_value, - expire_style=data.expire_style, - expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES), + reservation_token = f"presign:{upload_id}" + await reserve_storage( + reservation_token, data.file_size, ttl_seconds=PRESIGN_SESSION_EXPIRES ) + try: + path, _, _, filename, save_path = await FileUploadService.generate_file_path( + data.file_name, upload_id + ) + storage: FileStorageInterface = storages[settings.file_storage]() + presigned_url = await storage.generate_presigned_upload_url( + save_path, PRESIGN_SESSION_EXPIRES + ) + mode = "direct" if presigned_url else "proxy" + proxy_urls = build_proxy_upload_urls(upload_id) + upload_url = presigned_url or proxy_urls["proxy_upload_url"] + await PresignUploadSession.create( + upload_id=upload_id, + file_name=filename, + file_size=data.file_size, + save_path=save_path, + mode=mode, + expire_value=data.expire_value, + expire_style=data.expire_style, + expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES), + ) + except Exception: + await release_storage(reservation_token) + raise ip_limit["upload"].add_ip(ip) detail = { @@ -763,6 +819,11 @@ async def presign_upload_proxy( ): """代理模式上传,服务器转存到存储后端""" session = await _get_valid_session(upload_id, expected_mode="proxy") + await reserve_storage( + f"presign:{upload_id}", + session.file_size, + ttl_seconds=PRESIGN_SESSION_EXPIRES, + ) file_size = await validate_file_size(file, settings.uploadSize) if abs(file_size - session.file_size) > 1024: @@ -774,15 +835,28 @@ async def presign_upload_proxy( except Exception as e: raise HTTPException(500, f"文件保存失败: {str(e)}") - code = await FileUploadService.create_file_record( - session.file_name, - file_size, - os.path.dirname(session.save_path), - session.expire_value, - session.expire_style, - ) + try: + code = await FileUploadService.create_file_record( + session.file_name, + file_size, + os.path.dirname(session.save_path), + session.expire_value, + session.expire_style, + ) + except Exception: + try: + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception: + pass + raise await session.delete() + await release_storage(f"presign:{upload_id}") ip_limit["upload"].add_ip(ip) return APIResponse(detail={"code": code, "name": session.file_name}) @@ -793,20 +867,53 @@ async def presign_upload_proxy( async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])): """直传确认,客户端完成S3直传后调用获取分享码""" session = await _get_valid_session(upload_id, expected_mode="direct") + try: + await reserve_storage( + f"presign:{upload_id}", + session.file_size, + ttl_seconds=PRESIGN_SESSION_EXPIRES, + ) + except HTTPException: + storage: FileStorageInterface = storages[settings.file_storage]() + try: + if await storage.file_exists(session.save_path): + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + finally: + await session.delete() + await release_storage(f"presign:{upload_id}") + raise storage: FileStorageInterface = storages[settings.file_storage]() if not await storage.file_exists(session.save_path): raise HTTPException(404, "文件未上传或上传失败") - code = await FileUploadService.create_file_record( - session.file_name, - session.file_size, - os.path.dirname(session.save_path), - session.expire_value, - session.expire_style, - ) + try: + code = await FileUploadService.create_file_record( + session.file_name, + session.file_size, + os.path.dirname(session.save_path), + session.expire_value, + session.expire_style, + ) + except Exception: + try: + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception: + pass + raise await session.delete() + await release_storage(f"presign:{upload_id}") ip_limit["upload"].add_ip(ip) return APIResponse(detail={"code": code, "name": session.file_name}) @@ -853,4 +960,5 @@ async def presign_upload_cancel(upload_id: str): pass await session.delete() + await release_storage(f"presign:{upload_id}") return APIResponse(detail={"message": "上传会话已取消"}) diff --git a/core/settings.py b/core/settings.py index 36a2405..ef943e8 100644 --- a/core/settings.py +++ b/core/settings.py @@ -17,6 +17,7 @@ if not data_root.exists(): DEFAULT_CONFIG = { "file_storage": "local", "storage_path": "", + "storageLimit": 0, "name": "文件快递柜 - FileCodeBox", "description": "开箱即用的文件快传系统", "notify_title": "系统通知", diff --git a/core/tasks.py b/core/tasks.py index bc4aa7b..f3da97f 100644 --- a/core/tasks.py +++ b/core/tasks.py @@ -9,7 +9,12 @@ import os from tortoise.expressions import Q -from apps.base.models import FileCodes, UploadChunk +from apps.base.models import ( + FileCodes, + PresignUploadSession, + StorageReservation, + UploadChunk, +) from apps.base.utils import ip_limit, get_chunk_file_path_name from core.config import refresh_settings from core.settings import settings, data_root @@ -30,6 +35,7 @@ async def delete_expire_files(): await ip_limit["error"].remove_expired_ip() await ip_limit["metadata"].remove_expired_ip() await ip_limit["upload"].remove_expired_ip() + await StorageReservation.filter(expires_at__lte=await get_now()).delete() expire_data = await FileCodes.filter( Q(expired_at__lt=await get_now()) | Q(expired_count=0) ).all() @@ -75,6 +81,9 @@ async def clean_incomplete_uploads(): try: await UploadChunk.filter(upload_id=session.upload_id).delete() + await StorageReservation.filter( + token=f"chunk:{session.upload_id}" + ).delete() logging.info(f"已清理过期上传会话 upload_id={session.upload_id}") except Exception as e: logging.error( @@ -85,3 +94,37 @@ async def clean_incomplete_uploads(): logging.error(f"清理未完成上传任务异常: {e}") finally: await asyncio.sleep(3600) + + +async def clean_expired_presign_sessions(): + while True: + try: + await refresh_settings() + storage: FileStorageInterface = storages[settings.file_storage]() + now = await get_now() + expired_sessions = await PresignUploadSession.filter( + expires_at__lt=now + ).all() + for session in expired_sessions: + if session.mode == "direct": + try: + if await storage.file_exists(session.save_path): + await storage.delete_file( + FileCodes( + file_path=os.path.dirname(session.save_path), + uuid_file_name=os.path.basename(session.save_path), + ) + ) + except Exception as e: + logging.error( + "清理过期直传文件失败 " + f"upload_id={session.upload_id}: {e}" + ) + await StorageReservation.filter( + token=f"presign:{session.upload_id}" + ).delete() + await session.delete() + except Exception as e: + logging.error(f"清理过期预签名会话异常: {e}") + finally: + await asyncio.sleep(900) diff --git a/docs/changelog.md b/docs/changelog.md index e69de29..8581f74 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -0,0 +1,6 @@ +## [Unreleased] + +### Added + +- 增加全局存储容量上限配置,并对普通上传、分片上传、预签名直传和后台文件分享统一执行并发安全的容量预留。 +- 增加存储预留迁移及过期上传清理,失败、取消或过期的上传会释放预留容量。 diff --git a/docs/en/changelog.md b/docs/en/changelog.md index e69de29..0dbc7a7 100644 --- a/docs/en/changelog.md +++ b/docs/en/changelog.md @@ -0,0 +1,6 @@ +## [Unreleased] + +### Added + +- Added a global storage capacity limit with concurrency-safe reservations for regular, chunked, presigned, and admin file uploads. +- Added the storage reservation migration and stale upload cleanup so failed, cancelled, or expired uploads release reserved capacity. diff --git a/main.py b/main.py index 6be8715..1968b08 100644 --- a/main.py +++ b/main.py @@ -29,7 +29,11 @@ from core.database import db_startup_lock, get_db_config, init_db from core.logger import logger from core.response import APIResponse from core.settings import settings, BASE_DIR, DEFAULT_CONFIG -from core.tasks import delete_expire_files, clean_incomplete_uploads +from core.tasks import ( + clean_expired_presign_sessions, + clean_incomplete_uploads, + delete_expire_files, +) from core.version import APP_VERSION @@ -707,6 +711,7 @@ async def lifespan(app: FastAPI): # 启动后台任务 task = asyncio.create_task(delete_expire_files()) chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads()) + presign_cleanup_task = asyncio.create_task(clean_expired_presign_sessions()) logger.info("应用初始化完成") try: @@ -716,7 +721,13 @@ async def lifespan(app: FastAPI): logger.info("正在关闭应用...") task.cancel() chunk_cleanup_task.cancel() - await asyncio.gather(task, chunk_cleanup_task, return_exceptions=True) + presign_cleanup_task.cancel() + await asyncio.gather( + task, + chunk_cleanup_task, + presign_cleanup_task, + return_exceptions=True, + ) await Tortoise.close_connections() logger.info("应用已关闭") diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py index 13b2b7f..7025c61 100644 --- a/tests/test_admin_security.py +++ b/tests/test_admin_security.py @@ -182,6 +182,12 @@ class FakeConfigKeyValue: class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase): + def test_storage_limit_rejects_negative_values(self): + settings.user_config = copy.deepcopy(DEFAULT_CONFIG) + with self.assertRaises(HTTPException) as context: + asyncio.run(ConfigService().update_config({"storageLimit": -1})) + self.assertEqual(context.exception.status_code, 400) + def test_admin_session_lifetime_rejects_out_of_range_values(self): settings.user_config = copy.deepcopy(DEFAULT_CONFIG) diff --git a/tests/test_issue_486_storage_quota.py b/tests/test_issue_486_storage_quota.py new file mode 100644 index 0000000..57e4c3f --- /dev/null +++ b/tests/test_issue_486_storage_quota.py @@ -0,0 +1,91 @@ +import asyncio +import unittest + +from fastapi import HTTPException +from tortoise import Tortoise + +from apps.base.models import FileCodes, StorageReservation +from apps.base.quota import get_storage_usage, release_storage, reserve_storage +from core.settings import settings +from core.utils import get_now + + +class StorageQuotaTests(unittest.TestCase): + def test_quota_reservations_are_atomic_and_reusable(self): + asyncio.run(self._run_scenario()) + + async def _run_scenario(self): + original_config = dict(settings.user_config) + settings.storageLimit = 100 + await Tortoise.init( + config={ + "connections": { + "default": { + "engine": "tortoise.backends.sqlite", + "credentials": {"file_path": ":memory:"}, + } + }, + "apps": { + "models": { + "models": ["apps.base.models"], + "default_connection": "default", + } + }, + "use_tz": False, + "timezone": "Asia/Shanghai", + } + ) + await Tortoise.generate_schemas() + try: + await FileCodes.create(code="existing", size=60, expired_count=-1) + + results = await asyncio.gather( + reserve_storage("upload-a", 30, 300), + reserve_storage("upload-b", 30, 300), + return_exceptions=True, + ) + + self.assertEqual(sum(result is None for result in results), 1) + rejected = [result for result in results if isinstance(result, HTTPException)] + self.assertEqual(len(rejected), 1) + self.assertEqual(rejected[0].status_code, 507) + + usage = await get_storage_usage() + self.assertEqual(usage["used"], 60) + self.assertEqual(usage["reserved"], 30) + self.assertEqual(usage["available"], 10) + + active = await StorageReservation.first() + await release_storage(active.token) + await reserve_storage("upload-c", 40, 300) + self.assertEqual((await get_storage_usage())["available"], 0) + + settings.storageLimit = 0 + await reserve_storage("unlimited", 10_000, 300) + self.assertFalse( + await StorageReservation.filter(token="unlimited").exists() + ) + + settings.storageLimit = 100 + expired = await StorageReservation.get(token="upload-c") + expired.expires_at = await get_now() + await expired.save(update_fields=["expires_at"]) + await reserve_storage("upload-d", 40, 300) + self.assertEqual((await get_storage_usage())["reserved"], 40) + + await release_storage("upload-d") + same_token_results = await asyncio.gather( + *(reserve_storage("same-upload", 40, 300) for _ in range(10)), + return_exceptions=True, + ) + self.assertTrue(all(result is None for result in same_token_results)) + self.assertEqual( + await StorageReservation.filter(token="same-upload").count(), 1 + ) + finally: + settings.user_config = original_config + await Tortoise.close_connections() + + +if __name__ == "__main__": + unittest.main()