mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 00:15:56 +08:00
feat(media): 详情页按需查找 TMDB 链接 (#7492)
This commit is contained in:
@@ -6,7 +6,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Any, List, Optional, Union, cast
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Body, Depends, Query
|
||||
from fastapi import Body, Depends, HTTPException, Query
|
||||
from pydantic import BeforeValidator
|
||||
|
||||
from app.adapters.web.security.access import verify_apitoken, verify_token
|
||||
@@ -28,6 +28,12 @@ from app.application.classification.runtime import ClassificationRuntime
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.mediaserver import MediaServerQueryService
|
||||
from app.application.module import get_module_manager
|
||||
from app.application.server.lookup import (
|
||||
MediaMappingLookupBusy,
|
||||
MediaMappingLookupFailed,
|
||||
MediaMappingLookupUnavailable,
|
||||
get_media_mapping_lookup,
|
||||
)
|
||||
from app.application.server.mapping import get_media_mapping_port
|
||||
from app.application.subscription.contract import SubscriptionIdentity
|
||||
from app.application.subscription.query import SubscriptionQueryService
|
||||
@@ -50,7 +56,7 @@ from app.schemas.context import MediaSearchResults as _SchemaMediaSearchResults
|
||||
from app.schemas.context import MediaSeason as _SchemaMediaSeason
|
||||
from app.schemas.event import MediaSourceInfo as _SchemaMediaSourceInfo
|
||||
from app.schemas.file import FileItem as _SchemaFileItem
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingMatchQuery, MediaMappingQuery
|
||||
from app.schemas.media import MediaStatusQuery, MediaStatusResult, normalize_media_source, resolve_media_identity
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
@@ -75,6 +81,44 @@ async def media_mapping(
|
||||
return await port.async_query(query) if port is not None else None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/mapping/match",
|
||||
summary="按需查找 TMDB 共享关系",
|
||||
response_model=MediaMapping | None,
|
||||
responses={
|
||||
429: {"model": _SchemaResponse[None], "description": "同时查找的条目已达上限,请稍后重试"},
|
||||
502: {"model": _SchemaResponse[None], "description": "查找超时或失败,本次没有结论"},
|
||||
503: {"model": _SchemaResponse[None], "description": "查找服务暂不可用,例如正在关停"},
|
||||
},
|
||||
)
|
||||
async def match_media_mapping(
|
||||
query: Annotated[MediaMappingMatchQuery, Body()],
|
||||
_: ApiPrincipal = Depends(get_current_active_user_async),
|
||||
) -> MediaMapping | None:
|
||||
"""
|
||||
用户主动点击时查找 TMDB 关系,未命中共享关系时执行与订阅相同的转换并尽力写回共享表。
|
||||
|
||||
共享关系始终优先;同一条目同一时间只查找一次,请求断开不会取消查找,
|
||||
10 分钟内的结论直接复用。
|
||||
|
||||
:param query: 非 TMDB 原来源身份、必填影视类型和可选季号
|
||||
:param _: 已认证的当前用户
|
||||
:return: TMDB 关系;查找已完成但没有找到时为 None
|
||||
:raises HTTPException: 同时查找已满返回 429,查找失败返回 502,服务不可用返回 503
|
||||
"""
|
||||
lookup = get_media_mapping_lookup()
|
||||
if lookup is None:
|
||||
raise HTTPException(status_code=503, detail="TMDB 链接查找服务尚未就绪")
|
||||
try:
|
||||
return await lookup.lookup(query)
|
||||
except MediaMappingLookupBusy as err:
|
||||
raise HTTPException(status_code=429, detail="同时查找的条目过多,请稍后重试") from err
|
||||
except MediaMappingLookupFailed as err:
|
||||
raise HTTPException(status_code=502, detail="查找 TMDB 链接失败,请稍后重试") from err
|
||||
except MediaMappingLookupUnavailable as err:
|
||||
raise HTTPException(status_code=503, detail="TMDB 链接查找服务暂不可用") from err
|
||||
|
||||
|
||||
@router.post("/status", summary="批量查询本地入库与订阅状态", response_model=list[MediaStatusResult])
|
||||
async def media_status(
|
||||
items: Annotated[list[MediaStatusQuery], Body(min_length=1, max_length=50, description="按展示顺序提交的媒体,最多 50 项")],
|
||||
|
||||
242
app/application/server/lookup.py
Normal file
242
app/application/server/lookup.py
Normal file
@@ -0,0 +1,242 @@
|
||||
"""
|
||||
详情页按需查找 TMDB 关系的进程内协调。
|
||||
|
||||
本模块只负责共享关系优先、本地结果记录、同条目合并、并发上限和后台任务生命周期;
|
||||
具体匹配由启动组合根注入,Application 不反向依赖 Chain。状态只在本进程内有效,
|
||||
安全模式下多个 worker 各自持有一份。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from functools import partial
|
||||
from typing import Final, cast
|
||||
|
||||
from app.application.server.mapping import MediaMappingPort, get_media_mapping_port
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.tasks import TaskRegistry, get_task_registry
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingMatchQuery
|
||||
|
||||
# 本地结果记录的有效期,单位秒;与共享客户端的未命中缓存一致。
|
||||
RECORD_TTL: Final = 600
|
||||
# 本地结果记录的条数上限,超出时淘汰最久未访问的条目。
|
||||
RECORD_LIMIT: Final = 1024
|
||||
# 同时执行的后台查找条目上限;请求已断开但仍在运行的查找也计入。
|
||||
MATCH_LIMIT: Final = 4
|
||||
# 单次后台查找的总预算,单位秒;超时按失败处理,不写入本地记录。
|
||||
MATCH_TIMEOUT: Final = 180.0
|
||||
|
||||
MediaMappingMatcher = Callable[[MediaMappingMatchQuery], Awaitable[MediaMapping | None]]
|
||||
|
||||
|
||||
class MediaMappingLookupBusy(Exception):
|
||||
"""
|
||||
同时查找的条目已达上限,调用方应稍后重试。
|
||||
"""
|
||||
|
||||
|
||||
class MediaMappingLookupUnavailable(Exception):
|
||||
"""
|
||||
后台任务无法创建或已被关停取消,本次查找没有结论。
|
||||
"""
|
||||
|
||||
|
||||
class MediaMappingLookupFailed(Exception):
|
||||
"""
|
||||
后台查找超时或出现未预期异常,本次查找没有结论,也不写入本地记录。
|
||||
"""
|
||||
|
||||
|
||||
class _MatchFailure:
|
||||
"""
|
||||
后台查找失败的终态标记,避免把业务异常抛给任务登记器重复报告。
|
||||
"""
|
||||
|
||||
|
||||
_MATCH_FAILURE: Final = _MatchFailure()
|
||||
_Outcome = MediaMapping | None | _MatchFailure
|
||||
|
||||
|
||||
def _describe(query: MediaMappingMatchQuery) -> str:
|
||||
"""
|
||||
生成日志使用的条目描述,例如 `douban:123(电视剧 第2季)`。
|
||||
|
||||
:param query: 已校验的查找请求
|
||||
:return: 包含来源、ID、类型和季号的简短描述
|
||||
"""
|
||||
kind = "电影" if query.type == "movie" else "电视剧"
|
||||
season = f" 第{query.season}季" if query.season is not None else ""
|
||||
return f"{query.media_source.value}:{query.media_id}({kind}{season})"
|
||||
|
||||
|
||||
class MediaMappingLookup:
|
||||
"""
|
||||
串联共享关系、本地记录与后台匹配,保证同一条目同一时间只匹配一次。
|
||||
|
||||
共享关系始终优先;本地记录只在共享查询未命中时补充,记录找到与没找到两种结论。
|
||||
后台查找由任务登记器持有,请求断开不会取消;终态统一在任务完成回调中收口。
|
||||
只在宿主事件循环中调用。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
matcher: MediaMappingMatcher,
|
||||
*,
|
||||
port: Callable[[], MediaMappingPort | None] = get_media_mapping_port,
|
||||
tasks: Callable[[], TaskRegistry] = get_task_registry,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> None:
|
||||
"""
|
||||
保存注入能力,并建立有界记录、在途表及保护二者的锁。
|
||||
|
||||
:param matcher: 共享关系未命中时执行的订阅同款匹配
|
||||
:param port: 返回当前共享关系端口,未装配时返回 None
|
||||
:param tasks: 返回持有后台查找的任务登记器
|
||||
:param clock: 单调时钟,单位秒,测试可注入
|
||||
"""
|
||||
self._matcher = matcher
|
||||
self._port = port
|
||||
self._tasks = tasks
|
||||
self._clock = clock
|
||||
self._records: OrderedDict[str, tuple[float, MediaMapping | None]] = OrderedDict()
|
||||
self._flights: dict[str, asyncio.Task[_Outcome]] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
async def lookup(self, query: MediaMappingMatchQuery) -> MediaMapping | None:
|
||||
"""
|
||||
查找条目的 TMDB 关系:共享关系优先,其次本地记录,最后合并或启动后台匹配。
|
||||
|
||||
:param query: 已校验的原来源身份、影视类型和季号
|
||||
:return: TMDB 关系;查找已完成但没有找到时为 None
|
||||
:raises MediaMappingLookupBusy: 同时查找的条目已达上限
|
||||
:raises MediaMappingLookupUnavailable: 后台任务无法创建或已被关停取消
|
||||
:raises MediaMappingLookupFailed: 后台查找超时或出现未预期异常
|
||||
"""
|
||||
port = self._port()
|
||||
shared = await port.async_query(query) if port is not None else None
|
||||
if shared is not None:
|
||||
return shared
|
||||
key = query.model_dump_json()
|
||||
with self._lock:
|
||||
record = self._records.get(key)
|
||||
if record is not None and record[0] > self._clock():
|
||||
self._records.move_to_end(key)
|
||||
return record[1].model_copy(deep=True) if record[1] else None
|
||||
task = self._flights.get(key)
|
||||
if task is None:
|
||||
if len(self._flights) >= MATCH_LIMIT:
|
||||
logger.info(f"详情页查找 TMDB 链接:{_describe(query)} → 同时查找已达 {MATCH_LIMIT} 个,拒绝")
|
||||
raise MediaMappingLookupBusy()
|
||||
task = self._start(key, query)
|
||||
return await self._wait(task)
|
||||
|
||||
def _start(self, key: str, query: MediaMappingMatchQuery) -> asyncio.Task[_Outcome]:
|
||||
"""
|
||||
在锁内创建并登记后台查找;任务登记器拒绝时不留下在途项。
|
||||
|
||||
:param key: 规范化的查找键
|
||||
:param query: 已校验的查找请求
|
||||
:return: 由任务登记器持有的后台查找任务
|
||||
:raises MediaMappingLookupUnavailable: 任务登记器正在关闭
|
||||
"""
|
||||
try:
|
||||
task = self._tasks().create(self._run(query), owner="media-mapping.match")
|
||||
except RuntimeError as err:
|
||||
raise MediaMappingLookupUnavailable() from err
|
||||
flight = cast(asyncio.Task[_Outcome], task)
|
||||
self._flights[key] = flight
|
||||
flight.add_done_callback(partial(self._settle, key))
|
||||
return flight
|
||||
|
||||
async def _run(self, query: MediaMappingMatchQuery) -> _Outcome:
|
||||
"""
|
||||
在总预算内执行匹配并记录结论;超时和异常转换为失败终态,取消照常向外传播。
|
||||
|
||||
:param query: 已校验的查找请求
|
||||
:return: 找到的关系、没找到时的 None,或失败终态
|
||||
"""
|
||||
label = _describe(query)
|
||||
budget = asyncio.timeout(MATCH_TIMEOUT)
|
||||
try:
|
||||
async with budget:
|
||||
result = await self._matcher(query)
|
||||
except Exception as err: # 插件转换事件可能抛出任意异常,统一按本次失败处理
|
||||
if isinstance(err, TimeoutError) and budget.expired():
|
||||
logger.warning(f"详情页查找 TMDB 链接:{label} → 超时({MATCH_TIMEOUT:g} 秒)")
|
||||
else:
|
||||
# 匹配内部自行抛出的超时不是总预算到期,保留原始原因便于排查。
|
||||
logger.error(f"详情页查找 TMDB 链接:{label} → 失败:{err!r}")
|
||||
return _MATCH_FAILURE
|
||||
if result is None:
|
||||
logger.info(f"详情页查找 TMDB 链接:{label} → 未找到")
|
||||
else:
|
||||
season = f" 第{result.tmdb_season}季" if result.tmdb_season is not None else ""
|
||||
logger.info(f"详情页查找 TMDB 链接:{label} → 找到 TMDB {result.tmdb_type}/{result.tmdb_id}{season}")
|
||||
return result
|
||||
|
||||
def _settle(self, key: str, task: asyncio.Task[_Outcome]) -> None:
|
||||
"""
|
||||
在任务终态统一移出在途表;只有正常完成并得到结论时才写入本地记录。
|
||||
|
||||
任务在首次调度前被取消时协程体不会执行,因此不能依赖协程内的 finally 收口。
|
||||
|
||||
:param key: 规范化的查找键
|
||||
:param task: 已结束的后台查找任务
|
||||
"""
|
||||
concluded = not task.cancelled() and task.exception() is None
|
||||
outcome = task.result() if concluded else _MATCH_FAILURE
|
||||
with self._lock:
|
||||
if self._flights.get(key) is task:
|
||||
del self._flights[key]
|
||||
if isinstance(outcome, _MatchFailure):
|
||||
return
|
||||
self._records[key] = (self._clock() + RECORD_TTL, outcome)
|
||||
self._records.move_to_end(key)
|
||||
while len(self._records) > RECORD_LIMIT:
|
||||
self._records.popitem(last=False)
|
||||
|
||||
@staticmethod
|
||||
async def _wait(task: asyncio.Task[_Outcome]) -> MediaMapping | None:
|
||||
"""
|
||||
等待后台查找的终态;等待方被取消不影响查找本身。
|
||||
|
||||
:param task: 后台查找任务
|
||||
:return: 找到的关系副本,没找到时为 None
|
||||
:raises MediaMappingLookupUnavailable: 后台查找被取消,例如应用正在关停
|
||||
:raises MediaMappingLookupFailed: 后台查找超时或出现未预期异常
|
||||
"""
|
||||
try:
|
||||
outcome = await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if task.cancelled() and (current is None or current.cancelling() == 0):
|
||||
# 后台查找被取消而不是本请求被取消,不能把取消信号冒充为请求中断。
|
||||
raise MediaMappingLookupUnavailable() from None
|
||||
raise
|
||||
if isinstance(outcome, _MatchFailure):
|
||||
raise MediaMappingLookupFailed()
|
||||
return outcome.model_copy(deep=True) if outcome else None
|
||||
|
||||
|
||||
_lookup: MediaMappingLookup | None = None
|
||||
|
||||
|
||||
def configure_media_mapping_lookup(lookup: MediaMappingLookup | None) -> None:
|
||||
"""
|
||||
由宿主组合根装配或释放详情页查找协调对象。
|
||||
|
||||
:param lookup: 协调对象;None 表示释放
|
||||
"""
|
||||
global _lookup
|
||||
_lookup = lookup
|
||||
|
||||
|
||||
def get_media_mapping_lookup() -> MediaMappingLookup | None:
|
||||
"""
|
||||
返回已装配的详情页查找协调对象。
|
||||
|
||||
:return: 协调对象;未装配时为 None
|
||||
"""
|
||||
return _lookup
|
||||
@@ -18,6 +18,7 @@ from app.domain.context import Context, MediaInfo, MusicAlbumInfo, MusicArtistIn
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.foundation.singleton import Singleton
|
||||
from app.schemas.mapping import MediaMapping
|
||||
from app.schemas.types import MediaSource
|
||||
|
||||
_PUBLIC_MODULE = "app.chain.media"
|
||||
@@ -37,6 +38,7 @@ _ContextCall = Callable[..., Optional[Context]]
|
||||
_AsyncContextCall = Callable[..., Awaitable[Optional[Context]]]
|
||||
_ProjectionCall = Callable[..., Optional[dict[str, Any]]]
|
||||
_AsyncProjectionCall = Callable[..., Awaitable[Optional[dict[str, Any]]]]
|
||||
_AsyncMappingCall = Callable[..., Awaitable[Optional[MediaMapping]]]
|
||||
_SearchCall = Callable[..., tuple[Optional[MetaBase], list[MediaInfo]]]
|
||||
_AsyncSearchCall = Callable[
|
||||
..., Awaitable[tuple[Optional[MetaBase], list[MediaInfo]]]
|
||||
@@ -262,6 +264,9 @@ class MediaChain(ChainBase, metaclass=Singleton):
|
||||
_async_dispatch_projection_event = (
|
||||
MediaProjectionOwner._async_dispatch_projection_event
|
||||
)
|
||||
async_match_media_mapping = cast(
|
||||
_AsyncMappingCall, MediaProjectionOwner.async_match_media_mapping
|
||||
)
|
||||
_run_native_media_recognize = MediaRecognitionOwner._run_native_media_recognize
|
||||
_async_run_native_media_recognize = MediaRecognitionOwner._async_run_native_media_recognize
|
||||
recognize_by_meta = cast(_MediaCall, MediaRecognitionOwner.recognize_by_meta)
|
||||
|
||||
@@ -463,32 +463,72 @@ def _mapping_query(plan: _ProjectionPlan) -> MediaMappingQuery | None:
|
||||
return None
|
||||
|
||||
|
||||
def _season_unlisted(result: _ProjectionPayload, season: object) -> bool:
|
||||
"""
|
||||
判断 TMDB 详情是否给出了季列表却没有转换附带的季号。
|
||||
|
||||
TMDB 季匹配未命中时会按整剧名称回退,转换仍附带请求的季号;只有详情带季列表时才能核实,
|
||||
缺少季列表的插件结果保持原有处理。
|
||||
|
||||
:param result: 转换得到的完整 TMDB 详情
|
||||
:param season: 转换附带的 TMDB 季号,None 表示未指定
|
||||
:return: 详情给出季列表但其中没有该季时为 True
|
||||
"""
|
||||
seasons = result.get("seasons")
|
||||
if season is None or not isinstance(seasons, Sequence) or isinstance(seasons, (str, bytes)):
|
||||
return False
|
||||
return not any(isinstance(item, Mapping) and item.get("season_number") == season for item in seasons)
|
||||
|
||||
|
||||
def _extract_mapping(
|
||||
plan: _ProjectionPlan,
|
||||
query: MediaMappingQuery,
|
||||
result: _ProjectionPayload | None,
|
||||
) -> MediaMapping | None:
|
||||
"""
|
||||
从转换得到的 TMDB 原始详情提取单向关系,共享上报和详情页查找共用同一规则。
|
||||
|
||||
:param plan: 原来源身份及转换上下文,结果未声明类型时回退到调用方类型
|
||||
:param query: 由同一转换计划生成的共享查询
|
||||
:param result: 转换得到的完整 TMDB 详情,失败为 None
|
||||
:return: 可共享的关系;结果缺少有效 TMDB 类型或 ID,或 TMDB 详情未列出附带的季时为 None
|
||||
"""
|
||||
if not result:
|
||||
return None
|
||||
try:
|
||||
raw_type = result.get("media_type")
|
||||
media_type = raw_type if isinstance(raw_type, MediaType) else MediaType.from_agent(str(raw_type or ""))
|
||||
media_type = media_type or plan.media_type
|
||||
if media_type not in (MediaType.MOVIE, MediaType.TV):
|
||||
return None
|
||||
target_type: Literal["movie", "tv"] = "movie" if media_type == MediaType.MOVIE else "tv"
|
||||
tmdb_season = result.get("season") if target_type == "tv" else None
|
||||
if _season_unlisted(result, tmdb_season):
|
||||
# 整剧回退命中的季号未经核实,不能写成不存在的季链接;订阅转换结果本身不受影响。
|
||||
return None
|
||||
return MediaMapping.model_validate({
|
||||
**query.model_dump(), "type": query.type or target_type,
|
||||
"tmdb_id": result.get("id"), "tmdb_type": target_type, "tmdb_season": tmdb_season,
|
||||
})
|
||||
except (ValidationError, TypeError, ValueError):
|
||||
# 未提供有效 TMDB 身份的旧插件结果继续返回业务调用方,但不能污染公共关系表。
|
||||
return None
|
||||
|
||||
|
||||
def _share_mapping(plan: _ProjectionPlan, result: _ProjectionPayload | None) -> None:
|
||||
"""
|
||||
从成功的 TMDB 原始详情提取关系;不影响原转换结果与插件兼容合同。
|
||||
从成功的 TMDB 原始详情提取关系并后台共享;不影响原转换结果与插件兼容合同。
|
||||
|
||||
:param plan: 原来源身份及转换上下文
|
||||
:param result: 成功转换的完整 TMDB 详情,失败为 None
|
||||
"""
|
||||
port = get_media_mapping_port()
|
||||
query = _mapping_query(plan)
|
||||
if port is None or query is None or not result:
|
||||
return
|
||||
try:
|
||||
raw_type = result.get("media_type")
|
||||
media_type = raw_type if isinstance(raw_type, MediaType) else MediaType.from_agent(str(raw_type or ""))
|
||||
media_type = media_type or plan.media_type
|
||||
if media_type not in (MediaType.MOVIE, MediaType.TV):
|
||||
return
|
||||
target_type: Literal["movie", "tv"] = "movie" if media_type == MediaType.MOVIE else "tv"
|
||||
port.share(MediaMapping.model_validate({
|
||||
**query.model_dump(), "type": query.type or target_type,
|
||||
"tmdb_id": result.get("id"), "tmdb_type": target_type,
|
||||
"tmdb_season": result.get("season") if target_type == "tv" else None,
|
||||
}))
|
||||
except (ValidationError, TypeError, ValueError):
|
||||
# 未提供有效 TMDB 身份的旧插件结果继续返回业务调用方,但不能污染公共关系表。
|
||||
if port is None or query is None:
|
||||
return
|
||||
mapping = _extract_mapping(plan, query, result)
|
||||
if mapping is not None:
|
||||
port.share(mapping)
|
||||
|
||||
|
||||
class MediaProjectionOwner(_MediaOwnerBase):
|
||||
@@ -677,3 +717,31 @@ class MediaProjectionOwner(_MediaOwnerBase):
|
||||
result = await _async_convert_builtin_projection(self, plan)
|
||||
_share_mapping(plan, result)
|
||||
return result
|
||||
|
||||
async def async_match_media_mapping(
|
||||
self,
|
||||
query: MediaMappingQuery,
|
||||
) -> MediaMapping | None:
|
||||
"""
|
||||
用订阅同款转换为非 TMDB 影视来源查找 TMDB 关系,成功结果由转换流程尽力写回共享表。
|
||||
|
||||
只复用 `async_convert_media_identity`,不另写匹配流程;返回值与本次上报的关系
|
||||
使用同一提取规则,因此逐字段一致。共享关系已由调用方先行查询。
|
||||
|
||||
:param query: 已校验的原来源身份、影视类型和季号
|
||||
:return: 本次转换得到的关系;来源不受支持、未匹配或结果无效时为 None
|
||||
"""
|
||||
mtype = MediaType.MOVIE if query.type == "movie" else MediaType.TV if query.type == "tv" else None
|
||||
plan = _build_projection_plan(MediaSource.TMDB, query.media_source, query.media_id, mtype, query.season)
|
||||
mapping_query = _mapping_query(plan) if plan else None
|
||||
if plan is None or mapping_query is None:
|
||||
return None
|
||||
result = await MediaProjectionOwner.async_convert_media_identity(
|
||||
self,
|
||||
target_source=MediaSource.TMDB,
|
||||
media_source=query.media_source,
|
||||
media_id=query.media_id,
|
||||
mtype=mtype,
|
||||
season=query.season,
|
||||
)
|
||||
return _extract_mapping(plan, mapping_query, result)
|
||||
|
||||
@@ -632,6 +632,10 @@
|
||||
"未配置 Follow 订阅用户,跳过刷新": "No Follow subscription users configured, skipping refresh",
|
||||
"订阅日历预缓存完成": "Subscription calendar precache completed",
|
||||
"订阅活动暂时不可用": "Subscription activity is temporarily unavailable",
|
||||
"TMDB 链接查找服务尚未就绪": "TMDB link lookup is not ready yet",
|
||||
"同时查找的条目过多,请稍后重试": "Too many lookups are in progress, please try again later",
|
||||
"查找 TMDB 链接失败,请稍后重试": "Failed to look up the TMDB link, please try again later",
|
||||
"TMDB 链接查找服务暂不可用": "TMDB link lookup is temporarily unavailable",
|
||||
"活动不存在或无权查看": "Activity does not exist or access is denied",
|
||||
"文件路径为空": "File path is empty",
|
||||
"目录名不能包含路径分隔符": "Directory names cannot contain path separators",
|
||||
|
||||
@@ -590,6 +590,10 @@
|
||||
"未配置 Follow 订阅用户,跳过刷新": "未設定 Follow 訂閱使用者,跳過重新整理",
|
||||
"订阅日历预缓存完成": "訂閱日曆預快取完成",
|
||||
"订阅活动暂时不可用": "訂閱活動暫時無法使用",
|
||||
"TMDB 链接查找服务尚未就绪": "TMDB 連結查找服務尚未就緒",
|
||||
"同时查找的条目过多,请稍后重试": "同時查找的條目過多,請稍後重試",
|
||||
"查找 TMDB 链接失败,请稍后重试": "查找 TMDB 連結失敗,請稍後重試",
|
||||
"TMDB 链接查找服务暂不可用": "TMDB 連結查找服務暫時無法使用",
|
||||
"活动不存在或无权查看": "活動不存在或無權查看",
|
||||
"该源地址已有内部整理或失败历史,不能覆盖": "此來源位址已有內部整理或失敗歷史,不能覆寫",
|
||||
"该源地址的历史不属于可重复的外部登记": "此來源位址的歷史不屬於可重試的外部登記",
|
||||
|
||||
@@ -50,6 +50,27 @@ class MediaMappingQuery(BaseModel):
|
||||
return value
|
||||
|
||||
|
||||
class MediaMappingMatchQuery(MediaMappingQuery):
|
||||
"""
|
||||
详情页按需查找 TMDB 关系的请求,影视类型必填。
|
||||
|
||||
订阅转换总会携带类型,必填可让查找结果与订阅写入的共享关系落在同一缓存键上。
|
||||
"""
|
||||
|
||||
type: Literal["movie", "tv"] = Field(description="原来源影视类型,必填")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_season(self) -> "MediaMappingMatchQuery":
|
||||
"""
|
||||
拒绝电影携带季号,避免同一电影因季号不同被重复查找。
|
||||
|
||||
:return: 类型与季号相容的查询
|
||||
"""
|
||||
if self.type == "movie" and self.season is not None:
|
||||
raise ValueError("电影来源不能指定季号")
|
||||
return self
|
||||
|
||||
|
||||
class MediaMapping(MediaMappingQuery):
|
||||
"""
|
||||
记录单向转换的原身份及对应的 TMDB 类型、ID、季号。
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.application.image import (
|
||||
reset_wallpaper_providers,
|
||||
)
|
||||
from app.application.module import ModuleRuntime, configure_module_runtime
|
||||
from app.application.server.lookup import MediaMappingLookup, configure_media_mapping_lookup
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
from app.application.subscription.activity import SubscriptionActivityService
|
||||
from app.application.system import SystemService
|
||||
@@ -35,6 +36,7 @@ from app.chain._recognition import (
|
||||
configure_recognition_share_port,
|
||||
reset_recognition_share_port,
|
||||
)
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.mediaserver import MediaServerChain
|
||||
from app.chain.subscribe.notify import (
|
||||
SubscriptionSharePort,
|
||||
@@ -64,6 +66,7 @@ from app.runtime.extensions.module.manager import ModuleManager
|
||||
from app.runtime.extensions.plugin.manager import PluginManager
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingMatchQuery
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerQueryOptions
|
||||
from app.schemas.types import MediaType
|
||||
from app.startup.composition.database import build_transactional_user_repository
|
||||
@@ -337,6 +340,16 @@ class _NetworkFilesystemAdapter:
|
||||
))
|
||||
|
||||
|
||||
async def _match_media_mapping(query: MediaMappingMatchQuery) -> MediaMapping | None:
|
||||
"""
|
||||
把详情页按需查找交给媒体门面,执行与订阅相同的来源转换。
|
||||
|
||||
:param query: 已校验的原来源身份、影视类型和季号
|
||||
:return: 本次转换得到的 TMDB 关系;未匹配时为 None
|
||||
"""
|
||||
return await MediaChain().async_match_media_mapping(query)
|
||||
|
||||
|
||||
def configure_chain_port_composition() -> None:
|
||||
"""
|
||||
原子装配 Chain 的共享服务与文件系统端口。
|
||||
@@ -344,6 +357,7 @@ def configure_chain_port_composition() -> None:
|
||||
reset_chain_port_composition()
|
||||
try:
|
||||
configure_media_mapping_port(MediaMappingClient())
|
||||
configure_media_mapping_lookup(MediaMappingLookup(_match_media_mapping))
|
||||
configure_recognition_share_port(
|
||||
cast(RecognitionSharePort, _RecognitionShareAdapter())
|
||||
)
|
||||
@@ -362,6 +376,7 @@ def reset_chain_port_composition() -> None:
|
||||
"""
|
||||
释放 Chain 技术端口,支持重复 lifespan 与启动失败回滚。
|
||||
"""
|
||||
configure_media_mapping_lookup(None)
|
||||
configure_media_mapping_port(None)
|
||||
reset_network_filesystem_port()
|
||||
reset_subscription_share_port()
|
||||
|
||||
@@ -850,8 +850,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1187 |
|
||||
| 内部导入边 | 10,406 |
|
||||
| Python 模块 | 1188 |
|
||||
| 内部导入边 | 10,419 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
@@ -15,6 +15,18 @@
|
||||
成功关系缓存一小时、未命中十分钟,故障冷却三十秒,并合并并发查询、限制在途请求数。
|
||||
详情页独立异步补充 TheMovieDb 外链,查询失败时保留原详情及操作。
|
||||
|
||||
共享关系未命中时,登录用户可在详情页主动点击,经 `POST /api/v1/media/mapping/match`
|
||||
按需查找。请求体为 `media_source`、`media_id`、必填的 `type=movie|tv` 和可选 `season`
|
||||
(电影不能带季号);返回统一响应,`data` 为关系或 `null`(查找完成但没找到)。处理顺序为:
|
||||
先查共享关系(与上面的查询共用缓存),命中直接返回;再读本进程 10 分钟内的结论,找到与没找到都记;
|
||||
仍没有时执行与订阅相同的来源转换,成功后尽力写回 Server。同一条目同一时间只查找一次,
|
||||
请求断开不取消查找;同时查找的条目最多 4 个,超出返回 429;单次查找总时限 180 秒,
|
||||
超时或异常返回 502 且不记录结论;查找服务未就绪或正在关停返回 503。
|
||||
|
||||
写回是尽力而为:客户端处于故障冷却、在途已满或共享开关关闭时不上报;Server 已有关系时以 Server
|
||||
为准,客户端缓存随之修正,之后的查找立即返回 Server 的关系。共享开关关闭时仍可查找,只是不查询
|
||||
也不上报。以上状态只在本进程,安全模式下多个 worker 各自独立。此接口同样不增加 Agent operation。
|
||||
|
||||
Server 使用独立 SQL 表长期保存关系,不属于识别缓存清理范围。公共上报只补缺,
|
||||
管理后台可纠正目标或撤销错误关系;撤销保留记录,防止旧实例覆盖。实例正缓存最多一小时后更新。
|
||||
|
||||
|
||||
@@ -173,6 +173,18 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)):
|
||||
重试仍失败时继续抛出查询异常;普通未找到不触发重试。上述离线测试不代表真实媒体服务器
|
||||
或报告者 Docker 实例验收。
|
||||
|
||||
### 详情页按需查找 TMDB 链接
|
||||
|
||||
`tests/test_media_mapping_lookup.py` 注入假匹配、可控时钟和独立 `TaskRegistry`,验证共享关系
|
||||
优先于本地记录(没找到后被订阅补齐、本地结果被 Server 修正)、10 分钟记录与 LRU 淘汰、
|
||||
同条目合并、第 5 个不同条目被拒绝、请求断开后查找继续并占用名额、任务首次调度前被关停取消时
|
||||
仍清理在途项、超时和异常不写记录,以及结论日志。Chain 方法用例覆盖豆瓣电影、豆瓣剧集、
|
||||
Bangumi、AniList 与插件来源,确认返回值与上报关系一致;季匹配回退到整剧名称且 TMDB 详情未列出
|
||||
所附季号时既不返回也不上报,订阅转换结果保持不变(`tests/test_media_mapping.py` 同步覆盖上报路径);
|
||||
接口用例覆盖参数校验和 429/502/503 翻译。
|
||||
新增 `app/application/server/lookup.py` 进入启动导入闭包,三个启动入口的模块数快照各增加 1;
|
||||
仅更新该结构事实,原冷导入耗时记录与 3000ms 上限保留。上述用例不访问 TMDB、豆瓣或 Server。
|
||||
|
||||
### 飞书长会话流式卡片回归
|
||||
|
||||
`tests/test_feishu.py` 在 CardKit API 边界模拟 `300309` / `200850`:重开同一卡片的
|
||||
|
||||
@@ -166,8 +166,10 @@ downloader mappings when switching path modes.
|
||||
Conversions from other video sources to TMDB reuse cached community mappings
|
||||
before matching names and share successful results. Browsing only looks up known
|
||||
mappings to add a TheMovieDb link and preserves the original source identity.
|
||||
`GET /api/v1/media/mapping` is a frontend helper, without an Agent operation;
|
||||
continue using `media.detail` and do not construct extra HTTP requests.
|
||||
`GET /api/v1/media/mapping` and `POST /api/v1/media/mapping/match` (an explicit
|
||||
user click that runs the subscription conversion when no mapping is known) are
|
||||
frontend helpers, without Agent operations; continue using `media.detail` and do
|
||||
not construct extra HTTP requests.
|
||||
|
||||
1. Select the exact `operation_id` from the category index below.
|
||||
2. Call `read_skill` again with `name="moviepilot-api"` and
|
||||
|
||||
@@ -570,8 +570,10 @@ def configure_plugin_system_services():
|
||||
)
|
||||
|
||||
init_chain_ports()
|
||||
# 共享关系是新增的外部端口;普通单元测试保持未装配,由专项测试注入受控实现。
|
||||
# 共享关系与详情页查找会访问外部服务;普通单元测试保持未装配,由专项测试注入受控实现。
|
||||
from app.application.server.lookup import configure_media_mapping_lookup
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
configure_media_mapping_lookup(None)
|
||||
configure_media_mapping_port(None)
|
||||
init_chain_network_ports()
|
||||
configure_site_query_service(SiteQueryService(repository=site_repository()))
|
||||
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10406,
|
||||
"edge_sha256": "5157281ae12364f0d1c5ffcbbe8e7c41b5b02bf4b95b318568f3e75ab2e17c35",
|
||||
"edge_count": 10419,
|
||||
"edge_sha256": "07addae85ceb8650f858dee5e61b5612e04e3e3cda83c96809ef9f3594d65a08",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -2831,6 +2831,7 @@
|
||||
"app.api.endpoints.media -> app.application.plugin",
|
||||
"app.api.endpoints.media -> app.application.plugin.runtime",
|
||||
"app.api.endpoints.media -> app.application.server",
|
||||
"app.api.endpoints.media -> app.application.server.lookup",
|
||||
"app.api.endpoints.media -> app.application.server.mapping",
|
||||
"app.api.endpoints.media -> app.application.subscription",
|
||||
"app.api.endpoints.media -> app.application.subscription.contract",
|
||||
@@ -4389,6 +4390,14 @@
|
||||
"app.application.security.widget -> app.schemas.widget",
|
||||
"app.application.servarr -> app.schemas",
|
||||
"app.application.servarr -> app.schemas.types",
|
||||
"app.application.server.lookup -> app.application",
|
||||
"app.application.server.lookup -> app.application.server",
|
||||
"app.application.server.lookup -> app.application.server.mapping",
|
||||
"app.application.server.lookup -> app.runtime",
|
||||
"app.application.server.lookup -> app.runtime.log",
|
||||
"app.application.server.lookup -> app.runtime.tasks",
|
||||
"app.application.server.lookup -> app.schemas",
|
||||
"app.application.server.lookup -> app.schemas.mapping",
|
||||
"app.application.server.mapping -> app.schemas",
|
||||
"app.application.server.mapping -> app.schemas.mapping",
|
||||
"app.application.server.payload -> app.schemas",
|
||||
@@ -5258,6 +5267,7 @@
|
||||
"app.chain.media.facade -> app.foundation",
|
||||
"app.chain.media.facade -> app.foundation.singleton",
|
||||
"app.chain.media.facade -> app.schemas",
|
||||
"app.chain.media.facade -> app.schemas.mapping",
|
||||
"app.chain.media.facade -> app.schemas.types",
|
||||
"app.chain.media.path -> app.application",
|
||||
"app.chain.media.path -> app.application.audio",
|
||||
@@ -10389,12 +10399,14 @@
|
||||
"app.startup.composition.chain -> app.application.image",
|
||||
"app.startup.composition.chain -> app.application.module",
|
||||
"app.startup.composition.chain -> app.application.server",
|
||||
"app.startup.composition.chain -> app.application.server.lookup",
|
||||
"app.startup.composition.chain -> app.application.server.mapping",
|
||||
"app.startup.composition.chain -> app.application.subscription",
|
||||
"app.startup.composition.chain -> app.application.subscription.activity",
|
||||
"app.startup.composition.chain -> app.application.system",
|
||||
"app.startup.composition.chain -> app.chain",
|
||||
"app.startup.composition.chain -> app.chain._recognition",
|
||||
"app.startup.composition.chain -> app.chain.media",
|
||||
"app.startup.composition.chain -> app.chain.mediaserver",
|
||||
"app.startup.composition.chain -> app.chain.subscribe",
|
||||
"app.startup.composition.chain -> app.chain.subscribe.notify",
|
||||
@@ -10430,6 +10442,7 @@
|
||||
"app.startup.composition.chain -> app.runtime.stop",
|
||||
"app.startup.composition.chain -> app.schemas",
|
||||
"app.startup.composition.chain -> app.schemas.common",
|
||||
"app.startup.composition.chain -> app.schemas.mapping",
|
||||
"app.startup.composition.chain -> app.schemas.mediaserver",
|
||||
"app.startup.composition.chain -> app.schemas.types",
|
||||
"app.startup.composition.chain -> app.startup",
|
||||
@@ -11387,7 +11400,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1187,
|
||||
"module_count": 1188,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11797,6 +11810,7 @@
|
||||
"app.application.security.widget",
|
||||
"app.application.servarr",
|
||||
"app.application.server",
|
||||
"app.application.server.lookup",
|
||||
"app.application.server.mapping",
|
||||
"app.application.server.payload",
|
||||
"app.application.server.report",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 615,
|
||||
"loaded_app_module_count": 616,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 629,
|
||||
"loaded_app_module_count": 630,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 631,
|
||||
"loaded_app_module_count": 632,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
@@ -22,6 +23,9 @@ from app.application.messaging import ingress as ingress_provider
|
||||
from app.application.security import auth as auth_provider
|
||||
from app.application.security import passkey as passkey_provider
|
||||
from app.application.security import user as user_provider
|
||||
from app.application.server import lookup as lookup_provider
|
||||
from app.application.server import mapping as mapping_provider
|
||||
from app.schemas.mapping import MediaMappingMatchQuery
|
||||
from app.startup.composition import agent as agent_composition
|
||||
from app.startup.composition import chain as chain_composition
|
||||
from app.startup.composition import network as network_composition
|
||||
@@ -217,6 +221,41 @@ def test_chain_owner_reset_is_symmetric_and_idempotent(monkeypatch) -> None:
|
||||
assert wallpaper.get_mediaserver_wallpapers() == []
|
||||
|
||||
|
||||
def test_chain_port_owner_publishes_and_releases_mapping_lookup(monkeypatch) -> None:
|
||||
"""
|
||||
Chain 端口 owner 在共享关系端口之后发布详情页查找协调对象,撤销时先撤协调对象且可重复执行。
|
||||
"""
|
||||
relation = object()
|
||||
match = AsyncMock(return_value=relation)
|
||||
monkeypatch.setattr(chain_composition.MediaChain, "async_match_media_mapping", match)
|
||||
calls: list[str] = []
|
||||
original_lookup = chain_composition.configure_media_mapping_lookup
|
||||
original_port = chain_composition.configure_media_mapping_port
|
||||
monkeypatch.setattr(chain_composition, "configure_media_mapping_lookup",
|
||||
lambda value: (calls.append(f"lookup:{value is not None}"), original_lookup(value)))
|
||||
monkeypatch.setattr(chain_composition, "configure_media_mapping_port",
|
||||
lambda value: (calls.append(f"port:{value is not None}"), original_port(value)))
|
||||
|
||||
chain_composition.configure_chain_port_composition()
|
||||
published = lookup_provider.get_media_mapping_lookup()
|
||||
assert isinstance(published, lookup_provider.MediaMappingLookup)
|
||||
assert mapping_provider.get_media_mapping_port() is not None
|
||||
query = MediaMappingMatchQuery(media_source="douban", media_id="1001", type="tv")
|
||||
assert asyncio.run(published._matcher(query)) is relation
|
||||
match.assert_awaited_once_with(query)
|
||||
chain_composition.reset_chain_port_composition()
|
||||
chain_composition.reset_chain_port_composition()
|
||||
|
||||
assert lookup_provider.get_media_mapping_lookup() is None
|
||||
assert mapping_provider.get_media_mapping_port() is None
|
||||
assert calls == [
|
||||
"lookup:False", "port:False",
|
||||
"port:True", "lookup:True",
|
||||
"lookup:False", "port:False",
|
||||
"lookup:False", "port:False",
|
||||
]
|
||||
|
||||
|
||||
def test_composition_owner_resets_run_in_reverse_publication_order(monkeypatch) -> None:
|
||||
"""
|
||||
多 provider owner 必须按发布逆序撤销,避免依赖先于消费者消失。
|
||||
|
||||
@@ -186,6 +186,23 @@ def test_miss_keeps_existing_conversion_and_shares_success(monkeypatch):
|
||||
assert port.share.call_args.args[0] == relation(season=1, tmdb_season=2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_unlisted_tmdb_season_keeps_conversion_without_sharing(monkeypatch, asynchronous):
|
||||
"""
|
||||
季匹配回退到整剧名称且 TMDB 详情未列出附带的季时,订阅转换结果不变,但不上报季关系。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
port = SimpleNamespace(query=Mock(return_value=None), async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
fallback = {"id": 456, "media_type": "tv", "season": 2, "seasons": [{"season_number": 0}, {"season_number": 1}]}
|
||||
match = AsyncMock(return_value=fallback) if asynchronous else Mock(return_value=fallback)
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection" if asynchronous else "_convert_builtin_projection", match)
|
||||
args = dict(target_source=MediaSource.TMDB, media_source=MediaSource.AniList, media_id="123", mtype=MediaType.TV, season=2)
|
||||
result = asyncio.run(MediaChain.async_convert_media_identity(SimpleNamespace(), **args)) if asynchronous else MediaChain.convert_media_identity(SimpleNamespace(), **args)
|
||||
assert result == fallback
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
def test_reverse_conversion_never_queries_or_shares(monkeypatch):
|
||||
"""
|
||||
原有 TMDB 到其他来源转换保持原行为,不接入关系共享。
|
||||
|
||||
523
tests/test_media_mapping_lookup.py
Normal file
523
tests/test_media_mapping_lookup.py
Normal file
@@ -0,0 +1,523 @@
|
||||
"""
|
||||
详情页按需查找 TMDB 关系的协调、转换复用和接口回归。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Iterator
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.adapters.external import mapping as transport
|
||||
from app.api.endpoints import media as endpoint
|
||||
from app.application.server import lookup as lookup_module
|
||||
from app.application.server.lookup import (
|
||||
MediaMappingLookup,
|
||||
MediaMappingLookupBusy,
|
||||
MediaMappingLookupFailed,
|
||||
MediaMappingLookupUnavailable,
|
||||
)
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.tasks import TaskRegistry
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingMatchQuery, MediaMappingQuery
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
def match_query(**overrides) -> MediaMappingMatchQuery:
|
||||
"""
|
||||
构造豆瓣剧集第 2 季的查找请求,可按需覆盖来源、ID、类型和季号。
|
||||
"""
|
||||
values = {"media_source": MediaSource.Douban, "media_id": "1001", "type": "tv", "season": 2, **overrides}
|
||||
return MediaMappingMatchQuery(**values)
|
||||
|
||||
|
||||
def found(query: MediaMappingQuery, **overrides) -> MediaMapping:
|
||||
"""
|
||||
为查询构造 TMDB 剧集关系,默认季号与原来源相同。
|
||||
"""
|
||||
values = {"tmdb_id": 456, "tmdb_type": "tv", "tmdb_season": query.season, **overrides}
|
||||
if query.type == "movie":
|
||||
values = {"tmdb_id": 456, "tmdb_type": "movie", "tmdb_season": None, **overrides}
|
||||
return MediaMapping(**query.model_dump(), **values)
|
||||
|
||||
|
||||
def blocking_matcher(gate: asyncio.Event) -> AsyncMock:
|
||||
"""
|
||||
返回等待闸门打开后才给出结论的匹配替身,用于观察在途状态。
|
||||
"""
|
||||
async def match(query: MediaMappingMatchQuery) -> MediaMapping:
|
||||
"""
|
||||
模拟耗时的订阅同款匹配。
|
||||
"""
|
||||
await gate.wait()
|
||||
return found(query)
|
||||
return AsyncMock(side_effect=match)
|
||||
|
||||
|
||||
def test_shared_relation_takes_priority_over_local_record() -> None:
|
||||
"""
|
||||
共享关系始终优先:本地记录没找到或找到旧目标后,客户端出现的新关系立即生效。
|
||||
"""
|
||||
missing, other = match_query(), match_query(media_id="2002")
|
||||
corrected = found(other, tmdb_id=999)
|
||||
port = SimpleNamespace(async_query=AsyncMock(side_effect=[None, None, found(missing), None, corrected]))
|
||||
matcher = AsyncMock(side_effect=[None, found(other)])
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
依次覆盖没找到后被订阅补齐、本地匹配后被 Server 修正两种情况。
|
||||
"""
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: port, tasks=TaskRegistry)
|
||||
assert await lookup.lookup(missing) is None
|
||||
assert await lookup.lookup(missing) is None
|
||||
assert await lookup.lookup(missing) == found(missing)
|
||||
assert await lookup.lookup(other) == found(other)
|
||||
assert await lookup.lookup(other) == corrected
|
||||
assert matcher.await_count == 2
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_local_record_covers_disabled_sharing_and_expires() -> None:
|
||||
"""
|
||||
共享未装配时本地记录同时记住没找到和找到,过期后重新匹配,读取结果互不影响。
|
||||
"""
|
||||
clock = [100.0]
|
||||
query = match_query()
|
||||
matcher = AsyncMock(side_effect=[None, found(query)])
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
有效期内不重复匹配,过期后得到新结论并继续复用。
|
||||
"""
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=TaskRegistry, clock=lambda: clock[0])
|
||||
assert await lookup.lookup(query) is None
|
||||
assert await lookup.lookup(query) is None
|
||||
clock[0] += lookup_module.RECORD_TTL + 1
|
||||
first = await lookup.lookup(query)
|
||||
first.tmdb_id = 1
|
||||
assert await lookup.lookup(query) == found(query)
|
||||
assert matcher.await_count == 2
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_record_limit_evicts_least_recently_used(monkeypatch) -> None:
|
||||
"""
|
||||
条数超过上限时淘汰最久未访问的记录,刚访问过的记录保留。
|
||||
"""
|
||||
monkeypatch.setattr(lookup_module, "RECORD_LIMIT", 2)
|
||||
first, second, third = (match_query(media_id=str(value)) for value in (1, 2, 3))
|
||||
matcher = AsyncMock(side_effect=lambda query: found(query))
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
访问顺序决定淘汰对象。
|
||||
"""
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=TaskRegistry)
|
||||
for query in (first, second, first, third):
|
||||
await lookup.lookup(query)
|
||||
assert matcher.await_count == 3
|
||||
await lookup.lookup(first)
|
||||
assert matcher.await_count == 3
|
||||
await lookup.lookup(second)
|
||||
assert matcher.await_count == 4
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_concurrent_requests_share_one_match() -> None:
|
||||
"""
|
||||
同一条目的并发请求只触发一次匹配,并得到相同结果。
|
||||
"""
|
||||
async def run() -> None:
|
||||
"""
|
||||
匹配未完成前的所有请求都合并到同一个后台任务。
|
||||
"""
|
||||
gate = asyncio.Event()
|
||||
matcher = blocking_matcher(gate)
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=TaskRegistry)
|
||||
waiters = [asyncio.create_task(lookup.lookup(match_query())) for _ in range(3)]
|
||||
await asyncio.sleep(0)
|
||||
assert len(lookup._flights) == 1
|
||||
gate.set()
|
||||
assert await asyncio.gather(*waiters) == [found(match_query())] * 3
|
||||
assert matcher.await_count == 1
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_distinct_entries_beyond_limit_are_rejected() -> None:
|
||||
"""
|
||||
同时查找的不同条目达到上限后拒绝新条目,名额释放后可以继续查找。
|
||||
"""
|
||||
async def run() -> None:
|
||||
"""
|
||||
第 5 个不同条目在前 4 个完成前被拒绝。
|
||||
"""
|
||||
gate = asyncio.Event()
|
||||
lookup = MediaMappingLookup(blocking_matcher(gate), port=lambda: None, tasks=TaskRegistry)
|
||||
waiters = [
|
||||
asyncio.create_task(lookup.lookup(match_query(media_id=str(value))))
|
||||
for value in range(1, lookup_module.MATCH_LIMIT + 1)
|
||||
]
|
||||
await asyncio.sleep(0)
|
||||
with pytest.raises(MediaMappingLookupBusy):
|
||||
await lookup.lookup(match_query(media_id="extra"))
|
||||
gate.set()
|
||||
await asyncio.gather(*waiters)
|
||||
assert await lookup.lookup(match_query(media_id="extra")) == found(match_query(media_id="extra"))
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_cancelled_waiter_keeps_match_running_and_slot_occupied() -> None:
|
||||
"""
|
||||
请求断开不取消后台查找;查找期间继续占用名额,完成后写入记录。
|
||||
"""
|
||||
async def run() -> None:
|
||||
"""
|
||||
取消等待方后匹配仍然完成,再次请求直接复用结论。
|
||||
"""
|
||||
registry = TaskRegistry()
|
||||
gate = asyncio.Event()
|
||||
matcher = blocking_matcher(gate)
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=lambda: registry)
|
||||
waiter = asyncio.create_task(lookup.lookup(match_query()))
|
||||
await asyncio.sleep(0)
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
assert len(lookup._flights) == 1
|
||||
gate.set()
|
||||
await asyncio.gather(*(record.task for record in registry.records))
|
||||
assert not lookup._flights
|
||||
assert await lookup.lookup(match_query()) == found(match_query())
|
||||
assert matcher.await_count == 1
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_task_cancelled_before_start_cleans_up_without_record() -> None:
|
||||
"""
|
||||
后台任务在首次调度前被关停取消时,协程体不会执行,仍须清理在途项且不写记录。
|
||||
"""
|
||||
async def run() -> None:
|
||||
"""
|
||||
关停取消尚未启动的查找,等待方得到不可用,之后拒绝创建新任务。
|
||||
"""
|
||||
registry = TaskRegistry()
|
||||
matcher = AsyncMock(return_value=None)
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=lambda: registry)
|
||||
waiter = asyncio.create_task(lookup.lookup(match_query()))
|
||||
await asyncio.sleep(0)
|
||||
assert len(lookup._flights) == 1
|
||||
assert await registry.shutdown(timeout_seconds=1)
|
||||
with pytest.raises(MediaMappingLookupUnavailable):
|
||||
await waiter
|
||||
matcher.assert_not_awaited()
|
||||
assert not lookup._flights
|
||||
assert not lookup._records
|
||||
with pytest.raises(MediaMappingLookupUnavailable):
|
||||
await lookup.lookup(match_query())
|
||||
assert not lookup._flights
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_timeout_and_error_fail_without_record(monkeypatch) -> None:
|
||||
"""
|
||||
后台超时和匹配异常都按失败处理,不写记录、释放名额,下次重新匹配。
|
||||
"""
|
||||
calls = []
|
||||
|
||||
async def match(query: MediaMappingMatchQuery) -> MediaMapping:
|
||||
"""
|
||||
第一次永不返回,第二次抛出异常,第三次正常返回。
|
||||
"""
|
||||
calls.append(query)
|
||||
if len(calls) == 1:
|
||||
await asyncio.Event().wait()
|
||||
if len(calls) == 2:
|
||||
raise RuntimeError("插件转换异常")
|
||||
return found(query)
|
||||
log = Mock()
|
||||
monkeypatch.setattr(lookup_module, "logger", log)
|
||||
monkeypatch.setattr(lookup_module, "MATCH_TIMEOUT", 0.02)
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
两次失败后第三次得到结论。
|
||||
"""
|
||||
lookup = MediaMappingLookup(match, port=lambda: None, tasks=TaskRegistry)
|
||||
for _ in range(2):
|
||||
with pytest.raises(MediaMappingLookupFailed):
|
||||
await lookup.lookup(match_query())
|
||||
assert not lookup._flights
|
||||
assert not lookup._records
|
||||
assert await lookup.lookup(match_query()) == found(match_query())
|
||||
asyncio.run(run())
|
||||
assert "超时" in log.warning.call_args.args[0]
|
||||
assert "插件转换异常" in log.error.call_args.args[0]
|
||||
|
||||
|
||||
def test_matcher_own_timeout_is_logged_as_failure_with_cause(monkeypatch) -> None:
|
||||
"""
|
||||
匹配内部自行抛出的超时不是总预算到期,按失败记录原始原因,不冒充 180 秒超时。
|
||||
"""
|
||||
log = Mock()
|
||||
monkeypatch.setattr(lookup_module, "logger", log)
|
||||
matcher = AsyncMock(side_effect=TimeoutError("上游转换超时"))
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
失败不写记录,日志保留原始异常。
|
||||
"""
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=TaskRegistry)
|
||||
with pytest.raises(MediaMappingLookupFailed):
|
||||
await lookup.lookup(match_query())
|
||||
assert not lookup._records
|
||||
asyncio.run(run())
|
||||
log.warning.assert_not_called()
|
||||
assert "上游转换超时" in log.error.call_args.args[0]
|
||||
|
||||
|
||||
def test_conclusion_logs_describe_entry(monkeypatch) -> None:
|
||||
"""
|
||||
每次后台查找结束只打一行结论日志,命中本地记录时不再记录。
|
||||
"""
|
||||
log = Mock()
|
||||
monkeypatch.setattr(lookup_module, "logger", log)
|
||||
movie = match_query(type="movie", season=None)
|
||||
matcher = AsyncMock(side_effect=[found(match_query()), None])
|
||||
|
||||
async def run() -> None:
|
||||
"""
|
||||
找到与没找到各一次,再次读取记录不追加日志。
|
||||
"""
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: None, tasks=TaskRegistry)
|
||||
await lookup.lookup(match_query())
|
||||
await lookup.lookup(movie)
|
||||
await lookup.lookup(movie)
|
||||
asyncio.run(run())
|
||||
assert [call.args[0] for call in log.info.call_args_list] == [
|
||||
"详情页查找 TMDB 链接:douban:1001(电视剧 第2季) → 找到 TMDB tv/456 第2季",
|
||||
"详情页查找 TMDB 链接:douban:1001(电影) → 未找到",
|
||||
]
|
||||
|
||||
|
||||
def test_lookup_reads_shared_client_cache_written_by_detail_query(monkeypatch) -> None:
|
||||
"""
|
||||
查找请求与详情页 GET 使用同一共享客户端缓存键,命中时不匹配。
|
||||
"""
|
||||
config = {"MP_SERVER_HOST": "https://center.example", "MEDIA_RECOGNIZE_SHARE": True, "PROXY": None}
|
||||
monkeypatch.setattr(transport, "get_runtime_setting", config.get)
|
||||
client = transport.MediaMappingClient()
|
||||
query = match_query()
|
||||
url = client._url()
|
||||
assert url is not None
|
||||
with client._lock:
|
||||
client._remember(client._key(url, MediaMappingQuery(**query.model_dump())), found(query), transport.POSITIVE_TTL)
|
||||
matcher = AsyncMock()
|
||||
lookup = MediaMappingLookup(matcher, port=lambda: client, tasks=TaskRegistry)
|
||||
assert asyncio.run(lookup.lookup(query)) == found(query)
|
||||
matcher.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("query", "result"),
|
||||
[
|
||||
(match_query(type="movie", season=None), {"id": 456, "media_type": MediaType.MOVIE}),
|
||||
(match_query(), {"id": 456, "media_type": MediaType.TV, "season": 1}),
|
||||
(match_query(media_source=MediaSource.Bangumi, media_id="88", season=None),
|
||||
{"id": 456, "media_type": MediaType.TV, "season": 1}),
|
||||
(match_query(media_source=MediaSource.AniList, media_id="99", season=None),
|
||||
{"id": 456, "media_type": MediaType.TV, "season": 0}),
|
||||
],
|
||||
)
|
||||
def test_chain_match_reuses_conversion_and_returns_shared_relation(monkeypatch, query, result) -> None:
|
||||
"""
|
||||
Chain 方法复用订阅同款转换,返回值与本次上报的关系逐字段一致。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
convert = AsyncMock(return_value=result)
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection", convert)
|
||||
actual = asyncio.run(MediaChain.async_match_media_mapping(SimpleNamespace(), query))
|
||||
assert actual is not None
|
||||
assert actual == port.share.call_args.args[0]
|
||||
assert actual.model_dump(include={"media_source", "media_id", "type", "season"}) == query.model_dump()
|
||||
assert actual.tmdb_id == 456
|
||||
convert.assert_awaited_once()
|
||||
|
||||
|
||||
def test_chain_match_supports_plugin_source_through_conversion_event() -> None:
|
||||
"""
|
||||
插件来源与订阅一致,通过转换事件得到 TMDB 详情并写回共享表。
|
||||
"""
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
|
||||
async def send(_etype, data):
|
||||
"""
|
||||
模拟插件填充 TMDB 详情。
|
||||
"""
|
||||
data.media_dict = {"id": 789, "media_type": MediaType.MOVIE}
|
||||
return SimpleNamespace(event_data=data)
|
||||
owner = SimpleNamespace(eventmanager=SimpleNamespace(async_send_event=AsyncMock(side_effect=send)))
|
||||
query = match_query(media_source=MediaSource("examplesource"), media_id="abc", type="movie", season=None)
|
||||
actual = asyncio.run(MediaChain.async_match_media_mapping(owner, query))
|
||||
assert actual == found(query, tmdb_id=789)
|
||||
assert port.share.call_args.args[0] == actual
|
||||
|
||||
|
||||
@pytest.mark.parametrize("result", [None, {"id": 0, "media_type": MediaType.TV}, {"id": 789, "media_type": "music"}])
|
||||
def test_chain_match_returns_none_without_valid_identity(monkeypatch, result) -> None:
|
||||
"""
|
||||
转换没有结果或结果缺少有效 TMDB 身份时返回 None,也不写回共享表。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection", AsyncMock(return_value=result))
|
||||
assert asyncio.run(MediaChain.async_match_media_mapping(SimpleNamespace(), match_query())) is None
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("seasons", "listed"),
|
||||
[
|
||||
([{"season_number": 0}, {"season_number": 1}], False),
|
||||
([{"season_number": 1}, {"season_number": 2}], True),
|
||||
],
|
||||
)
|
||||
def test_chain_match_returns_season_only_when_tmdb_lists_it(monkeypatch, seasons, listed) -> None:
|
||||
"""
|
||||
季匹配回退到整剧名称时转换仍附带请求的季号;TMDB 详情未列出该季则不返回也不上报。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
result = {"id": 456, "media_type": MediaType.TV, "season": 2, "seasons": seasons}
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection", AsyncMock(return_value=result))
|
||||
actual = asyncio.run(MediaChain.async_match_media_mapping(SimpleNamespace(), match_query()))
|
||||
assert actual == (found(match_query()) if listed else None)
|
||||
assert port.share.called is listed
|
||||
|
||||
|
||||
def test_chain_match_rejects_unsupported_identity_without_conversion(monkeypatch) -> None:
|
||||
"""
|
||||
来源 ID 不符合转换规则时直接返回 None,不进入转换,也不写回共享表。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
convert = AsyncMock()
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection", convert)
|
||||
query = match_query(media_source=MediaSource.Bangumi, media_id="not-a-number", season=None)
|
||||
assert asyncio.run(MediaChain.async_match_media_mapping(SimpleNamespace(), query)) is None
|
||||
convert.assert_not_awaited()
|
||||
port.async_query.assert_not_awaited()
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
def test_chain_match_still_returns_relation_when_sharing_disabled(monkeypatch) -> None:
|
||||
"""
|
||||
共享端口未装配时仍返回本次转换结果,只是不查询也不上报。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
configure_media_mapping_port(None)
|
||||
monkeypatch.setattr(
|
||||
projection, "_async_convert_builtin_projection",
|
||||
AsyncMock(return_value={"id": 456, "media_type": MediaType.TV, "season": 2}),
|
||||
)
|
||||
assert asyncio.run(MediaChain.async_match_media_mapping(SimpleNamespace(), match_query())) == found(match_query())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def match_api(monkeypatch) -> Iterator[SimpleNamespace]:
|
||||
"""
|
||||
只挂载媒体路由并替换认证与协调对象,检验参数校验和错误翻译。
|
||||
|
||||
:param monkeypatch: 用例结束后恢复协调对象读取的 pytest 夹具
|
||||
:yields: HTTP 客户端与协调对象替身
|
||||
"""
|
||||
stub = SimpleNamespace(lookup=AsyncMock(return_value=found(match_query())))
|
||||
monkeypatch.setattr(endpoint, "get_media_mapping_lookup", lambda: stub)
|
||||
app = FastAPI()
|
||||
app.include_router(endpoint.router, prefix="/api/v1/media")
|
||||
app.dependency_overrides[endpoint.get_current_active_user_async] = lambda: SimpleNamespace(is_active=True)
|
||||
with TestClient(app) as client:
|
||||
yield SimpleNamespace(client=client, stub=stub, app=app)
|
||||
|
||||
|
||||
def test_match_endpoint_returns_unified_response(match_api) -> None:
|
||||
"""
|
||||
正常结果使用统一响应格式,请求体按查找模型校验后传给协调对象。
|
||||
"""
|
||||
body = {"media_source": "douban", "media_id": "1001", "type": "tv", "season": 2}
|
||||
response = match_api.client.post("/api/v1/media/mapping/match", json=body)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data"] == found(match_query()).model_dump(mode="json")
|
||||
assert match_api.stub.lookup.await_args.args[0] == match_query()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"media_source": "douban", "media_id": "1001"},
|
||||
{"media_source": "douban", "media_id": "1001", "type": "movie", "season": 1},
|
||||
{"media_source": "themoviedb", "media_id": "1001", "type": "tv"},
|
||||
{"media_source": "douban", "media_id": "1001", "type": "tv", "extra": 1},
|
||||
],
|
||||
)
|
||||
def test_match_endpoint_rejects_invalid_body(match_api, body) -> None:
|
||||
"""
|
||||
缺少类型、电影带季号、TMDB 来源或多余字段都在进入协调对象前被拒绝。
|
||||
"""
|
||||
response = match_api.client.post("/api/v1/media/mapping/match", json=body)
|
||||
assert response.status_code == 422
|
||||
match_api.stub.lookup.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "status"),
|
||||
[(MediaMappingLookupBusy(), 429), (MediaMappingLookupFailed(), 502), (MediaMappingLookupUnavailable(), 503)],
|
||||
)
|
||||
def test_match_endpoint_translates_lookup_errors(match_api, error, status) -> None:
|
||||
"""
|
||||
协调对象的已满、失败和不可用分别翻译为 429、502 和 503。
|
||||
"""
|
||||
match_api.stub.lookup.side_effect = error
|
||||
response = match_api.client.post("/api/v1/media/mapping/match",
|
||||
json={"media_source": "douban", "media_id": "1001", "type": "tv"})
|
||||
assert response.status_code == status
|
||||
|
||||
|
||||
def test_match_endpoint_requires_assembled_lookup(match_api, monkeypatch) -> None:
|
||||
"""
|
||||
协调对象未装配时返回 503。
|
||||
"""
|
||||
monkeypatch.setattr(endpoint, "get_media_mapping_lookup", lambda: None)
|
||||
response = match_api.client.post("/api/v1/media/mapping/match",
|
||||
json={"media_source": "douban", "media_id": "1001", "type": "tv"})
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_match_endpoint_requires_same_authentication_as_lookup_endpoint() -> None:
|
||||
"""
|
||||
按需查找与只读查询使用同一登录用户依赖,未登录请求不会进入协调对象。
|
||||
"""
|
||||
def dependencies(path: str, method: str) -> set:
|
||||
"""
|
||||
读取指定路由声明的直接依赖。
|
||||
"""
|
||||
route = next(item for item in endpoint.router.routes
|
||||
if getattr(item, "path", "") == path and method in getattr(item, "methods", set()))
|
||||
return {dependency.call for dependency in route.dependant.dependencies}
|
||||
|
||||
assert endpoint.get_current_active_user_async in dependencies("/mapping/match", "POST")
|
||||
assert endpoint.get_current_active_user_async in dependencies("/mapping", "GET")
|
||||
Reference in New Issue
Block a user