refactor: reorganize backend module boundaries

This commit is contained in:
jxxghp
2026-08-14 19:53:33 +08:00
parent fe0b444ceb
commit 369d7d6448
584 changed files with 2423 additions and 2275 deletions

View File

@@ -79,16 +79,16 @@ Entrypoints / Plugins --> Application / Chain --> Domain + Ports --> Foundation
| 目标包 | 职责 | 允许依赖 |
| --- | --- | --- |
| `app.foundation` | 不读取 MoviePilot 业务或运行配置的 HTTP、动态模块加载、通用结构、加密、URL、版本和文本基础能力 | 标准库、第三方库、同层代码 |
| `app.foundation` | 不读取 MoviePilot 业务或运行配置、也不执行 I/O 的反射/动态加载、DOM、通用结构、加密、URL、版本和文本基础能力 | 标准库、第三方库、同层代码 |
| `app.domain` | 媒体、识别、媒体服务器身份、站点和种子业务语义 | `foundation` 和 schemas;不得依赖 DB、settings、基础设施、扩展、消息、安全或应用服务 |
| `app.chain`、`app.services` | 用例编排、跨模块业务流程和聚焦应用服务 | 领域、平台能力和适配器;不得形成模块级依赖环 |
| `app.infrastructure` | RSS、Redis/文件缓存、浏览器、DNS、资源、包、OS 和 Rust 等配置化运行适配 | `foundation`、`platform`;不得依赖领域或上层能力包 |
| `app.platform` | 配置、事件总线、缓存契约/内存策略、并发、GC 和进程级协调 | `foundation` 及少量明确的 OS 适配器 |
| `app.extensions` | 模块、插件和服务的运行时发现及生命周期 | 领域、平台及适配器;依赖由 startup 注入 |
| `app.chain`、`app.application` | 用例编排、跨模块业务流程和聚焦应用服务 | 领域、平台能力和适配器;不得形成模块级依赖环 |
| `app.adapters` | 按 cache/network/system/external 分类的 Redis、HTTP、浏览器、DNS、资源、包、OS、Rust 和命名外部生态适配 | `foundation`、`domain`、schemas 和必要 runtime 契约;不得依赖 application、runtime extensions/compat 或 SDK |
| `app.runtime` | 配置、事件总线、缓存契约/内存策略、并发、GC 和进程级协调 | `foundation` 及少量明确的 OS 适配器 |
| `app.runtime.extensions` | 模块、插件和服务的运行时发现及生命周期 | 领域、平台及适配器;依赖由 startup 注入 |
| `app.agent.skills` | Agent Skill 元数据、市场和本地生命周期 | Agent、平台及适配器;不归入通用扩展层 |
| `app.integrations`、`app.messaging`、`app.security` | 插件市场、IP 归属等外部生态、消息和安全边界 | 领域、平台及基础设施能力 |
| `app.adapters.external`、`app.application.messaging`、`app.application.security` | 插件市场、IP 归属等外部生态、消息和安全边界 | 领域、平台及基础设施能力 |
| `app.sdk` | 明确承诺给插件使用的稳定类型、事件和服务门面 | 只通过显式导出依赖受控 canonical 对象 |
| `app.compat` | 旧导入路径兼容机制和声明式映射 | 仅 Python 标准库;不能导入业务目标模块 |
| `app.runtime.compat` | 旧导入路径兼容机制和声明式映射 | 仅 Python 标准库;不能导入业务目标模块 |
源码已按这些边界迁移完成。后续新增模块以所有权和无环依赖为验收标准,不能重新创建 `core/helper/utils` 物理源码目录。
@@ -108,27 +108,28 @@ Entrypoints / Plugins --> Application / Chain --> Domain + Ports --> Foundation
| --- | --- | --- |
| `core.context`、`core.meta*`、`core.metainfo` | `app.domain.context` / `app.domain.meta` / `app.domain.metainfo` | 已去除 DB、settings、平台日志实现和 Rust adapter 直接依赖,由 startup 注入 |
| `helper.nfo`、`helper.scraper` | `app.domain.scraper` | NFO 读取与媒体元数据文档生成属于同一领域能力;旧 `app.helper.nfo` 精确映射到合并后的模块 |
| `app.log` | `app.platform.log` | 日志策略、控制台/插件路由、异步滚动文件写入和关闭集中在一个模块;插件入口为 `app.sdk.logging` |
| `core.config` | `runtime.config` | 先把纯路径、URL、系统操作下沉到 foundation/infrastructure,避免 runtime 被低层反向导入 |
| `app.log` | `app.runtime.log` | 日志策略、控制台/插件路由、异步滚动文件写入和关闭集中在一个模块;插件入口为 `app.sdk.logging` |
| `core.config` | `runtime.config` | 纯 URL、网络和系统操作下沉到 foundation/adapters,避免 runtime 承担具体 I/O |
| `core.event` 中的 `Event` 契约 | `domain.events` 或稳定 SDK contract | 与事件队列、线程、处理器实例解析分离 |
| `core.event` 中的 EventManager | `runtime.events` | 移除按类名猜路径及直接实例化 PluginManager/ModuleManager/MessageHelper |
| `core.module`、`core.plugin` | `runtime.extensions` | 安装、发现、生命周期和业务上报通过接口/装配连接 |
| `core.cache` | `app.platform.cache` + `app.infrastructure.cache` | platform 保留契约、内存策略和装饰器;infrastructure 实现 Redis/文件 I/O;SDK 维持旧完整符号集 |
| `core.cache` | `app.runtime.cache` + `app.adapters.cache.backends` | runtime 保留契约、内存策略和装饰器;cache adapters 实现 Redis/文件 I/O;SDK 维持旧完整符号集 |
| `utils.string/url/identity/coalesce/structures` 等纯函数 | `foundation` 对应领域文件 | 确认不读取全局配置、不执行 I/O、不导入高层模块 |
| `utils.http` | `foundation.http` | 去除对 `settings` 的反向读取,由启动层注入宿主 User-Agent |
| `utils.web` | `app.integrations.location` | 外部 IP 归属服务是具体生态集成,不是通用网络基础设施 |
| `utils.gc` | `app.platform.gc` | 进程内存观测和回收是运行平台策略,不是外部适配器 |
| `utils.rust_accel/system/stdio` | `app.infrastructure` | 具体扩展、系统调用和 stdio I/O 保留在适配器层 |
| `utils.http` | `app.adapters.network.http` | 去除对 `settings` 的反向读取,由启动层注入宿主 User-Agent |
| `utils.web` | `app.adapters.external.location` | 外部 IP 归属服务是具体生态集成,不是通用网络基础设施 |
| `utils.gc` | `app.runtime.gc` | 进程内存观测和回收是运行平台策略,不是外部适配器 |
| `utils.rust_accel/system/stdio` | `app.adapters` | 具体扩展、系统调用和 stdio I/O 保留在适配器层 |
| `utils.mixins` | 按能力拆分,配置重载部分归 `runtime` | 消除 mixin 对全局事件单例的导入期注册 |
| `helper.redis/browser/doh/display/thread/package` 等 | `infrastructure` | 生命周期由 runtime 装配,不在适配器内部反向获取管理器 |
| `helper.module` | `foundation.module` | 只保留通用 Python 模块发现与动态加载,不承担模块生命周期 |
| `helper.downloader/mediaserver/service` | `app.services` + `app.extensions.service_registry` | 媒体服务器身份/匹配规则与配置化服务发现统一归入 `services/mediaserver.py`,通用服务注册机制保持独立 |
| `helper.message/interaction` | `app.messaging` | 负责消息渲染、路由和交互,不承担配置化服务发现 |
| `helper.notification` | `app.services.notification` | 通知模块发现依赖持久化配置,属于应用服务 |
| `helper.redis/browser/doh/display/thread/package` 等 | `adapters/cache`、`adapters/network`、`adapters/system` 或 `runtime/thread.py` | 生命周期由 startup 装配,不在适配器内部反向获取管理器 |
| `helper.module` | `foundation.reflection` | 只保留通用 Python 反射、模块发现与动态加载,不承担模块生命周期 |
| `helper.downloader/mediaserver/service` | `app.application` + `app.runtime.extensions.service_registry` | 媒体服务器身份/匹配规则与配置化服务发现统一归入 `application/mediaserver.py`,通用服务注册机制保持独立 |
| `helper.message/interaction` | `app.application.messaging` | 负责消息渲染、路由和交互,不承担配置化服务发现 |
| `helper.notification` | `app.application.notification` | 通知模块发现依赖持久化配置,属于应用服务 |
| `helper.webpush` | `app.api.endpoints.message` | Web Push 订阅和手动发送只服务消息 HTTP API,直接归入对应 endpoint |
| `helper.server` | `app.integrations.server` | MoviePilot 远端服务是命名外部生态集成 |
| `helper.server` | `app.adapters.external.server` | MoviePilot 远端服务是命名外部生态集成 |
| `helper.torrent/audio/directory/format/nfo/rule/scraper` | `domain` 纯规则 + `application` 用例 + I/O adapter | 逐函数区分纯转换、业务流程和文件/网络访问 |
| `helper.sites` 与二进制资源 | `infrastructure.sites` + 独立资源目录 | 完成 Build、Resources、Docker、本地安装的跨仓同步迁移 |
| `helper.rss` | `app.application.rss` | RSS 同时负责 Feed/种子语义、站点规则和浏览器回退,不把它简化为网络传输适配器 |
| `helper.sites` 与二进制资源 | `app.application.site.sites` + `app/application/site/` 资源目录 | 站点目录、认证和索引属于应用能力;完成 Build、Resources、Docker、本地安装及 CI 的跨仓同步迁移 |
`app.chain` 已经承担 application orchestration,可继续保留,不必仅为追求目录命名整齐而整体改名。`app.modules` 继续作为可插拔 adapter 集合,但模块间编排仍由 chain/application 完成。
@@ -161,7 +162,7 @@ app/
services.py
```
`app.compat` 自身只使用标准库,尤其不能导入 `settings`、logger、事件总线、插件管理器或映射目标。`app/__init__.py` 只负责无业务依赖地安装钩子;配置初始化完成后、插件加载前,再由启动装配代码调用类似 `configure_diagnostics(enabled=settings.DEBUG, emit=logger.warning)` 的入口注入 Debug 状态和日志回调,避免兼容层再次进入当前依赖环。
`app.runtime.compat` 自身只使用标准库,尤其不能导入 `settings`、logger、事件总线、插件管理器或映射目标。`app/__init__.py` 只负责无业务依赖地安装钩子;配置初始化完成后、插件加载前,再由启动装配代码调用类似 `configure_diagnostics(enabled=settings.DEBUG, emit=logger.warning)` 的入口注入 Debug 状态和日志回调,避免兼容层再次进入当前依赖环。
### 4.3 声明式映射
@@ -170,12 +171,12 @@ app/
```python
MODULE_ALIASES = {
"app.core.event": ModuleAlias(
target="app.platform.events",
target="app.runtime.events",
introduced="3.x.y",
owner="runtime",
),
"app.utils.http": ModuleAlias(
target="app.foundation.http",
target="app.adapters.network.http",
introduced="3.x.y",
owner="infrastructure",
),
@@ -187,7 +188,7 @@ MODULE_ALIASES = {
约束如下:
- 旧路径和目标路径都必须是完整绝对模块名。
- 不允许 `app.core.* -> app.platform.*` 这类通配规则自动覆盖未知模块。
- 不允许 `app.core.* -> app.runtime.*` 这类通配规则自动覆盖未知模块。
- 旧路径不能仍有真实 `.py` 文件,避免标准查找器绕过兼容 Finder。
- 目标不能再指向另一个旧路径;启动校验应将别名链视为错误。
- 一个旧模块只能映射到一个目标模块。
@@ -202,7 +203,7 @@ MODULE_ALIASES = {
```python
import app.core.event as legacy
import app.platform.events as canonical
import app.runtime.events as canonical
assert legacy is canonical
assert legacy.Event is canonical.Event
@@ -269,7 +270,7 @@ Finder 在诊断回调尚未配置时仍可暂存命中的旧路径和调用模
当 `settings.DEBUG` 为真且兼容 Finder 命中旧路径时,记录一次 Debug 兼容警告:
```text
[兼容导入] 插件 AutoSignIn 使用旧路径 app.utils.http,已映射到 app.foundation.http;请迁移到 app.sdk.network
[兼容导入] 插件 AutoSignIn 使用旧路径 app.utils.http,已映射到 app.adapters.network.http;请迁移到 app.sdk.network
```
警告应包含:
@@ -361,7 +362,7 @@ SYMBOL_ALIASES = {
### 阶段 1:先落兼容基础设施
- 新增只依赖标准库的 `app.compat`。
- 新增只依赖标准库的 `app.runtime.compat`。
- 在 `app/__init__.py` 最早安装 Finder。
- 实现 DEBUG 运行时告警与插件 AST 扫描。
- 映射表先为空或只放一个无副作用的试点模块。
@@ -406,12 +407,12 @@ SYMBOL_ALIASES = {
新增 AST 级测试或独立脚本,至少检查:
- `app.compat` 不导入任何 MoviePilot 业务模块;
- `app.runtime.compat` 不导入任何 MoviePilot 业务模块;
- `app.foundation` 不导入其他 MoviePilot 能力包;
- `domain` 不导入 DB、平台日志实现、platform、infrastructure、`extensions/integrations/messaging/security/services/sdk/compat`;
- `infrastructure` 不导入 `domain` 或任何上层应用能力包;
- `foundation` 不打印日志,也不导入平台日志实现;`platform.cache` 不导入具体 infrastructure cache adapter;
- `infrastructure.resource` 不导入或调用 `platform.runtime`;
- `domain` 不导入 DB、runtime、adapters、application、SDK 或兼容层;
- `adapters` 不导入 application、runtime extensions/compat 或 SDK;
- `foundation` 不打印日志,也不导入任何其他 `app.*` 包;`runtime.cache` 不导入具体 cache adapter;
- `adapters.system.resource` 不导入或调用 `runtime.state`;
- 低层不导入 `PluginManager`、`ModuleManager` 等运行时实现;
- `app/` 主程序代码不再导入已登记的旧路径,插件目录除外;
- 完整导入图中不存在包含 canonical 迁移模块、SDK 或兼容层的强连通分量;
@@ -453,13 +454,14 @@ SYMBOL_ALIASES = {
## 10. 资源、构建和跨仓影响
`MoviePilot-Resources/resources.v3`、Docker 更新脚本、本地安装脚本以及 `MoviePilot-Build` 现已把站点扩展和数据文件同步到 `app/infrastructure/`,编译扩展模块名为 `app.infrastructure.sites`。
`MoviePilot-Resources/resources.v3`、Docker 更新脚本、本地安装脚本以及 `MoviePilot-Build` 现已把站点扩展和数据文件同步到 `app/application/site/`,编译扩展模块名为 `app.application.site.sites`。
跨仓资源迁移已按以下约束完成:
- 站点运行时扩展 canonical 路径为 `app.infrastructure.sites`;
- 数据文件放到明确的资源目录,不再与 Python helper 源码混放;
- 站点运行时扩展 canonical 路径为 `app.application.site.sites`;
- 数据文件与其唯一消费者放到聚焦的站点应用目录,不再混入通用网络适配器;
- 同步修改 `MoviePilot-Build` 的扩展名和输出参数;
- 同步修改 Build CI 的认证扩展、站点数据发布流程和 manifest target;
- 同步修改 `MoviePilot-Resources` 的 package target;
- 修改 Dockerfile、`docker/update.sh`、entrypoint、本地安装/卸载和相关文档;
- 为 `app.helper.sites` 保留旧路径兼容,并验证 CPython 扩展通过别名加载时保持同一模块身份;
@@ -511,16 +513,16 @@ SYMBOL_ALIASES = {
## 14. 实施结果
1. `app/core`、`app/helper`、`app/utils` 已无物理 Python 源码,宿主全部使用 canonical 路径。
2. `app.compat` 在 `app` 包初始化时安装精确白名单 Finder,旧叶子模块与 canonical 模块保持同一身份。
2. `app.runtime.compat` 在 `app` 包初始化时安装精确白名单 Finder,旧叶子模块与 canonical 模块保持同一身份。
3. DEBUG 诊断通过运行时命中和插件 AST 扫描互补发现旧引用,生产模式静默。
4. Event、模块、插件和安全边界改为由 startup composition root 注入 resolver、回调和错误处理器,迁移模块不再处于强连通分量。
5. 插件稳定入口收敛到 `app.sdk`;存量插件无需同步修改,官方插件可以按正常发布节奏迁移。
6. 站点二进制和数据资源迁到 `app.infrastructure`,Build 直接生成 canonical 模块,Resources V3 manifest、Docker 和本地 CLI 使用同一目标路径。
6. 站点二进制和数据资源迁到 `app/application/site`,Build 直接生成 `app.application.site.sites`,Build CI、Resources V3 manifest、Docker 和本地 CLI 使用同一目标路径。
7. 媒体识别领域不再直接读取 DB/settings,也不导入 Rust 适配器;`startup/domain_initializer.py` 统一注入实时规则、后缀策略、TMDB 图片地址、默认媒体来源和加速器。
8. 缓存按职责拆为 `platform/cache.py`(契约、内存实现、装饰器、代理)和 `infrastructure/cache.py`(Redis、文件 I/O);旧 `app.core.cache` 指向完整 `app.sdk.cache` 门面。
9. `services/mediaserver.py` 集中负责媒体服务器的配置化服务发现、Provider ID 规范化和音乐库匹配;通用媒体身份规则继续复用 `domain/media.py`。
10. GC 归入 `platform/gc.py`,外部 IP 归属查询归入 `integrations/location.py`,安全能力统一在 `app/security/`,URL 安全策略为 `url.py`,二次认证文件为 `twofactor.py`。
8. 缓存按职责拆为 `runtime/cache.py`(契约、内存实现、装饰器、代理)和 `adapters/cache/backends.py`(Redis、文件 I/O);旧 `app.core.cache` 指向完整 `app.sdk.cache` 门面。
9. `application/mediaserver.py` 集中负责媒体服务器的配置化服务发现、Provider ID 规范化和音乐库匹配;通用媒体身份规则继续复用 `domain/media.py`。
10. GC 归入 `runtime/gc.py`,外部 IP 归属查询归入 `adapters/external/location.py`,安全能力统一在 `app/application/security/`,URL 安全策略为 `url.py`,二次认证文件为 `twofactor.py`。
11. 资源适配器只负责检测、下载和安装,成功后是否重启由 startup 决策。
12. 日志策略、控制台/插件路由、异步滚动文件写入和关闭集中在 `platform/log.py`;该模块不得导入任何 `app.*` 模块,foundation 不打印日志,运行期诊断由上层调用方负责。插件使用 `app.sdk.logging`,旧 `app.log` 继续精确兼容。
12. 日志策略、控制台/插件路由、异步滚动文件写入和关闭集中在 `runtime/log.py`;该模块不得导入任何 `app.*` 模块,foundation 不打印日志,运行期诊断由上层调用方负责。插件使用 `app.sdk.logging`,旧 `app.log` 继续精确兼容。
13. `domain/nfo.py` 已合并进 `domain/scraper.py`,NFO 读取与元数据文档生成由同一领域模块负责,旧 `app.helper.nfo` 仍可导入。
14. 通知服务发现归入 `services/notification.py`;Web Push API 辅助逻辑归入 `api/endpoints/message.py`,不再保留 `messaging/notification.py` 和 `messaging/webpush.py`。
14. 通知服务发现归入 `application/notification.py`;Web Push API 辅助逻辑归入 `api/endpoints/message.py`,不再保留旧顶级 messaging 中的 notification/webpush 模块。

View File

@@ -16,7 +16,7 @@ curl -fsSL https://raw.githubusercontent.com/jxxghp/MoviePilot/v3/scripts/bootst
- 安装后端依赖
- 按当前仓库 `version.py` 中的 `FRONTEND_VERSION` 下载对应前端 release 的 `dist.zip`
- 下载 `MoviePilot-Resources` 主分支资源
- 将 `resources.v3/*` 同步到后端 `app/infrastructure/`
- 将 `resources.v3/*` 同步到后端 `app/application/site/`
- 下载本地 Node 运行时并安装前端运行依赖
- 执行初始化向导
- 创建全局 `moviepilot` 命令
@@ -192,7 +192,7 @@ moviepilot install resources --config-dir /path/to/moviepilot-config
说明:
- 默认直接从 GitHub 下载 `MoviePilot-Resources` 主分支压缩包
- 会将 `resources.v3/*` 整体复制到 `app/infrastructure/`
- 会将 `resources.v3/*` 整体复制到 `app/application/site/`
- 这一步和 Docker 构建流程保持一致
## 初始化命令
@@ -294,7 +294,7 @@ moviepilot uninstall --config-dir /path/to/moviepilot-config
说明:
- 卸载时会先停止当前 CLI 管理的前后端服务
- 会删除本地虚拟环境、前端运行时、本地 Node 运行时、全局 `moviepilot` 软链接,以及同步到 `app/infrastructure` 的资源文件
- 会删除本地虚拟环境、前端运行时、本地 Node 运行时、全局 `moviepilot` 软链接,以及同步到 `app/application/site` 的资源文件
- 如果之前注册过开机自启,卸载时也会一并取消
- 会询问是否同时删除配置目录,默认不删除
- 如果当前使用的是仓库内 legacy `config/` 目录,确认删除后其中的 `category.yaml` 等配置文件也会一起删除

View File

@@ -105,10 +105,10 @@ chmod +x scripts/start-local.sh
本地源码开发时,主程序需要读取资源文件和插件源码。相关文件需要放到主程序实际加载的目录下:
- **资源文件**:将 [MoviePilot-Resources](https://github.com/jxxghp/MoviePilot-Resources) 仓库中 `resources.v3/` 下的文件同步到本仓库的 `app/infrastructure/` 目录下。CLI 安装和 Docker 构建流程只读取 V3 资源。
- **资源文件**:将 [MoviePilot-Resources](https://github.com/jxxghp/MoviePilot-Resources) 仓库中 `resources.v3/` 下的文件同步到本仓库的 `app/application/site/` 目录下。CLI 安装和 Docker 构建流程只读取 V3 资源。
- **插件源码**:需要开发或调试的插件放到本仓库的 `app/plugins/` 目录下,例如 `app/plugins/<插件目录>/`。主程序运行时从该目录加载插件,独立插件仓库只是源码来源。
如果资源文件没有放到 `app/infrastructure/`,站点索引、规则和内置资源相关能力可能无法按本地开发预期工作;如果插件没有放到 `app/plugins/`,主程序也不会在本地运行时发现该插件。
如果资源文件没有放到 `app/application/site/`,站点索引、规则和内置资源相关能力可能无法按本地开发预期工作;如果插件没有放到 `app/plugins/`,主程序也不会在本地运行时发现该插件。
### 4.1 GitHub 发版时生成插件市场默认值
@@ -126,7 +126,7 @@ chmod +x scripts/start-local.sh
```bash
python -m scripts.generate_plugin_market_default \
--wiki-file /path/to/MoviePilot-Wiki/plugin.md \
--config-file app/platform/config.py
--config-file app/runtime/config.py
```
### 5. 运行安全检查

View File

@@ -29,15 +29,14 @@ MoviePilot is a self-hosted media automation platform targeting Chinese-language
| `app/db/` | SQLAlchemy models and data access wrappers |
| `app/foundation/` | Stateless general-purpose primitives |
| `app/domain/` | Media-domain models, parsing, and rules |
| `app/platform/` | Config, events, caching, and process-wide coordination |
| `app/infrastructure/` | Network, filesystem, process, Redis, and site-resource adapters |
| `app/extensions/` | Module, plugin, market, and service lifecycle management |
| `app/integrations/` | Downloader, media-server, RSS, OCR, storage, and remote-service adapters |
| `app/messaging/` | Messaging, interaction, notification, and push capabilities |
| `app/security/` | Authentication and access-control capabilities |
| `app/services/` | Focused application services |
| `app/runtime/` | Config, events, logging, caching, concurrency, process state, extensions, and legacy compatibility |
| `app/adapters/` | Cache, network, system, generated-resource, and named external-product adapters |
| `app/runtime/extensions/` | Module, plugin, and configured-service lifecycle management |
| `app/application/messaging/` | Messaging, interaction, and Agent-to-message capabilities |
| `app/application/security/` | Authentication and access-control capabilities |
| `app/application/` | Focused application services |
| `app/sdk/` | Stable imports for plugins |
| `app/compat/` | Virtual legacy import compatibility and DEBUG diagnostics |
| `app/runtime/compat/` | Virtual legacy import compatibility and DEBUG diagnostics |
| `app/schemas/` | Pydantic request/response models and shared enums |
| `app/agent/` | LLM Agent runtime, tools, middleware, and Skill lifecycle |
| `app/workflow/` | Workflow engine |

View File

@@ -17,7 +17,7 @@
| Web framework | FastAPI |
| ASGI server | Uvicorn |
| Data validation | Pydantic v2 (`BaseModel`, `BaseSettings`, `model_validator`) |
| Settings management | `pydantic-settings` (`BaseSettings` class in `app/platform/config.py`) |
| Settings management | `pydantic-settings` (`BaseSettings` class in `app/runtime/config.py`) |
---
@@ -37,7 +37,7 @@
| Item | Detail |
|---|---|
| File-based cache | `FileCache` / `AsyncFileCache` in `app/platform/cache.py` |
| File-based cache | `FileCache` / `AsyncFileCache` in `app/runtime/cache.py` |
| Redis | Optional; `app/modules/redis/` module; used for distributed caching when configured |
| In-process cache | Decorator helpers `fresh` / `async_fresh` on `FileCache` |

View File

@@ -299,7 +299,7 @@ bash scripts/collect-site-adapter.sh
# Run after activating the project virtual environment
python -m scripts.generate_plugin_market_default \
--wiki-file /path/to/MoviePilot-Wiki/plugin.md \
--config-file app/platform/config.py
--config-file app/runtime/config.py
```
**Rules:**

View File

@@ -84,12 +84,12 @@ result = await self.async_run_module("method_name", kwarg1=val1)
**When to use:** Triggering cross-cutting reactions (e.g., notifying the media server after a transfer completes, reloading a module after config changes, dispatching user messages to message channels).
**Core classes:** `EventManager` (singleton instance `eventmanager`) and `Event` in `app/platform/events.py`.
**Core classes:** `EventManager` (singleton instance `eventmanager`) and `Event` in `app/runtime/events.py`.
**Registering a handler:**
```python
from app.platform.events import eventmanager, Event
from app.runtime.events import eventmanager, Event
from app.schemas.types import EventType
@eventmanager.register(EventType.TransferComplete)
@@ -136,7 +136,7 @@ oper.add(Subscribe(name="Example", type="电影"))
**When to use:** A chain, module, or helper holds a long-lived object that must be rebuilt when specific configuration keys change (e.g., a downloader client reconnects when its host/port changes).
**Mixin:** `ConfigReloadMixin` in `app/platform/reload.py`
**Mixin:** `ConfigReloadMixin` in `app/runtime/reload.py`
**How it works:**
1. Inherit `ConfigReloadMixin`.

View File

@@ -1,18 +1,15 @@
# 05 - Architecture and Modules
## Dependency Model
## Directory Model
MoviePilot uses explicit capability packages instead of the historical
`app/core`, `app/helper`, and `app/utils` buckets. Physical Python source must
not be added back under those paths. They exist only as virtual compatibility
packages for installed plugins.
MoviePilot keeps the established product packages such as `app/chain`,
`app/agent`, `app/modules`, `app/db`, `app/api`, `app/startup` and
`app/workflow` in their original locations. The historical `app/core`,
`app/helper` and `app/utils` roots are virtual compatibility packages only;
physical Python sources must not be recreated there.
Every migrated capability module and boundary package is required to stay out
of Python-module import cycles. The gate builds the complete application graph
so a cycle through an unmigrated caller is still detected. Startup code is the
composition root: it wires callbacks, resolvers, and adapters into lower-level
managers instead of letting those managers import and instantiate higher-level
services.
Capabilities migrated out of those legacy roots are organized by technical
responsibility:
```text
Entrypoints / Plugins
@@ -21,230 +18,254 @@ Entrypoints / Plugins
API / Agent / CLI / Scheduler / Workflow
|
v
Chain orchestration -----> Modules / DB / Services
| |
+-------------------------+
|
v
Domain / Platform contracts and state
|
v
Foundation and infrastructure adapters
Chain orchestration ---------> Application services
| |
+----------> Modules / DB <----+
|
v
Domain / Runtime contracts
|
v
Foundation / Adapters
Startup composes managers, adapters, diagnostics, and error callbacks.
Compatibility aliases and the plugin SDK are boundary packages, never
dependencies of canonical implementation modules.
Startup remains the composition root. SDK and compatibility are boundaries,
not dependencies of canonical implementation modules.
```
## Canonical Capability Packages
Directory grouping does not override dependency direction. The architecture
gate builds the complete Python module graph and rejects cycles even when a
cycle passes through an established package that was not moved.
## Canonical Migrated Packages
| Package | Ownership |
|---|---|
| `app/foundation/` | Reusable low-level mechanisms with no MoviePilot business/config dependency: HTTP clients, dynamic module loading, crypto, DOM, identity, URL, version, singleton, text segmentation, and data structures |
| `app/domain/` | Pure business semantics for media, recognition, sites, and torrents; configuration, persistence, and acceleration are injected; detailed below |
| `app/platform/` | Process-wide config, events, complete logging runtime, cache contracts/in-memory policy, execution policy, localization, scheduling, runtime lifecycle, concurrency, GC monitoring, and rate limits |
| `app/infrastructure/` | Configured runtime adapters for Redis/file cache, standard streams, browser, DNS/network, RSS, resources, packages, OS, Rust acceleration, and generated site resources |
| `app/extensions/` | Runtime module, plugin, and service discovery/lifecycle management |
| `app/integrations/` | Concrete product/ecosystem integrations: plugin markets and repositories, CookieCloud, IP-location providers, OCR, and remote MoviePilot service |
| `app/messaging/` | Agent-message bridge, message rendering/routing, and interactions |
| `app/security/` | Authentication, authorization, URL/path safety, SSRF protection, OTP, cookies, passkeys, and two-factor authentication |
| `app/services/` | Focused application services: audio, directory, downloader/media-server/storage selection, notification selection, media-server normalization/matching, persisted recognition/filter rules, formatting, image, torrent I/O, and transfer history |
| `app/agent/skills/` | Agent Skill metadata, market discovery, installation, and local lifecycle; importing it must not initialize the Agent orchestrator |
| `app/foundation/` | Stateless, config-free and I/O-free primitives: reflection and dynamic import, crypto, DOM parsing, identity, collections, singleton, text conversion/segmentation, URL and version helpers |
| `app/domain/` | Pure MoviePilot business semantics for media, recognition, sites and torrents; live configuration, persistence, transport and acceleration are injected |
| `app/application/` | Focused stateful application services, configured capability selection and service-bound rules |
| `app/runtime/` | Process-wide config, events, complete logging runtime, cache contracts/in-memory policy, execution, localization, scheduling, restart state, concurrency, GC and rate limits |
| `app/adapters/` | Concrete technical I/O and named external ecosystems, split by cache, network, system and external boundaries |
| `app/sdk/` | Stable, deliberately curated imports for plugin authors |
| `app/compat/` | Standard-library-only legacy import routing and DEBUG diagnostics |
`app/chain/` remains the application orchestration layer and `app/modules/`
remains the collection of pluggable backend implementations. A package name
describes ownership; it does not authorize a dependency cycle. The architecture
gate checks the complete module graph, including imports outside these packages.
The packages above are the only top-level roots created by the legacy-module
refactor. Existing product roots remain unchanged rather than being moved only
to make the directory tree look symmetrical.
### Application boundaries
| Path | Ownership |
|---|---|
| `app/application/*.py` | Audio, directory, downloader, filter, formatting, transfer history, image, media-server, notification, recognition, RSS, storage and torrent application services |
| `app/application/site/` | Configured site catalog, authentication level and index-resource capability; the generated extension and its data bundle stay together here |
| `app/application/messaging/` | Message rendering/routing, interactions and the Agent-to-message bridge |
| `app/application/security/` | Authentication, authorization, cookies, passkeys, OTP/two-factor, path/URL safety, SSRF and signing policy |
Application services may use domain rules, runtime contracts, Oper classes and
adapters. Multi-domain workflows still belong in the existing `app/chain/`
package. `Chain`, `Service` and `Manager` remain class patterns; they do not
create additional top-level directory categories.
### Runtime boundaries
| Path | Ownership |
|---|---|
| `app/runtime/config.py` | Deployment configuration and resolved runtime settings |
| `app/runtime/events.py` | Event contracts, dispatch and resolver registration |
| `app/runtime/log.py` | Complete console/plugin/file logging runtime and shutdown |
| `app/runtime/cache.py` | Cache protocols, memory implementations, decorators and proxies |
| `app/runtime/state.py` | Process restart and update state |
| `app/runtime/extensions/` | Module, plugin and configured-service discovery/registration/lifecycle |
| `app/runtime/compat/` | Standard-library-only exact legacy import routing and DEBUG diagnostics |
`app/startup/` remains the established composition root and is not nested under
runtime. It injects providers and callbacks, orders initialization/shutdown and
decides restart policy. Lower-level runtime modules must not import startup.
### Adapter boundaries
| Path | Ownership |
|---|---|
| `app/adapters/cache/` | Redis and filesystem cache implementations and Redis clients |
| `app/adapters/network/` | Generic HTTP, browser, DNS, Cloudflare and IP transport mechanisms |
| `app/adapters/system/` | OS/filesystem/process facilities, stdio, display, packages, resources and optional Rust acceleration |
| `app/adapters/external/` | CookieCloud, plugin market, OCR, IP-location providers and MoviePilot Server |
Generic protocol transport belongs in `adapters/network`; a named product or
ecosystem workflow belongs in `adapters/external`. An adapter may depend on
foundation, domain models, schemas and narrowly required runtime contracts, but
must not import application services, `runtime/extensions`, `runtime/compat` or
the plugin SDK.
RSS is not classified as a transport adapter merely because it uses HTTP. The
current `RssHelper` combines feed parsing, torrent item semantics, configured
site-specific URL discovery and browser fallback, so it belongs to
`app/application/rss.py` and consumes network adapters. Likewise, the generated
site extension owns the configured catalog/authentication/index capability and
lives in `app/application/site/`; only its download and file installation
mechanism remains in `app/adapters/system/resource.py`.
`app/foundation/crypto.py` stays in foundation because it contains only generic
RSA, digest and CryptoJS-compatible AES primitives and has no settings, policy,
I/O or logging. Authentication, token, passkey, signing and two-factor policy
still belongs in `app/application/security/`; callers decide how cryptographic
failures are reported.
### Domain subdomains
`app/domain/` is a business-capability package, not a synonym for every file
whose name mentions media, site, or torrent:
`app/domain/` is a business package, not a synonym for every file whose name
mentions media, site or torrent:
| Subdomain | Modules and ownership |
|---|---|
| Media | `context.py` owns `MediaInfo`, `TorrentInfo`, music models, and use-case context; `media.py` owns source/ID normalization; `scraper.py` owns Kodi-style NFO reading and media metadata document generation |
| Recognition | `metainfo.py`, `meta/`, and `tokens.py` parse names, paths, release groups, streaming platforms, anime, video, and music metadata |
| Site | `site.py` interprets site HTML into business states such as logged-in and checked-in; generic HTTP transport remains foundation and configured browser access remains infrastructure |
| Torrent | Torrent identity and title semantics live in the context/recognition model; downloading, caching, and parsing torrent files lives in `services/torrent.py` |
| Shared business text | `string.py` retains MoviePilot-specific media/site/torrent text normalization pending concern-level extraction; new generic primitives must not be added to it |
| Media | `context.py` owns `Context`, `MediaInfo` and `TorrentInfo`; `media.py` owns source/ID normalization; `scraper.py` owns Kodi-style NFO reading and metadata document generation |
| Recognition | `metainfo.py`, `meta/` and `tokens.py` parse names, paths, release groups, streaming platforms, anime, video and music metadata |
| Site | `site.py` interprets HTML into business states such as logged-in and checked-in; configured catalog/auth/index resources stay in `app/application/site/`, DOM parsing stays in foundation and network access stays in adapters |
| Torrent | Identity/title semantics live in the domain model; configured download/cache/file behavior stays in `app/application/torrent.py` |
| Shared business text | `string.py` contains MoviePilot-specific media/site/torrent normalization; generic text primitives stay in `app/foundation/text.py` |
Filter-rule meaning is part of the torrent/filter domain, but
`services/filter.py` reads user-persisted rule configuration and is
therefore an application service rather than a pure domain module.
`app/domain` may depend only on schemas and foundation. It must not read global
settings, access DB/network/filesystem adapters, import Rust, discover services
or initialize process runtime state.
Recognition follows the same boundary: `services/recognition.py` reads
`SystemConfigOper`; `startup/domain_initializer.py` injects live rule providers,
file-extension policy, TMDB image URL construction, source defaults, and the
optional Rust accelerator into pure domain modules.
## Established Packages That Stay in Place
## Shared File Placement Rule
The following roots predate this migration and must not be moved or renamed as
part of migrated-capability cleanup:
Before creating a file, first decide which capability package owns it and check
whether an existing domain file already provides that capability. Create a new
file only for a genuinely separate concern and name it according to
`07-naming-conventions.md`.
- `app/agent/`
- `app/api/`
- `app/chain/`
- `app/db/`
- `app/doctor/`
- `app/modules/`
- `app/monitor/`
- `app/plugins/`
- `app/schemas/`
- `app/startup/`
- `app/testing/`
- `app/workflow/`
Do not create generic `common`, `helper`, or `utils` buckets. A reusable function
still needs an owner:
Necessary canonical import updates are allowed; changing their physical layout
or product responsibilities requires a separate architectural decision.
- Generic code that does not read MoviePilot business/config state belongs in `app/foundation/`, including reusable protocol clients and reflection helpers.
- Core media-specific rules belong in `app/domain/`; rules tied specifically to
configured media-server representations belong in `app/services/mediaserver.py`.
- Configuration-aware runtime resources belong in `app/infrastructure/`; a
concrete external product or ecosystem belongs in `app/integrations/`.
- Stateful cross-domain behavior belongs in `app/services/` or `app/chain/`.
- Plugin-facing public imports belong in `app/sdk/`; canonical packages are not
automatically public plugin APIs.
## Placement Decision Order
## Entrypoint Layer
Use these questions in order before creating or moving a migrated capability:
**Directories:** `app/api/endpoints/`, `moviepilot` (CLI), `app/agent/`, scheduler
callbacks, webhook handlers, and message interactions.
1. Is it generic, stateless, independent of MoviePilot state and free of I/O?
Put it in `app/foundation`.
2. Is it a pure MoviePilot business rule/model? Put it in `app/domain`.
3. Does it read persisted configuration or coordinate one focused configured
capability? Put it in `app/application`.
4. Is it authentication, authorization, signing, SSRF, URL/path safety, OTP,
passkey or two-factor policy? Put it in `app/application/security`.
5. Is it message rendering, routing or interaction behavior? Put it in
`app/application/messaging`.
6. Is it process-wide configuration, events, logging, cache policy, execution,
scheduling, concurrency, GC or restart state? Put it in `app/runtime`.
7. Does it discover/manage modules, plugins or configured service providers?
Put it in `app/runtime/extensions`.
8. Does it perform concrete cache, network, OS/process, filesystem, stdio,
package/resource or Rust I/O? Put it under the matching `app/adapters`
technical boundary.
9. Does it implement a named external product/ecosystem? Put it in
`app/adapters/external`.
10. Is it public to plugins or only preserving an old path? Curate it in
`app/sdk` or map it in `app/runtime/compat`; never move implementation there.
Responsibilities:
Do not create generic `common`, `helper` or `utils` buckets. Reuse does not erase
ownership.
- Handle authentication, parameter parsing, response serialization, streaming,
and boundary validation.
- Call `app/chain/` for logic that coordinates modules, events, caches, or
workflows.
- Call an Oper class or focused service directly only for simple CRUD and input
normalization.
## Existing Chain, Module and DB Layers
Endpoints must not contain reusable business workflows. Register new API
endpoints in `app/api/apiv1.py`.
### Chain layer
## Chain Layer
`app/chain/` implements use cases shared by API, CLI, Agent, scheduler and other
entrypoints. Chains may coordinate modules, application services, Oper classes,
events and caches. New chain-to-chain dependencies are allowed only while the
static graph remains acyclic. Backend protocol details and HTTP request objects
do not belong here.
**Directory:** `app/chain/`
### Module layer
Chains implement use cases shared by API, CLI, agent, scheduler, and other
entrypoints. They may coordinate modules, services, Oper classes, events, and
caches.
`app/modules/` contains pluggable downloaders, media servers, metadata sources,
message channels, indexers and storage providers. New direct module-to-module or
module-to-chain dependencies are forbidden; cross-module orchestration belongs
in a chain. The directory remains unchanged because discovery and plugin code
depend on this established runtime root.
- Call module capabilities through `run_module()` or `async_run_module()`.
- Use `ModuleManager` directly only for enumeration, inspection, or health
checks.
- Chain-to-chain reuse is allowed only while the static dependency graph remains
acyclic.
- Do not place HTTP request objects or backend-specific protocol details here.
### DB / Oper layer
## Module Layer
**Directory:** `app/modules/`
Modules implement pluggable backends such as downloaders, media servers,
metadata sources, message channels, indexers, and storage providers.
- A module focuses on one backend or capability and returns domain results, not
HTTP responses.
- New direct `module -> module` or `module -> chain` dependencies are forbidden.
- Cross-module orchestration belongs in a chain.
- Shared backend-neutral behavior belongs in its owning canonical package.
Module categories are defined in `app/schemas/types.py`.
## DB / Oper Layer
**Directory:** `app/db/`
SQLAlchemy models live under `app/db/models/`; `*_oper.py` classes encapsulate
queries. Chains, modules, services, and endpoints must use those classes instead
of issuing SQLAlchemy queries directly. Every schema change requires an Alembic
migration under `database/versions/`.
SQLAlchemy models stay under `app/db/models/`; `*_oper.py` classes encapsulate
queries. Chains, modules, application services and endpoints use Oper classes
instead of issuing SQLAlchemy queries directly. Every schema change requires an
Alembic migration under `database/versions/`.
## Composition and Compatibility Boundaries
- `app/startup/` owns process composition. Lower layers expose explicit
registration or configuration functions for dependencies such as event
resolvers and error reporters.
- Cache contracts, memory implementations, decorators, and proxies live in
`app/platform/cache.py`; Redis and file I/O implementations live in
`app/infrastructure/cache.py`. Startup registers concrete factories before
importing modules that instantiate cache decorators.
- The complete logging runtime lives in `app/platform/log.py`: policy,
console/plugin routing, async rotating file output, and shutdown.
`app.platform.config` supplies the resolved settings and log path.
`platform/log.py` is enforced as a dependency leaf with no `app.*` imports.
Foundation modules do not emit runtime logs; their callers decide whether a
returned fallback or raised error should be logged. Plugins use `app.sdk.logging`;
legacy `app.log` resolves to that SDK facade.
- Resource adapters only report whether installation succeeded. Process restart
policy belongs to `app/startup/modules_initializer.py`.
- Configured notification-service discovery lives in
`app/services/notification.py`. Web Push subscription and manual-send HTTP
behavior lives directly in `app/api/endpoints/message.py`, not in messaging.
- `app/compat/` may not import canonical MoviePilot implementation modules at
import time. Its manifest stores strings and resolves aliases lazily.
- Canonical packages may not import `app.compat` or `app.sdk`.
- Startup registers concrete cache factories before decorated business modules
are imported. Cache contracts remain in `app/runtime/cache.py`; Redis/file
implementations remain in `app/adapters/cache/backends.py`.
- `app/runtime/log.py` is a dependency leaf with no `app.*` imports. Foundation
emits no runtime logs; upper-layer owners decide whether failures are
operationally relevant.
- `app/adapters/system/resource.py` only reports whether installation occurred;
`app/startup/modules_initializer.py` supplies the loaded site-resource
versions and decides whether to restart. The adapter never imports the site
application service.
- Configured notification discovery lives in
`app/application/notification.py`. Web Push subscription and manual-send HTTP
behavior stays in `app/api/endpoints/message.py`.
- `app/runtime/compat` stores string mappings and resolves aliases lazily. It may
not eagerly import canonical MoviePilot modules.
- Canonical implementation packages may not import `app/runtime/compat` or
`app/sdk`.
- Host code uses canonical paths. Only `app/plugins/` and compatibility tests
may use legacy `app.core`, `app.helper`, or `app.utils` paths.
- New plugins use `app.sdk`. In DEBUG mode, legacy plugin imports work but emit
one actionable warning per plugin and legacy module.
- Delayed imports are not accepted as a way to hide a dependency cycle.
may use `app.core`, `app.helper`, `app.utils` or `app.log`.
- New plugins use `app.sdk`. In DEBUG mode, a legacy plugin import remains
functional and emits one actionable warning per plugin and legacy module.
- Delayed imports are not accepted as a way to hide dependency cycles.
## Permitted Call Directions
| Direction | Status |
|---|---|
| `entrypoint -> chain / service / Oper` | Allowed according to workflow complexity |
| `chain -> module / service / Oper / canonical capability` | Allowed |
| `entrypoint -> chain / application / Oper` | Allowed according to workflow complexity |
| `chain -> module / application / Oper / canonical capability` | Allowed |
| `application -> domain / runtime / adapter / Oper` | Allowed |
| `module -> canonical capability / Oper` | Allowed |
| `module -> module / chain` | Forbidden for new code |
| `adapter -> application / runtime.extensions / sdk / compat` | Forbidden |
| `domain -> runtime / adapter / application / DB` | Forbidden |
| `foundation -> other app packages` | Forbidden |
| `canonical implementation -> sdk / compat` | Forbidden |
| `compat -> canonical implementation at module import time` | Forbidden; aliases resolve lazily |
| `foundation -> other app capability packages` | Forbidden |
| `compat -> canonical implementation at module import time` | Forbidden |
| Any import that creates a module-level cycle | Forbidden |
## Key File Locations
| Path | Purpose |
|---|---|
| `app/api/apiv1.py` | API router registration |
| `app/platform/config.py` | `ConfigModel`, `Settings`, and deployment configuration |
| `app/platform/events.py` | `EventManager`, `Event`, and event resolver registration |
| `app/extensions/module_manager.py` | Module discovery and lifecycle |
| `app/extensions/plugin_manager.py` | Plugin discovery and lifecycle |
| `app/foundation/module.py` | Generic Python module discovery and dynamic import |
| `app/foundation/http.py` | Shared synchronous and asynchronous HTTP clients |
| `app/infrastructure/rss.py` | Configured RSS retrieval and parsing adapter |
| `app/platform/cache.py` | Cache contracts, memory backend, decorators, and proxies |
| `app/infrastructure/cache.py` | Redis and filesystem cache adapters |
| `app/platform/gc.py` | Process memory observation and garbage-collection policy |
| `app/integrations/market.py` | Plugin repository discovery, compatibility, download, and installation |
| `app/integrations/location.py` | External IP-location provider integration |
| `app/agent/skills/registry.py` | Agent Skill discovery, market, and local lifecycle |
| `app/domain/context.py` | `Context`, `MediaInfo`, and `TorrentInfo` |
| `app/security/url.py` | URL/path validation, SSRF protection, and signed image URL policy |
| `app/services/filter.py` | Persistent user filter-rule lookup and media-context selection |
| `app/services/recognition.py` | Persistent recognition-rule lookup for domain injection |
| `app/services/mediaserver.py` | Configured media-server discovery, Provider ID normalization, and music-library matching |
| `app/startup/` | Runtime composition root |
| `app/compat/manifest.py` | Exact legacy-to-canonical import manifest |
| `app/runtime/config.py` | `ConfigModel`, `Settings` and deployment configuration |
| `app/runtime/events.py` | `EventManager`, `Event` and event resolver registration |
| `app/runtime/extensions/module_manager.py` | Module discovery and lifecycle |
| `app/runtime/extensions/plugin_manager.py` | Plugin discovery and lifecycle |
| `app/foundation/reflection.py` | Generic reflection and Python module discovery |
| `app/adapters/network/http.py` | Shared synchronous and asynchronous HTTP clients |
| `app/application/rss.py` | Configured RSS retrieval and parsing |
| `app/application/site/sites.*` | Generated site catalog, authentication and index capability plus its colocated data bundle |
| `app/runtime/cache.py` | Cache contracts, memory backend, decorators and proxies |
| `app/adapters/cache/backends.py` | Redis and filesystem cache adapters |
| `app/adapters/system/resource.py` | Runtime resource detection/download/installation |
| `app/adapters/external/market.py` | Plugin repository discovery and installation |
| `app/application/security/url.py` | URL/path validation, SSRF protection and signed image policy |
| `app/application/mediaserver.py` | Configured media-server discovery and identity matching |
| `app/runtime/compat/manifest.py` | Exact legacy-to-canonical import manifest |
| `app/sdk/` | Stable plugin imports |
| `database/versions/` | Alembic migrations |
## Where New Capabilities Go
| Scenario | Action |
|---|---|
| Shared business workflow | `app/chain/` |
| Stateful focused application behavior | `app/services/` or the owning capability package |
| New backend implementation | `app/modules/<backend>/` or `app/integrations/` |
| New public HTTP endpoint | `app/api/endpoints/`, registered in `app/api/apiv1.py` |
| Generic primitive, protocol client, or reflection mechanism | `app/foundation/` |
| Media-domain parsing or rule | `app/domain/` |
| Configuration-aware network, filesystem, process, feed, or generated resource adapter | `app/infrastructure/` |
| Concrete third-party product or ecosystem integration | `app/integrations/` |
| Deployment/startup setting | `ConfigModel` in `app/platform/config.py` |
| Runtime user-editable option | `SystemConfigKey` plus `SystemConfigOper` |
| New supported plugin API | Curated export in `app/sdk/` with compatibility tests |
Run `tests/test_architecture_dependencies.py` after every ownership or import
change. It rejects physical legacy sources, host legacy imports, implementation
dependencies on SDK/compat, and any strongly connected component containing a
canonical migrated module.
change. It rejects physical legacy or retired canonical sources, forbidden
upward dependencies, SDK/compat backreferences and any strongly connected
component containing a migrated module.
*Last Updated: 2026-08-14*

View File

@@ -25,7 +25,7 @@
- All request body and response models must be defined as Pydantic `BaseModel` subclasses in `app/schemas/`.
- Use `Field(...)` for required fields; use `Field(default=...)` or `Field(None)` for optional fields.
- Do not define ad-hoc `dict` return types for API responses — define a schema class.
- Settings and deployment configuration live in `ConfigModel` / `Settings` in `app/platform/config.py` using `pydantic-settings`.
- Settings and deployment configuration live in `ConfigModel` / `Settings` in `app/runtime/config.py` using `pydantic-settings`.
- Use `model_validator` for cross-field validation logic.
---
@@ -34,7 +34,7 @@
- Prefer `async def` for I/O-bound operations (network requests, database queries, file operations).
- Use `await` consistently; do not mix sync and async code paths in the same function without using `run_in_threadpool` from FastAPI or `asyncio.to_thread`.
- For CPU-bound work that must not block the event loop, submit to `ThreadHelper` (see `app/platform/thread.py`).
- For CPU-bound work that must not block the event loop, submit to `ThreadHelper` (see `app/runtime/thread.py`).
- Do not use bare `threading.Thread` in new code; use `ThreadHelper.submit()`.
---
@@ -84,7 +84,7 @@ except:
## Logging
- Host code uses `logger` from `app.platform.log`; new plugins use `app.sdk.logging`. The historical `app.log` path is compatibility-only. Do not import the standard library `logging` directly in application code.
- Host code uses `logger` from `app.runtime.log`; new plugins use `app.sdk.logging`. The historical `app.log` path is compatibility-only. Do not import the standard library `logging` directly in application code.
- Log levels:
- `logger.debug(...)` — detailed diagnostic information, disabled by default.
- `logger.info(...)` — normal operational events.
@@ -107,7 +107,7 @@ except:
- Private functions in the same file are preferable to extracting a new module for single-use logic.
- Add code to the canonical capability package that owns it, and extend an existing domain file whenever that domain already exists.
- Do not recreate generic `core`, `helper`, or `utils` buckets; see `05-architecture.md` for placement rules.
- New files should use a focused noun name; a role suffix is appropriate only when it distinguishes ownership, such as `plugin_manager.py`; otherwise prefer the package-owned noun, such as `infrastructure/package.py`.
- New files should use a focused noun name; a role suffix is appropriate only when it distinguishes ownership, such as `plugin_manager.py`; otherwise prefer the package-owned noun, such as `adapters/system/package.py`.
- Keep files focused on one domain concern.
---

View File

@@ -12,7 +12,7 @@
- Retry logic
```python
from app.foundation.http import RequestUtils
from app.adapters.network.http import RequestUtils
res = RequestUtils(
ua=settings.USER_AGENT,
@@ -136,7 +136,7 @@ Internal notifications use the `Notification` schema and the event system:
```python
from app.schemas import Notification
from app.schemas.types import NotificationType, MessageChannel
from app.platform.events import eventmanager
from app.runtime.events import eventmanager
from app.schemas.types import EventType
eventmanager.send_event(

View File

@@ -120,14 +120,14 @@ oper.set(user_id=1, key="notification_enabled", value=True)
**Purpose:** Deployment-level, environment-level, and startup-time configuration such as ports, paths, proxies, switches, API keys, and third-party service addresses.
**Location:** `ConfigModel` and `Settings` in `app/platform/config.py`
**Location:** `ConfigModel` and `Settings` in `app/runtime/config.py`
These values are read from environment variables (or `.moviepilot.env`) at startup and are immutable at runtime. They are not stored in the database.
**Access:**
```python
from app.platform.config import settings
from app.runtime.config import settings
host = settings.QB_HOST
port = settings.QB_PORT
@@ -139,12 +139,12 @@ port = settings.QB_PORT
### FileCache / AsyncFileCache
**Location:** `app/platform/cache.py`
**Location:** `app/runtime/cache.py`
Used to cache expensive external API responses to disk. Cache entries have a configurable TTL.
```python
from app.platform.cache import FileCache, fresh
from app.runtime.cache import FileCache, fresh
cache = FileCache(cache_name="tmdb", ttl=3600)

View File

@@ -15,7 +15,7 @@ pytest
### When to Expand Scope
Run the full test suite when changing:
- `app/platform/`, `app/extensions/`, or `app/compat/` - config, events, managers, and compatibility boundaries
- `app/runtime/`, `app/adapters/`, or `app/runtime/compat/` - config, events, managers, adapters, and compatibility boundaries
- `app/chain/__init__.py` — chain base class
- `app/modules/__init__.py` — module base class
- `app/main.py` — application startup

View File

@@ -22,7 +22,7 @@ python tests/run.py # 等价于 pytest 全量(参数透
收集任何测试模块、`import app.*` **之前**,conftest 完成两件事:
1. **临时库**:把 `CONFIG_DIR` 指向临时目录并 `init_db()` 建表。`app.db` 在导入期即按 `CONFIG_PATH` 连接 `user.db`,所以必须早于首个 `import app.*`;空库会让运行期查表报 `no such table`,故必须建表。
2. **`app.infrastructure.sites` 垫片**:该模块由独立仓库动态拉取、CI 无此文件,conftest 统一补最小垫片(本地存在真实模块时优先用真实模块)。兼容层会把旧插件的 `app.helper.sites` 导入路由到同一模块。
2. **`app.application.site.sites` 垫片**:该模块由独立仓库动态拉取、CI 无此文件,conftest 统一补最小垫片(本地存在真实模块时优先用真实模块)。兼容层会把旧插件的 `app.helper.sites` 导入路由到同一模块。
由此推出两条**硬规范**: