From 46a3c8abeff71ccb5172b6de6ad381577e1219c3 Mon Sep 17 00:00:00 2001 From: ranzhigg <126594517+ranzhigg@users.noreply.github.com> Date: Fri, 4 Sep 2026 09:56:54 +0800 Subject: [PATCH 1/8] ci(sync): merge upstream nightly with failure reports Co-authored-by: Codex --- .github/scripts/sync-upstream.sh | 34 ++++++++++++ .github/workflows/fork-upstream-sync.yml | 69 ++++++++++++++++++++++++ docs/development-setup.md | 4 ++ docs/fork-upstream-sync.md | 13 +++++ 4 files changed, 120 insertions(+) create mode 100644 .github/scripts/sync-upstream.sh create mode 100644 .github/workflows/fork-upstream-sync.yml create mode 100644 docs/fork-upstream-sync.md diff --git a/.github/scripts/sync-upstream.sh b/.github/scripts/sync-upstream.sh new file mode 100644 index 000000000..fc1424f86 --- /dev/null +++ b/.github/scripts/sync-upstream.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail +report="$RUNNER_TEMP/upstream-sync-report.md" +printf '# 上游同步清单\n\n' > "$report" +git config user.name 'github-actions[bot]' +git config user.email '41898282+github-actions[bot]@users.noreply.github.com' +git fetch --no-tags https://github.com/jxxghp/MoviePilot.git v3 +upstream=$(git rev-parse FETCH_HEAD) +base=$(git merge-base HEAD "$upstream") +echo "上游提交:$upstream" >> "$report" +git log --format='- %h %s' HEAD.."$upstream" >> "$report" +if git merge-base --is-ancestor "$upstream" HEAD; then + echo '没有上游更新。' >> "$report" + echo 'changed=false' >> "$GITHUB_OUTPUT" + exit 0 +fi +# 双方修改同一文件时交给人工处理,避免自动合并悄悄改变定制行为 +git diff --name-only "$base" HEAD | sort > "$RUNNER_TEMP/fork-paths" +git diff --name-only "$base" "$upstream" | sort > "$RUNNER_TEMP/upstream-paths" +comm -12 "$RUNNER_TEMP/fork-paths" "$RUNNER_TEMP/upstream-paths" > "$RUNNER_TEMP/overlap" +if [ -s "$RUNNER_TEMP/overlap" ]; then + echo '需要人工审阅:上游与 fork 同时修改以下文件,未推送:' >> "$report" + cat "$RUNNER_TEMP/overlap" >> "$report" + exit 1 +fi +if ! git merge --no-ff --no-edit "$upstream"; then + echo '合并冲突,未推送:' >> "$report" + git diff --name-only --diff-filter=U >> "$report" + git merge --abort + exit 1 +fi +git diff --check HEAD^ HEAD +echo 'changed=true' >> "$GITHUB_OUTPUT" +echo '合并完成,等待验证。' >> "$report" diff --git a/.github/workflows/fork-upstream-sync.yml b/.github/workflows/fork-upstream-sync.yml new file mode 100644 index 000000000..655afc412 --- /dev/null +++ b/.github/workflows/fork-upstream-sync.yml @@ -0,0 +1,69 @@ +name: Fork upstream sync +on: + schedule: + - cron: '0 15 * * *' + workflow_dispatch: +permissions: + contents: write + issues: write +concurrency: + group: fork-upstream-sync + cancel-in-progress: false +jobs: + sync: + if: github.repository == 'ranzhigg/MoviePilot' + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7 + with: + ref: v3 + fetch-depth: 0 + - name: Merge upstream conservatively + id: merge + run: bash .github/scripts/sync-upstream.sh + - name: Set up uv + if: steps.merge.outputs.changed == 'true' + uses: astral-sh/setup-uv@v10.0.1 + with: + python-version: '3.14' + - name: Verify merged MoviePilot + if: steps.merge.outputs.changed == 'true' + run: | + uv sync --locked + uv run --locked --no-sync python tests/run.py + - name: Push verified merge + if: steps.merge.outputs.changed == 'true' + run: | + git push origin HEAD:v3 + echo '验证通过,已推送;没有更新本地 MP,也没有自动发布插件安装包。' >> "$RUNNER_TEMP/upstream-sync-report.md" + - name: Record failure + if: failure() + run: | + echo '同步失败:请查看失败步骤。主分支不会收到未通过验证的合并。' >> "$RUNNER_TEMP/upstream-sync-report.md" + - name: Publish run summary + if: always() + run: | + test -f "$RUNNER_TEMP/upstream-sync-report.md" || echo '工作流未完成初始化,请查看日志。' > "$RUNNER_TEMP/upstream-sync-report.md" + cat "$RUNNER_TEMP/upstream-sync-report.md" >> "$GITHUB_STEP_SUMMARY" + - name: Save report + if: always() + uses: actions/upload-artifact@v4 + with: + name: upstream-sync-report + path: ${{ runner.temp }}/upstream-sync-report.md + retention-days: 30 + - name: Report failure as issue + if: failure() + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + printf '\n运行日志:%s\n' "$RUN_URL" >> "$RUNNER_TEMP/upstream-sync-report.md" + issue=$(gh issue list --state open --search '"上游同步失败" in:title' --json number --jq '.[0].number // empty') + if [ -n "$issue" ]; then + gh issue comment "$issue" --body-file "$RUNNER_TEMP/upstream-sync-report.md" + else + gh issue create --title '上游同步失败:需要检查' --body-file "$RUNNER_TEMP/upstream-sync-report.md" + fi diff --git a/docs/development-setup.md b/docs/development-setup.md index de635ce8d..569144df8 100644 --- a/docs/development-setup.md +++ b/docs/development-setup.md @@ -241,3 +241,7 @@ Docker 镜像发布前还会使用 Trivy 扫描 OS 与语言包;根目录 `.tr - [pip-audit](https://github.com/pypa/pip-audit) - [MoviePilot-Resources](https://github.com/jxxghp/MoviePilot-Resources) - [MoviePilot-Plugins](https://github.com/jxxghp/MoviePilot-Plugins) + +## 个人 fork 同步 + +定时合并和失败通知见 [Fork 上游同步](fork-upstream-sync.md)。 diff --git a/docs/fork-upstream-sync.md b/docs/fork-upstream-sync.md new file mode 100644 index 000000000..7ab76aa0e --- /dev/null +++ b/docs/fork-upstream-sync.md @@ -0,0 +1,13 @@ +# Fork 上游同步 + +每天北京时间 23:00(UTC 15:00)由 GitHub Actions 检查上游;GitHub 定时任务可能延迟。也可在 Actions → Fork upstream sync 手动运行。 + +使用普通合并,保留 fork 提交;双方改动同一文件时暂停人工审阅,不采用 ours/theirs 或强制覆盖。合并、校验或推送失败时工作流失败,生成日志、30 天报告附件,并创建或更新失败 Issue。每次运行的 Summary 展示上游提交清单及结果。失败不自动回滚已有提交,不修改本地 MP。 + +推送使用 GITHUB_TOKEN,合并推送不会自动触发其他 push 工作流或插件发布;插件发布及本地安装需要另行执行。验证仅覆盖工作流列出的检查,不保证所有外部服务或第三方插件兼容。 + +## GitHub 自带失败邮件 + +仓库代码无法修改账号的邮件通知偏好。在 GitHub Settings → Notifications → System → Actions,启用 Email 并选择仅失败通知;确保该仓库通知路由使用已验证的 `ranzhigg@gmail.com`。首次用自己的账号手动运行本工作流,并检查失败邮件偏好。未开启账号通知前,工作流无法保证邮件送达,也不能从仓库设置强制收件人。 + +不需要 SMTP 密钥。失败 Issue 和 Actions 日志始终作为反馈入口,修复后可手动重跑;失败 Issue 由人工确认后关闭。 From 06240d129d1d8eadb6758e01a62cbcff2183bf41 Mon Sep 17 00:00:00 2001 From: ranzhigg <126594517+ranzhigg@users.noreply.github.com> Date: Fri, 4 Sep 2026 10:26:54 +0800 Subject: [PATCH 2/8] fix(ci): align sync reports with artifact policy Co-authored-by: Codex --- .github/workflows/fork-upstream-sync.yml | 2 +- tests/test_architecture_ci.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/fork-upstream-sync.yml b/.github/workflows/fork-upstream-sync.yml index 655afc412..347e68c99 100644 --- a/.github/workflows/fork-upstream-sync.yml +++ b/.github/workflows/fork-upstream-sync.yml @@ -48,7 +48,7 @@ jobs: cat "$RUNNER_TEMP/upstream-sync-report.md" >> "$GITHUB_STEP_SUMMARY" - name: Save report if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: upstream-sync-report path: ${{ runner.temp }}/upstream-sync-report.md diff --git a/tests/test_architecture_ci.py b/tests/test_architecture_ci.py index 7421ec815..c4d2f8fe0 100644 --- a/tests/test_architecture_ci.py +++ b/tests/test_architecture_ci.py @@ -206,6 +206,7 @@ def test_upload_artifact_actions_share_node24_major(): assert actions_by_workflow == { "architecture-observe.yml": ["actions/upload-artifact@v7"], + "fork-upstream-sync.yml": ["actions/upload-artifact@v7"], "native-dependency-update.yml": ["actions/upload-artifact@v7"], "pylint.yml": ["actions/upload-artifact@v7"], "site-adapter-collector.yml": ["actions/upload-artifact@v7"], From 053de2b14ed9c8d4ab86f3cb147502ebbe050a65 Mon Sep 17 00:00:00 2001 From: ranzhigg Date: Tue, 8 Sep 2026 20:46:43 +0800 Subject: [PATCH 3/8] fix: restore Python 3 exception syntax --- app/api/endpoints/media.py | 2 +- app/application/plugin/data.py | 2 +- app/domain/classification/facts.py | 2 +- app/modules/musicbrainz/__init__.py | 2 +- app/modules/themoviedb/__init__.py | 2 +- app/runtime/extensions/module/contracts.py | 2 +- app/startup/composition/enrichment.py | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/api/endpoints/media.py b/app/api/endpoints/media.py index 641bab50f..f5da8d053 100644 --- a/app/api/endpoints/media.py +++ b/app/api/endpoints/media.py @@ -116,7 +116,7 @@ def _is_valid_source_media_id( try: UUID(normalized_media_id) return True - except TypeError, ValueError: + except (TypeError, ValueError): return False if normalized_source == MediaSource.DoubanMusic and ":" in normalized_media_id: album_id, track_number = normalized_media_id.split(":", 1) diff --git a/app/application/plugin/data.py b/app/application/plugin/data.py index 651349e7f..557813a41 100644 --- a/app/application/plugin/data.py +++ b/app/application/plugin/data.py @@ -169,7 +169,7 @@ def plugin_data_serialized_chars(value: JsonData) -> Optional[int]: """计算合法 JSON 值的紧凑字符数,异常对象不执行自定义字符串化。""" try: return len(json.dumps(value, ensure_ascii=False, separators=(",", ":"))) - except TypeError, ValueError: + except (TypeError, ValueError): return None diff --git a/app/domain/classification/facts.py b/app/domain/classification/facts.py index 8301829af..bbd2ca4f6 100644 --- a/app/domain/classification/facts.py +++ b/app/domain/classification/facts.py @@ -231,7 +231,7 @@ def _optional_int(value: object) -> int | None: return None try: return int(str(value)) - except TypeError, ValueError: + except (TypeError, ValueError): return None diff --git a/app/modules/musicbrainz/__init__.py b/app/modules/musicbrainz/__init__.py index c665f649e..d46f3ff5c 100644 --- a/app/modules/musicbrainz/__init__.py +++ b/app/modules/musicbrainz/__init__.py @@ -831,7 +831,7 @@ class MusicBrainzModule(_ModuleBase): """相关度每五分成组,组内应用发行偏好并保留原始得分。""" try: score = int(release.get("score") or 0) - except TypeError, ValueError: + except (TypeError, ValueError): score = 0 region_rank, script_rank = cls._release_preference_sort_key( release, diff --git a/app/modules/themoviedb/__init__.py b/app/modules/themoviedb/__init__.py index 2f5fc6a5e..8671459a5 100644 --- a/app/modules/themoviedb/__init__.py +++ b/app/modules/themoviedb/__init__.py @@ -164,7 +164,7 @@ class TheMovieDbModule(MediaAuxiliaryProviderMixin, _ModuleBase): try: tmdb_id = int(raw_tmdb_id) media_type = MediaType(request.media_type) - except TypeError, ValueError: + except (TypeError, ValueError): return None info = self.tmdb_info(tmdbid=tmdb_id, mtype=media_type) if not info: diff --git a/app/runtime/extensions/module/contracts.py b/app/runtime/extensions/module/contracts.py index 0caf0ec5d..835819d0a 100644 --- a/app/runtime/extensions/module/contracts.py +++ b/app/runtime/extensions/module/contracts.py @@ -1809,7 +1809,7 @@ def diagnose_module_callable(method: str, callback: Callable[..., Any]) -> tuple return () try: parameters = inspect.signature(callback).parameters - except TypeError, ValueError: + except (TypeError, ValueError): return ("signature-unavailable",) missing = tuple( name diff --git a/app/startup/composition/enrichment.py b/app/startup/composition/enrichment.py index 8773eba94..7dd6a8b93 100644 --- a/app/startup/composition/enrichment.py +++ b/app/startup/composition/enrichment.py @@ -120,7 +120,7 @@ class RuntimeClassificationEnrichmentCache: return ClassificationEnrichmentCacheEntry(response=None) try: response = ClassificationEnrichmentResponse.model_validate(value.get("response")) - except TypeError, ValidationError: + except (TypeError, ValidationError): return None return ClassificationEnrichmentCacheEntry(response=response) From 56cf6fefe0e846c03de2d608b74447db19ed152f Mon Sep 17 00:00:00 2001 From: ranzhigg <126594517+ranzhigg@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:45:31 +0800 Subject: [PATCH 4/8] perf(transfer): bound queue snapshots for batch imports --- app/api/endpoints/transfer.py | 6 +- app/api/endpoints/transferqueue.py | 29 +++++ app/api/routers.py | 2 + app/application/transfer/jobs.py | 102 ++++++++++++++++-- app/application/transfer/workflow.py | 20 ++++ app/chain/transfer/queue.py | 7 +- app/schemas/exports.py | 5 + app/schemas/transfer.py | 47 +++++++++ docs/refactor/agent-api-surface-audit.json | 16 ++- docs/refactor/agent-api-surface-audit.md | 5 +- scripts/generate_agent_api_surface_audit.py | 1 + tests/test_transfer_queue_paging.py | 111 ++++++++++++++++++++ 12 files changed, 334 insertions(+), 17 deletions(-) create mode 100644 app/api/endpoints/transferqueue.py create mode 100644 tests/test_transfer_queue_paging.py diff --git a/app/api/endpoints/transfer.py b/app/api/endpoints/transfer.py index afe96a07d..779bac329 100644 --- a/app/api/endpoints/transfer.py +++ b/app/api/endpoints/transfer.py @@ -11,11 +11,7 @@ from app.api.endpoints.transferhistory import ( restore_manual_transfer_history_batch, restore_manual_transfer_history_metadata, ) -from app.api.response import ( - CompatibleCountParam, - CompatiblePageParam, - ResponseAPIRouter, -) +from app.api.response import CompatibleCountParam, CompatiblePageParam, ResponseAPIRouter from app.application.configuration import get_api_runtime_config_snapshot from app.application.directory import DirectoryHelper from app.application.history import TransferHistoryLookupService diff --git a/app/api/endpoints/transferqueue.py b/app/api/endpoints/transferqueue.py new file mode 100644 index 000000000..397aa4740 --- /dev/null +++ b/app/api/endpoints/transferqueue.py @@ -0,0 +1,29 @@ +from fastapi import Depends, Query + +from app.adapters.web.security.access import verify_token +from app.api.response import COLLECTION_MAX_PAGE_SIZE, ResponseAPIRouter +from app.chain.transfer.facade import TransferChain +from app.schemas.token import TokenPayload as _SchemaTokenPayload +from app.schemas.transfer import TransferQueuePageData as _SchemaTransferQueuePageData + +router = ResponseAPIRouter() + + +@router.get( # type: ignore[misc] + "/queue/page", + summary="查询受限整理队列快照", + response_model=_SchemaTransferQueuePageData, +) +async def query_queue_page( + _: _SchemaTokenPayload = Depends(verify_token), + page: int = Query(1, ge=1), + count: int = Query(100, ge=1, le=COLLECTION_MAX_PAGE_SIZE), +) -> _SchemaTransferQueuePageData: + """返回前端所需的有限整理队列窗口,避免全量队列阻塞接口序列化。""" + items, total = TransferChain().get_queue_tasks_page(page, count) + return _SchemaTransferQueuePageData( + items=items, + total=total, + page=page, + count=count, + ) diff --git a/app/api/routers.py b/app/api/routers.py index d1a154cb8..a2e915820 100644 --- a/app/api/routers.py +++ b/app/api/routers.py @@ -41,6 +41,7 @@ from app.api.endpoints import ( tmdb, torrent, transfer, + transferqueue, user, webhook, workflow, @@ -88,6 +89,7 @@ API_V1_ROUTER_SPECS: tuple[RouterSpec, ...] = ( RouterSpec(dashboard.router, "/dashboard", ("dashboard",)), RouterSpec(storage.router, "/storage", ("storage",)), RouterSpec(transfer.router, "/transfer", ("transfer",)), + RouterSpec(transferqueue.router, "/transfer", ("transfer",)), RouterSpec(mediaserver.router, "/mediaserver", ("mediaserver",)), RouterSpec(bangumi.router, "/bangumi", ("bangumi",)), RouterSpec(anilist.router, "/anilist", ("anilist",)), diff --git a/app/application/transfer/jobs.py b/app/application/transfer/jobs.py index b8d6de88f..8b5094aaa 100644 --- a/app/application/transfer/jobs.py +++ b/app/application/transfer/jobs.py @@ -26,7 +26,14 @@ from app.schemas.file import FileItem from app.schemas.media import resolve_media_identity from app.schemas.music import MusicInfo as _SchemaMusicInfo from app.schemas.music import MusicMeta as _SchemaMusicMeta -from app.schemas.transfer import TransferJob, TransferJobTask +from app.schemas.transfer import ( + TransferJob, + TransferJobTask, + TransferQueueFileItemData, + TransferQueueItemData, + TransferQueueMediaData, + TransferQueueTaskData, +) from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaType if TYPE_CHECKING: @@ -68,6 +75,44 @@ def _job_task_fileitem(task: TransferJobTask) -> FileItem: return cast(FileItem, task.fileitem) +def _queue_media_snapshot(media: Optional[Union[MediaInfo, MusicInfo]]) -> Optional[TransferQueueMediaData]: + """只复制整理队列页面会展示的媒体字段,避免重复输出完整刮削结果。""" + if not media: + return TransferQueueMediaData() + media_id = getattr(media, "media_id", None) + year = getattr(media, "year", None) + media_source = getattr(media, "media_source", None) + return TransferQueueMediaData( + media_source=getattr(media_source, "value", media_source), + media_id=str(media_id) if media_id is not None else None, + title=getattr(media, "title", None), + title_year=getattr(media, "title_year", None), + year=str(year) if year is not None else None, + poster_path=getattr(media, "poster_path", None), + episode_run_time=getattr(media, "episode_run_time", None) or [], + origin_country=getattr(media, "origin_country", None) or [], + ) + + +def _queue_fileitem_snapshot(fileitem: FileItem) -> TransferQueueFileItemData: + """保留 path/storage 以支持取消任务,其余只保留官方队列 UI 所需字段。""" + return TransferQueueFileItemData( + path=fileitem.path, + storage=fileitem.storage, + type=fileitem.type, + name=fileitem.name, + size=fileitem.size, + ) + + +def _queue_task_snapshot(task: TransferJobTask) -> TransferQueueTaskData: + """构造不含识别元数据和云盘目录树的轻量任务投影。""" + return TransferQueueTaskData( + fileitem=_queue_fileitem_snapshot(_job_task_fileitem(task)), + state=task.state, + ) + + def _job_task_size(task: TransferJobTask) -> int: """按既有本地目录回退规则返回已完成任务的文件大小。""" fileitem = _job_task_fileitem(task) @@ -80,6 +125,49 @@ def _job_task_size(task: TransferJobTask) -> int: return 0 +def _list_jobs_page( + jobs: Dict[JobId, TransferJob], + page: int, + count: int, + total_hint: Optional[int] = None, +) -> Tuple[List[TransferQueueItemData], int]: + """按扁平任务窗口构造轻量队列视图。""" + if page < 1 or count < 1: + raise ValueError("队列分页参数必须为正数") + + start = (page - 1) * count + end = start + count + selected: List[TransferQueueItemData] = [] + total = 0 + + for job in jobs.values(): + tasks = _job_tasks(job) + job_start = total + total += len(tasks) + if job_start >= end: + if total_hint is not None: + break + continue + if total <= start: + continue + + task_start = max(0, start - job_start) + task_end = min(len(tasks), end - job_start) + if task_start < task_end: + selected.append( + TransferQueueItemData( + media=_queue_media_snapshot(job.media), + season=job.season, + tasks=[ + _queue_task_snapshot(task) + for task in tasks[task_start:task_end] + ], + ) + ) + + return selected, total_hint if total_hint is not None else total + + job_lock = threading.Lock() @@ -99,7 +187,6 @@ class JobManager: _task_state_changed_at: Dict[FileKey, float] = {} # 记录仍由主程序整理线程直接执行的任务,避免把阻塞中的本地任务误判为失活 _active_executions: set[FileKey] = set() - def __init__(self) -> None: """初始化当前进程内的整理作业状态。""" self._job_view = {} @@ -247,11 +334,7 @@ class JobManager: with job_lock: __mediaid__ = self.__get_id(task) # 同一个源文件可能在识别前后落入不同作业,必须跨作业去重。 - if any( - self.__get_file_key(_job_task_fileitem(t)) == file_key - for job in self._job_view.values() - for t in _job_tasks(job) - ): + if file_key in self._task_state_changed_at: logger.debug(f"任务 {task.fileitem.name} 已存在,跳过重复添加") return False if __mediaid__ not in self._job_view: @@ -828,6 +911,11 @@ class JobManager: with job_lock: return list(self._job_view.values()) + def list_jobs_page(self, page: int, count: int) -> Tuple[List[TransferQueueItemData], int]: + """返回轻量队列窗口,避免复制云盘目录树和识别元数据。""" + with job_lock: + return _list_jobs_page(self._job_view, page, count, len(self._task_state_changed_at) or None) + def season_episodes( self, media: Union[MediaInfo, MusicInfo], season: Optional[int] = None ) -> List[int]: diff --git a/app/application/transfer/workflow.py b/app/application/transfer/workflow.py index ec6cf29c8..d467847f2 100644 --- a/app/application/transfer/workflow.py +++ b/app/application/transfer/workflow.py @@ -14,8 +14,11 @@ TransferJob / TransferJobTask,那两个用 app.schemas 的同名 DTO——一 视图,分开表达之后两边都不必再迁就对方。 """ from typing import ( + Any, Callable, List, + Optional, + Tuple, ) from app.application.transfer.feedback import TransferFailureNotification @@ -102,6 +105,9 @@ class TransferQueueService: remove_task: Callable[[FileItem], None], list_tasks: Callable[[], List[TransferJob]], expire_tasks: Callable[[], None], + list_tasks_page: Optional[ + Callable[[int, int], Tuple[List[Any], int]] + ] = None, ) -> None: """保存队列用例依赖,避免 Application 服务绑定具体线程队列实现。""" self._register_task = register_task @@ -112,6 +118,7 @@ class TransferQueueService: self._remove_task = remove_task self._list_tasks = list_tasks self._expire_tasks = expire_tasks + self._list_tasks_page = list_tasks_page def put(self, task: TransferTask, callback: TransferCallback) -> bool: """先持久化准入事实再入队;任何前置失败都撤销内存作业视图。""" @@ -143,3 +150,16 @@ class TransferQueueService: """先处理失活任务,再返回当前整理作业视图。""" self._expire_tasks() return self._list_tasks() + + def list_page(self, page: int, count: int) -> Tuple[List[Any], int]: + """返回受限队列快照,避免前端请求触发全量 DTO 序列化。""" + if page < 1 or count < 1: + raise ValueError("队列分页参数必须为正数") + + self._expire_tasks() + if self._list_tasks_page is not None: + return self._list_tasks_page(page, count) + + tasks = self._list_tasks() + start = (page - 1) * count + return tasks[start:start + count], len(tasks) diff --git a/app/chain/transfer/queue.py b/app/chain/transfer/queue.py index e6b24b732..b4532a417 100644 --- a/app/chain/transfer/queue.py +++ b/app/chain/transfer/queue.py @@ -42,7 +42,7 @@ from app.runtime.progress import ProgressHelper from app.runtime.stop import runtime_stop_state from app.schemas.system import TransferDirectoryConf from app.schemas.tmdb import TmdbEpisode -from app.schemas.transfer import TransferInfo, TransferJob +from app.schemas.transfer import TransferInfo, TransferJob, TransferQueueItemData from app.schemas.types import ( MediaSource, MediaType, @@ -391,6 +391,7 @@ class TransferQueueOwner(_TransferOwnerBase): remove_task=self.jobview.remove_task, list_tasks=self.jobview.list_jobs, expire_tasks=self._TransferChain__expire_stale_transfer_tasks, + list_tasks_page=self.jobview.list_jobs_page, ) def replay_pending(self) -> None: @@ -1473,6 +1474,10 @@ class TransferQueueOwner(_TransferOwnerBase): """ return self._transfer_queue_service().list() + def get_queue_tasks_page(self, page: int, count: int) -> Tuple[List[TransferQueueItemData], int]: + """获取供前端展示的受限整理队列快照。""" + return self._transfer_queue_service().list_page(page, count) + def process(self, progress_callback: Optional[Callable[..., None]] = None) -> bool: """ 获取下载器中的种子列表,并执行整理 diff --git a/app/schemas/exports.py b/app/schemas/exports.py index a81b124a8..4692de9db 100644 --- a/app/schemas/exports.py +++ b/app/schemas/exports.py @@ -532,6 +532,11 @@ SCHEMA_EXPORTS = { 'TransferManualReviewStepData': ('app.schemas.transfer', 'TransferManualReviewStepData'), 'TransferManualReviewTaskData': ('app.schemas.transfer', 'TransferManualReviewTaskData'), 'TransferOverwriteCheckEventData': ('app.schemas.event', 'TransferOverwriteCheckEventData'), + 'TransferQueueFileItemData': ('app.schemas.transfer', 'TransferQueueFileItemData'), + 'TransferQueueItemData': ('app.schemas.transfer', 'TransferQueueItemData'), + 'TransferQueueMediaData': ('app.schemas.transfer', 'TransferQueueMediaData'), + 'TransferQueuePageData': ('app.schemas.transfer', 'TransferQueuePageData'), + 'TransferQueueTaskData': ('app.schemas.transfer', 'TransferQueueTaskData'), 'TransferRenameBuildEventData': ('app.schemas.event', 'TransferRenameBuildEventData'), 'TransferRenameEventData': ('app.schemas.event', 'TransferRenameEventData'), 'TransferResultContractData': ('app.schemas.event', 'TransferResultContractData'), diff --git a/app/schemas/transfer.py b/app/schemas/transfer.py index 38d49604c..185fd6747 100644 --- a/app/schemas/transfer.py +++ b/app/schemas/transfer.py @@ -113,6 +113,53 @@ class TransferJob(BaseModel): tasks: Optional[List[TransferJobTask]] = Field(default_factory=list) +class TransferQueueFileItemData(BaseModel): # type: ignore[misc] + """整理队列快照只需要的源文件字段,不携带云盘目录树和 provider 扩展字段。""" + + path: Optional[str] = None + storage: Optional[str] = "local" + type: Optional[str] = None + name: Optional[str] = None + size: Optional[int] = None + + +class TransferQueueMediaData(BaseModel): # type: ignore[misc] + """整理队列 UI 所需的媒体身份与海报摘要。""" + + media_source: Optional[str] = None + media_id: Optional[str] = None + title: Optional[str] = None + title_year: Optional[str] = None + year: Optional[str] = None + poster_path: Optional[str] = None + episode_run_time: Optional[List[int]] = Field(default_factory=list) + origin_country: Optional[List[str]] = Field(default_factory=list) + + +class TransferQueueTaskData(BaseModel): # type: ignore[misc] + """整理队列 UI 所需的任务状态与源文件摘要。""" + + fileitem: TransferQueueFileItemData + state: Optional[str] = None + + +class TransferQueueItemData(BaseModel): # type: ignore[misc] + """单个媒体分组的轻量整理队列投影。""" + + media: Optional[TransferQueueMediaData] = None + season: Optional[int] = None + tasks: List[TransferQueueTaskData] = Field(default_factory=list) + + +class TransferQueuePageData(BaseModel): # type: ignore[misc] + """前端整理队列的受限快照。""" + + items: List[TransferQueueItemData] = Field(default_factory=list) + total: int = 0 + page: int = 1 + count: int = 100 + + class TransferInfo(BaseModel): """ 文件整理结果 diff --git a/docs/refactor/agent-api-surface-audit.json b/docs/refactor/agent-api-surface-audit.json index 5c3e1025b..e86eef7d1 100644 --- a/docs/refactor/agent-api-surface-audit.json +++ b/docs/refactor/agent-api-surface-audit.json @@ -6,7 +6,7 @@ "provider-skill": 12, "stream_or_binary": 10, "transport_or_identity": 76, - "ui_presentation": 13 + "ui_presentation": 14 }, "dynamic_gateway_routes": [ { @@ -21,7 +21,7 @@ "gateway_http_route_count": 229, "gateway_operation_count": 231, "matched_gateway_http_route_count": 228, - "openapi_operation_count": 421, + "openapi_operation_count": 422, "operations": [ { "disposition": "consolidated", @@ -5145,6 +5145,18 @@ "transfer" ] }, + { + "disposition": "ui_presentation", + "method": "GET", + "operation_ids": [], + "owner": "host-ui", + "path": "/api/v1/transfer/queue/page", + "reason": "Plugin-rendered page, dashboard, or navigation metadata owned by the frontend presentation contract rather than an Agent business action.", + "summary": "查询受限整理队列快照", + "tags": [ + "transfer" + ] + }, { "disposition": "gateway", "method": "GET", diff --git a/docs/refactor/agent-api-surface-audit.md b/docs/refactor/agent-api-surface-audit.md index 463e0ac78..baf951cca 100644 --- a/docs/refactor/agent-api-surface-audit.md +++ b/docs/refactor/agent-api-surface-audit.md @@ -5,7 +5,7 @@ ## Result -- OpenAPI HTTP operations: **421** +- OpenAPI HTTP operations: **422** - Stable `moviepilot_api` operations: **231** - Exact HTTP routes used by the gateway: **229** - OpenAPI routes matched directly by the gateway: **228** @@ -23,7 +23,7 @@ | `provider-skill` | 12 | Low-level downloader or media-server capability owned by a provider Skill. | | `stream_or_binary` | 10 | Streaming or binary response owned by a direct client transport. | | `transport_or_identity` | 76 | Authentication, protocol, callback, account, or conversation transport boundary. | -| `ui_presentation` | 13 | Frontend or plugin-rendered presentation contract. | +| `ui_presentation` | 14 | Frontend or plugin-rendered presentation contract. | ## Bounded Dynamic Routes @@ -423,6 +423,7 @@ | `GET` | `/api/v1/transfer/now` | transfer | `consolidated` | scheduler.run | 立即执行下载器文件整理 | | `DELETE` | `/api/v1/transfer/queue` | transfer | `gateway` | transfer.queue.delete | 从整理队列中删除任务 | | `GET` | `/api/v1/transfer/queue` | transfer | `gateway` | transfer.queue | 查询整理队列 | +| `GET` | `/api/v1/transfer/queue/page` | transfer | `ui_presentation` | host-ui | 查询受限整理队列快照 | | `GET` | `/api/v1/transfer/tasks/manual-reviews` | transfer | `gateway` | transfer.manual_reviews | 分页查询 durable 整理人工复核任务 | | `GET` | `/api/v1/transfer/tasks/{task_id}/manual-review` | transfer | `gateway` | transfer.manual_review | 查询 durable 整理人工复核详情 | | `POST` | `/api/v1/transfer/tasks/{task_id}/manual-review` | transfer | `gateway` | transfer.manual_review.resolve | 人工判定整理步骤的外部执行结果 | diff --git a/scripts/generate_agent_api_surface_audit.py b/scripts/generate_agent_api_surface_audit.py index c8a8e31b8..f405c741b 100644 --- a/scripts/generate_agent_api_surface_audit.py +++ b/scripts/generate_agent_api_surface_audit.py @@ -104,6 +104,7 @@ UI_PRESENTATION_PATHS = frozenset( "/api/v1/rule/groups/reorder", "/api/v1/storage/catalog", "/api/v1/storage/options", + "/api/v1/transfer/queue/page", } ) EXPLICIT_TRANSPORT_PATHS = frozenset( diff --git a/tests/test_transfer_queue_paging.py b/tests/test_transfer_queue_paging.py new file mode 100644 index 000000000..f8528e81e --- /dev/null +++ b/tests/test_transfer_queue_paging.py @@ -0,0 +1,111 @@ +from unittest.mock import Mock + +import pytest + +from app.application.transfer.jobs import JobManager +from app.application.transfer.workflow import TransferQueueService +from app.schemas.file import FileItem +from app.schemas.transfer import TransferJob, TransferJobTask +from tests.test_transfer_job_manager import make_task + + +def _job(*paths: str) -> TransferJob: + """构造只包含队列分页测试所需字段的整理作业。""" + return TransferJob( + season=1, + tasks=[ + TransferJobTask( + fileitem=FileItem( + name=path.rsplit("/", 1)[-1], + path=path, + size=1, + storage="local", + type="file", + children=[ + FileItem( + name="cloud-child.mkv", + path=f"{path}.child", + size=1, + storage="local", + type="file", + ) + ], + ), + state="waiting", + ) + for path in paths + ], + ) + + +def test_job_manager_page_keeps_flat_order_and_only_projects_the_requested_window(): + """大队列分页必须保持任务顺序,并按窗口复制作业投影。""" + manager = JobManager() + manager._job_view = { + ("first", 1): _job("/downloads/first-1.mkv", "/downloads/first-2.mkv"), + ("second", 1): _job( + "/downloads/second-1.mkv", + "/downloads/second-2.mkv", + "/downloads/second-3.mkv", + ), + } + + first_page, total = manager.list_jobs_page(page=1, count=3) + second_page, second_total = manager.list_jobs_page(page=2, count=3) + + assert total == second_total == 5 + assert [len(job.tasks or []) for job in first_page] == [2, 1] + assert not hasattr(first_page[0].tasks[0].fileitem, "children") + assert [task.fileitem.path for job in first_page for task in job.tasks or []] == [ + "/downloads/first-1.mkv", + "/downloads/first-2.mkv", + "/downloads/second-1.mkv", + ] + assert [task.fileitem.path for job in second_page for task in job.tasks or []] == [ + "/downloads/second-2.mkv", + "/downloads/second-3.mkv", + ] + + +@pytest.mark.parametrize("page,count", [(0, 1), (1, 0), (-1, 10)]) +def test_job_manager_page_rejects_invalid_windows(page: int, count: int): + """分页窗口不接受零或负数,避免异常切片产生隐性全量查询。""" + with pytest.raises(ValueError, match="队列分页参数必须为正数"): + JobManager().list_jobs_page(page, count) + + +def test_transfer_queue_service_uses_bounded_projection_after_expiring_tasks(): + """应用服务先清理失活任务,再调用可选的受限投影依赖。""" + expire_tasks = Mock() + list_tasks_page = Mock(return_value=([_job("/downloads/page.mkv")], 101)) + service = TransferQueueService( + register_task=lambda _task: True, + admit_task=lambda _task: None, + enqueue=lambda _queue: None, + before_enqueue=lambda _task: None, + enqueue_failed=lambda _task, _error: None, + remove_task=lambda _fileitem: None, + list_tasks=lambda: [], + expire_tasks=expire_tasks, + list_tasks_page=list_tasks_page, + ) + + items, total = service.list_page(page=3, count=50) + + assert len(items) == 1 + assert total == 101 + expire_tasks.assert_called_once_with() + list_tasks_page.assert_called_once_with(3, 50) + + +def test_job_manager_duplicate_index_is_released_when_a_cloud_task_is_removed(): + """批量云盘任务的 O(1) 去重索引不能阻止同一源文件后续重新入队。""" + manager = JobManager() + task = make_task(1) + + assert manager.add_task(task) is True + assert manager.add_task(make_task(1)) is False + + manager.remove_task(task.fileitem) + + assert manager.add_task(make_task(1)) is True From fb8f283123fe942eeca04862495a7e57a7f98ea8 Mon Sep 17 00:00:00 2001 From: ranzhigg <126594517+ranzhigg@users.noreply.github.com> Date: Thu, 1 Oct 2026 13:00:46 +0800 Subject: [PATCH 5/8] docs(architecture): sync transfer queue baseline --- docs/architecture-overview.md | 6 +++--- docs/refactor/optimization-checklist.md | 4 ++-- .../architecture/dependency-baseline.json | 20 ++++++++++++++++--- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index d774f9b1d..0f0ecfa90 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -762,8 +762,8 @@ flowchart LR | 指标 | 当前值 | |---|---:| -| Python 模块 | 1091 | -| 内部导入边 | 9,295 | +| Python 模块 | 1105 | +| 内部导入边 | 9,308 | | 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 48(债务已清零,48 条精确 containment) | @@ -773,7 +773,7 @@ flowchart LR | Model/Oper 自动事务与自建 Session | 0 | | 组合根外 `SystemConfigOper()` | 0 | -整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,295,音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 578、`app.factory` 为 591、`app.main` 为 593。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 +整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,308,音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 578、`app.factory` 为 591、`app.main` 为 593。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 架构专项验证分为两个 CI 投影:`Check event semantic policy` 先运行依赖、Adapter、出口和 Event 语义门禁,`Check host architecture snapshot` 再执行快照测试及一次 diff --git a/docs/refactor/optimization-checklist.md b/docs/refactor/optimization-checklist.md index 5d3e54d9f..0d8046689 100644 --- a/docs/refactor/optimization-checklist.md +++ b/docs/refactor/optimization-checklist.md @@ -98,7 +98,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 1104 / 9,295 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 | +| 宿主 Python 模块 / 内部依赖边 | 1105 / 9,308 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 | | 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | @@ -106,7 +106,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | Event Contract | 53 | 均已有 payload model,但当前全部是 diagnostic enforcement | | Python 源码量 | 305,884 行 | 排除 `app/plugins/**`;61 个文件超过 1,000 行,11 个超过 2,000 行 | | 长方法 | 290 个超过 80 行 | AST 统计排除 `app/plugins/**`;65 个超过 150 行,21 个超过 250 行 | -| 全量 mypy 历史债务 | 9,217 / 508 文件 | 删除独立活动日志中间件后的现状基线;消息媒体交互类型债务已清零,canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降 | +| 全量 mypy 历史债务 | 9,209 / 508 文件 | 删除独立活动日志中间件后的现状基线;消息媒体交互类型债务已清零,canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降 | | Ruff 历史诊断 | 509 | 低水位门禁通过,但规则集只覆盖 `E4/E7/E9/F/I` | | 覆盖率固定基线 | Application 80.00%,Domain 80.00% | Chain、Runtime、Agent、Adapter、Startup 未进入包级覆盖率门禁 | diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index e7cab881a..6ab414655 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -930,8 +930,8 @@ "runtime_only": true } }, - "edge_count": 9295, - "edge_sha256": "6af911fd0a305838375d727fa8d7f451d271d073f46651b746d3926bad57bde2", + "edge_count": 9308, + "edge_sha256": "6c903fe5cd5db19ceb11f5ddde8418d89c663afee19349d4aaf25b7d8ef8ffaa", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -3218,6 +3218,18 @@ "app.api.endpoints.transferhistory -> app.schemas", "app.api.endpoints.transferhistory -> app.schemas.file", "app.api.endpoints.transferhistory -> app.schemas.transfer", + "app.api.endpoints.transferqueue -> app.adapters", + "app.api.endpoints.transferqueue -> app.adapters.web", + "app.api.endpoints.transferqueue -> app.adapters.web.security", + "app.api.endpoints.transferqueue -> app.adapters.web.security.access", + "app.api.endpoints.transferqueue -> app.api", + "app.api.endpoints.transferqueue -> app.api.response", + "app.api.endpoints.transferqueue -> app.chain", + "app.api.endpoints.transferqueue -> app.chain.transfer", + "app.api.endpoints.transferqueue -> app.chain.transfer.facade", + "app.api.endpoints.transferqueue -> app.schemas", + "app.api.endpoints.transferqueue -> app.schemas.token", + "app.api.endpoints.transferqueue -> app.schemas.transfer", "app.api.endpoints.user -> app.api", "app.api.endpoints.user -> app.api.dependencies", "app.api.endpoints.user -> app.api.dependencies.auth", @@ -3306,6 +3318,7 @@ "app.api.routers -> app.api.endpoints.tmdb", "app.api.routers -> app.api.endpoints.torrent", "app.api.routers -> app.api.endpoints.transfer", + "app.api.routers -> app.api.endpoints.transferqueue", "app.api.routers -> app.api.endpoints.user", "app.api.routers -> app.api.endpoints.webhook", "app.api.routers -> app.api.endpoints.workflow", @@ -10229,7 +10242,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 1104, + "module_count": 1105, "modules": [ "app", "app.adapters", @@ -10480,6 +10493,7 @@ "app.api.endpoints.torrent", "app.api.endpoints.transfer", "app.api.endpoints.transferhistory", + "app.api.endpoints.transferqueue", "app.api.endpoints.user", "app.api.endpoints.webhook", "app.api.endpoints.workflow", From 1ba2f28c94992c7b52b947206ff3a4f4c84ff2c2 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 2 Oct 2026 22:08:10 +0800 Subject: [PATCH 6/8] chore(transfer): remove unrelated fork sync changes --- .github/scripts/sync-upstream.sh | 34 ------------ .github/workflows/fork-upstream-sync.yml | 69 ------------------------ app/api/endpoints/transfer.py | 6 ++- docs/development-setup.md | 4 -- docs/fork-upstream-sync.md | 13 ----- tests/test_architecture_ci.py | 1 - 6 files changed, 5 insertions(+), 122 deletions(-) delete mode 100644 .github/scripts/sync-upstream.sh delete mode 100644 .github/workflows/fork-upstream-sync.yml delete mode 100644 docs/fork-upstream-sync.md diff --git a/.github/scripts/sync-upstream.sh b/.github/scripts/sync-upstream.sh deleted file mode 100644 index fc1424f86..000000000 --- a/.github/scripts/sync-upstream.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -report="$RUNNER_TEMP/upstream-sync-report.md" -printf '# 上游同步清单\n\n' > "$report" -git config user.name 'github-actions[bot]' -git config user.email '41898282+github-actions[bot]@users.noreply.github.com' -git fetch --no-tags https://github.com/jxxghp/MoviePilot.git v3 -upstream=$(git rev-parse FETCH_HEAD) -base=$(git merge-base HEAD "$upstream") -echo "上游提交:$upstream" >> "$report" -git log --format='- %h %s' HEAD.."$upstream" >> "$report" -if git merge-base --is-ancestor "$upstream" HEAD; then - echo '没有上游更新。' >> "$report" - echo 'changed=false' >> "$GITHUB_OUTPUT" - exit 0 -fi -# 双方修改同一文件时交给人工处理,避免自动合并悄悄改变定制行为 -git diff --name-only "$base" HEAD | sort > "$RUNNER_TEMP/fork-paths" -git diff --name-only "$base" "$upstream" | sort > "$RUNNER_TEMP/upstream-paths" -comm -12 "$RUNNER_TEMP/fork-paths" "$RUNNER_TEMP/upstream-paths" > "$RUNNER_TEMP/overlap" -if [ -s "$RUNNER_TEMP/overlap" ]; then - echo '需要人工审阅:上游与 fork 同时修改以下文件,未推送:' >> "$report" - cat "$RUNNER_TEMP/overlap" >> "$report" - exit 1 -fi -if ! git merge --no-ff --no-edit "$upstream"; then - echo '合并冲突,未推送:' >> "$report" - git diff --name-only --diff-filter=U >> "$report" - git merge --abort - exit 1 -fi -git diff --check HEAD^ HEAD -echo 'changed=true' >> "$GITHUB_OUTPUT" -echo '合并完成,等待验证。' >> "$report" diff --git a/.github/workflows/fork-upstream-sync.yml b/.github/workflows/fork-upstream-sync.yml deleted file mode 100644 index 347e68c99..000000000 --- a/.github/workflows/fork-upstream-sync.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: Fork upstream sync -on: - schedule: - - cron: '0 15 * * *' - workflow_dispatch: -permissions: - contents: write - issues: write -concurrency: - group: fork-upstream-sync - cancel-in-progress: false -jobs: - sync: - if: github.repository == 'ranzhigg/MoviePilot' - runs-on: ubuntu-latest - timeout-minutes: 60 - steps: - - uses: actions/checkout@v7 - with: - ref: v3 - fetch-depth: 0 - - name: Merge upstream conservatively - id: merge - run: bash .github/scripts/sync-upstream.sh - - name: Set up uv - if: steps.merge.outputs.changed == 'true' - uses: astral-sh/setup-uv@v10.0.1 - with: - python-version: '3.14' - - name: Verify merged MoviePilot - if: steps.merge.outputs.changed == 'true' - run: | - uv sync --locked - uv run --locked --no-sync python tests/run.py - - name: Push verified merge - if: steps.merge.outputs.changed == 'true' - run: | - git push origin HEAD:v3 - echo '验证通过,已推送;没有更新本地 MP,也没有自动发布插件安装包。' >> "$RUNNER_TEMP/upstream-sync-report.md" - - name: Record failure - if: failure() - run: | - echo '同步失败:请查看失败步骤。主分支不会收到未通过验证的合并。' >> "$RUNNER_TEMP/upstream-sync-report.md" - - name: Publish run summary - if: always() - run: | - test -f "$RUNNER_TEMP/upstream-sync-report.md" || echo '工作流未完成初始化,请查看日志。' > "$RUNNER_TEMP/upstream-sync-report.md" - cat "$RUNNER_TEMP/upstream-sync-report.md" >> "$GITHUB_STEP_SUMMARY" - - name: Save report - if: always() - uses: actions/upload-artifact@v7 - with: - name: upstream-sync-report - path: ${{ runner.temp }}/upstream-sync-report.md - retention-days: 30 - - name: Report failure as issue - if: failure() - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - printf '\n运行日志:%s\n' "$RUN_URL" >> "$RUNNER_TEMP/upstream-sync-report.md" - issue=$(gh issue list --state open --search '"上游同步失败" in:title' --json number --jq '.[0].number // empty') - if [ -n "$issue" ]; then - gh issue comment "$issue" --body-file "$RUNNER_TEMP/upstream-sync-report.md" - else - gh issue create --title '上游同步失败:需要检查' --body-file "$RUNNER_TEMP/upstream-sync-report.md" - fi diff --git a/app/api/endpoints/transfer.py b/app/api/endpoints/transfer.py index 9843c9d37..2af051d74 100644 --- a/app/api/endpoints/transfer.py +++ b/app/api/endpoints/transfer.py @@ -11,7 +11,11 @@ from app.api.endpoints.transferhistory import ( restore_manual_transfer_history_batch, restore_manual_transfer_history_metadata, ) -from app.api.response import CompatibleCountParam, CompatiblePageParam, ResponseAPIRouter +from app.api.response import ( + CompatibleCountParam, + CompatiblePageParam, + ResponseAPIRouter, +) from app.application.configuration import get_api_runtime_config_snapshot from app.application.directory import DirectoryHelper from app.application.history import TransferHistoryLookupService diff --git a/docs/development-setup.md b/docs/development-setup.md index a6ed55af6..db73f9fa6 100644 --- a/docs/development-setup.md +++ b/docs/development-setup.md @@ -255,10 +255,6 @@ CI 上传 `complexity-report` 工件,门禁失败时也保留已生成的指 - [MoviePilot-Resources](https://github.com/jxxghp/MoviePilot-Resources) - [MoviePilot-Plugins](https://github.com/jxxghp/MoviePilot-Plugins) -## 个人 fork 同步 - -定时合并和失败通知见 [Fork 上游同步](fork-upstream-sync.md)。 - ### Agent 历史消息索引验证 独立消息库位于 Agent 运行目录,不参与主库 Alembic。使用临时运行目录运行 `tests/test_agent_recall_persistence.py`,不得用真实用户的 `state.db` 做索引破坏或重建测试。CJK tokenizer 保留 Hermes 原版源码及许可证于 `native/fts5_cjk/`;Docker 构建与 CLI 依赖安装使用该目录的 `install.py`,按本机架构编译并用目标解释器实际验证两字中文查询,安装到 `/lib/moviepilot/libfts5_cjk.so`。旧配置目录内的手工扩展作为加载回退;编译器要求和补装/检查命令见该目录 README。测试有本地 C 编译器时在临时目录构建,无编译器时只跳过原生扩展用例,不能宣称该分词路径已验证。常规 FTS5 与 trigram、短中文回退无需该扩展,扩展缺失或失效时索引状态会明确降级。独立 schema 版本不等于产品版本;后续新增主库升级脚本从 3.1.0 命名。 diff --git a/docs/fork-upstream-sync.md b/docs/fork-upstream-sync.md deleted file mode 100644 index 7ab76aa0e..000000000 --- a/docs/fork-upstream-sync.md +++ /dev/null @@ -1,13 +0,0 @@ -# Fork 上游同步 - -每天北京时间 23:00(UTC 15:00)由 GitHub Actions 检查上游;GitHub 定时任务可能延迟。也可在 Actions → Fork upstream sync 手动运行。 - -使用普通合并,保留 fork 提交;双方改动同一文件时暂停人工审阅,不采用 ours/theirs 或强制覆盖。合并、校验或推送失败时工作流失败,生成日志、30 天报告附件,并创建或更新失败 Issue。每次运行的 Summary 展示上游提交清单及结果。失败不自动回滚已有提交,不修改本地 MP。 - -推送使用 GITHUB_TOKEN,合并推送不会自动触发其他 push 工作流或插件发布;插件发布及本地安装需要另行执行。验证仅覆盖工作流列出的检查,不保证所有外部服务或第三方插件兼容。 - -## GitHub 自带失败邮件 - -仓库代码无法修改账号的邮件通知偏好。在 GitHub Settings → Notifications → System → Actions,启用 Email 并选择仅失败通知;确保该仓库通知路由使用已验证的 `ranzhigg@gmail.com`。首次用自己的账号手动运行本工作流,并检查失败邮件偏好。未开启账号通知前,工作流无法保证邮件送达,也不能从仓库设置强制收件人。 - -不需要 SMTP 密钥。失败 Issue 和 Actions 日志始终作为反馈入口,修复后可手动重跑;失败 Issue 由人工确认后关闭。 diff --git a/tests/test_architecture_ci.py b/tests/test_architecture_ci.py index 805d6b6bf..c41c3f6d5 100644 --- a/tests/test_architecture_ci.py +++ b/tests/test_architecture_ci.py @@ -256,7 +256,6 @@ def test_upload_artifact_actions_share_node24_major(): assert actions_by_workflow == { "architecture-observe.yml": ["actions/upload-artifact@v7"], - "fork-upstream-sync.yml": ["actions/upload-artifact@v7"], "native-dependency-update.yml": ["actions/upload-artifact@v7"], "pylint.yml": ["actions/upload-artifact@v7"], "site-adapter-collector.yml": ["actions/upload-artifact@v7"], From 1eacd10cd6f207880c2dcd7139cf6f5c5568afd9 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 2 Oct 2026 22:10:16 +0800 Subject: [PATCH 7/8] refactor(transfer): keep queue projections in transfer endpoint module --- app/api/endpoints/transfer.py | 22 ++++++++++++++++++++++ app/api/endpoints/transferqueue.py | 29 ----------------------------- app/api/routers.py | 2 -- 3 files changed, 22 insertions(+), 31 deletions(-) delete mode 100644 app/api/endpoints/transferqueue.py diff --git a/app/api/endpoints/transfer.py b/app/api/endpoints/transfer.py index 2af051d74..833217374 100644 --- a/app/api/endpoints/transfer.py +++ b/app/api/endpoints/transfer.py @@ -12,6 +12,7 @@ from app.api.endpoints.transferhistory import ( restore_manual_transfer_history_metadata, ) from app.api.response import ( + COLLECTION_MAX_PAGE_SIZE, CompatibleCountParam, CompatiblePageParam, ResponseAPIRouter, @@ -50,6 +51,7 @@ from app.schemas.transfer import TransferManualReviewData as _SchemaTransferManu from app.schemas.transfer import TransferManualReviewPageData as _SchemaTransferManualReviewPageData from app.schemas.transfer import TransferManualReviewRequest as _SchemaTransferManualReviewRequest from app.schemas.transfer import TransferManualReviewTaskData as _SchemaTransferManualReviewTaskData +from app.schemas.transfer import TransferQueuePageData as _SchemaTransferQueuePageData from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaType from app.schemas.workflow import FileItem from app.schemas.workflow import FileItem as _SchemaFileItem @@ -442,6 +444,26 @@ async def query_queue(_: _SchemaTokenPayload = Depends(verify_token), page: Comp return TransferChain().get_queue_tasks() +@router.get( # type: ignore[misc] + "/queue/page", + summary="查询受限整理队列快照", + response_model=_SchemaTransferQueuePageData, +) +async def query_queue_page( + _: _SchemaTokenPayload = Depends(verify_token), + page: int = Query(1, ge=1), + count: int = Query(100, ge=1, le=COLLECTION_MAX_PAGE_SIZE), +) -> _SchemaTransferQueuePageData: + """返回前端所需的有限整理队列窗口,避免序列化完整云盘目录树。""" + items, total = TransferChain().get_queue_tasks_page(page, count) + return _SchemaTransferQueuePageData( + items=items, + total=total, + page=page, + count=count, + ) + + @router.delete( "/queue", summary="从整理队列中删除任务", response_model=_SchemaResponse[None] ) diff --git a/app/api/endpoints/transferqueue.py b/app/api/endpoints/transferqueue.py deleted file mode 100644 index 397aa4740..000000000 --- a/app/api/endpoints/transferqueue.py +++ /dev/null @@ -1,29 +0,0 @@ -from fastapi import Depends, Query - -from app.adapters.web.security.access import verify_token -from app.api.response import COLLECTION_MAX_PAGE_SIZE, ResponseAPIRouter -from app.chain.transfer.facade import TransferChain -from app.schemas.token import TokenPayload as _SchemaTokenPayload -from app.schemas.transfer import TransferQueuePageData as _SchemaTransferQueuePageData - -router = ResponseAPIRouter() - - -@router.get( # type: ignore[misc] - "/queue/page", - summary="查询受限整理队列快照", - response_model=_SchemaTransferQueuePageData, -) -async def query_queue_page( - _: _SchemaTokenPayload = Depends(verify_token), - page: int = Query(1, ge=1), - count: int = Query(100, ge=1, le=COLLECTION_MAX_PAGE_SIZE), -) -> _SchemaTransferQueuePageData: - """返回前端所需的有限整理队列窗口,避免全量队列阻塞接口序列化。""" - items, total = TransferChain().get_queue_tasks_page(page, count) - return _SchemaTransferQueuePageData( - items=items, - total=total, - page=page, - count=count, - ) diff --git a/app/api/routers.py b/app/api/routers.py index a2e915820..d1a154cb8 100644 --- a/app/api/routers.py +++ b/app/api/routers.py @@ -41,7 +41,6 @@ from app.api.endpoints import ( tmdb, torrent, transfer, - transferqueue, user, webhook, workflow, @@ -89,7 +88,6 @@ API_V1_ROUTER_SPECS: tuple[RouterSpec, ...] = ( RouterSpec(dashboard.router, "/dashboard", ("dashboard",)), RouterSpec(storage.router, "/storage", ("storage",)), RouterSpec(transfer.router, "/transfer", ("transfer",)), - RouterSpec(transferqueue.router, "/transfer", ("transfer",)), RouterSpec(mediaserver.router, "/mediaserver", ("mediaserver",)), RouterSpec(bangumi.router, "/bangumi", ("bangumi",)), RouterSpec(anilist.router, "/anilist", ("anilist",)), From cb9b9e525552699cc062107dd2d4eeefe1eb9731 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 2 Oct 2026 22:24:46 +0800 Subject: [PATCH 8/8] test(transfer): cover bounded queue endpoint contract --- tests/test_transfer_queue_paging.py | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/test_transfer_queue_paging.py b/tests/test_transfer_queue_paging.py index f8528e81e..ff7e1873d 100644 --- a/tests/test_transfer_queue_paging.py +++ b/tests/test_transfer_queue_paging.py @@ -1,7 +1,11 @@ +import asyncio +import inspect from unittest.mock import Mock import pytest +from app.adapters.web.security.access import verify_token +from app.api.endpoints import transfer as transfer_endpoint from app.application.transfer.jobs import JobManager from app.application.transfer.workflow import TransferQueueService from app.schemas.file import FileItem @@ -98,6 +102,39 @@ def test_transfer_queue_service_uses_bounded_projection_after_expiring_tasks(): list_tasks_page.assert_called_once_with(3, 50) +def test_queue_page_endpoint_exposes_bounded_projection_with_existing_transfer_auth(monkeypatch): + """轻量队列端点必须复用整理模块的鉴权并转发分页窗口。""" + calls = [] + + class StubTransferChain: + """提供端点测试所需的受限队列查询替身。""" + + def get_queue_tasks_page(self, page: int, count: int): + """记录分页参数并返回最小合法快照。""" + calls.append((page, count)) + return ([], 7) + + monkeypatch.setattr(transfer_endpoint, "TransferChain", StubTransferChain) + + result = asyncio.run( + transfer_endpoint.query_queue_page( + _=object(), + page=2, + count=3, + ) + ) + + dependency = inspect.signature(transfer_endpoint.query_queue_page).parameters["_"].default.dependency + assert dependency is verify_token + assert calls == [(2, 3)] + assert result.model_dump() == { + "items": [], + "total": 7, + "page": 2, + "count": 3, + } + + def test_job_manager_duplicate_index_is_released_when_a_cloud_task_is_removed(): """批量云盘任务的 O(1) 去重索引不能阻止同一源文件后续重新入队。""" manager = JobManager()