modify proxy handler

This commit is contained in:
2025-11-17 12:21:35 +08:00
parent 760e4a9b03
commit abfa51f12e
19 changed files with 755 additions and 52 deletions

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Proxy Module Delegation
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2025-11-17
**Feature**: specs/005-proxy-module-delegation/spec.md
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Checklist completed; no blocking issues found.***

View File

@@ -0,0 +1,13 @@
# Contracts: Proxy Module Delegation
No external API surface changes are introduced by this feature. The core contract is the module handler interface used by the Proxy Dispatcher:
- **Handler Contract (conceptual)**: `Handle(ctx, route)` processes requests for a given route/module, applies module-defined caching/rewrite, and returns structured logs with `module_key`, `hub`, `domain`, `cache_hit`, `upstream_status`, `request_id`.
- **Registration Contract**: Modules must register both metadata and handler; missing handlers must fail fast at startup.
If future external endpoints are added, document them here with request/response schemas.
## Error Behaviors
- **module_handler_missing**: Forwarder无法找到给定 module_key 的 handler 时返回 `500 {"error":"module_handler_missing"}`,并记录 `hub/domain/module_key/rollout_flag` 等日志字段,便于排查配置缺失或注册遗漏。
- **module_handler_panic**: Module handler panic 被捕获后返回 `500 {"error":"module_handler_panic"}`,同时输出结构化日志 `error=module_handler_panic`,防止进程崩溃并提供观测。

View File

@@ -0,0 +1,43 @@
# Data Model: Proxy Module Delegation
## Entities
- **Hub Module**
- Attributes: `module_key`, `description`, `supported_protocols`, `cache_strategy` (ttl_hint, validation_mode, disk_layout, supports_streaming_write), `locator_rewrite`
- Behavior: Registers into global registry; binds to a module handler.
- Constraints: module_key unique; handler must be registered.
- **Module Handler**
- Attributes: `module_key`, `handle(request, route)` entrypoint; owns cache policy/rewrites; error mapping.
- Relationships: One-to-one with Hub Module; invoked by Proxy Dispatcher.
- Constraints: Must produce structured logs (hub, domain, module_key, cache_hit, upstream_status, request_id).
- **Proxy Dispatcher**
- Attributes: handler map (module_key → handler), default handler fallback.
- Behavior: Lookup by route.ModuleKey and invoke handler; wraps errors/logging.
- Constraints: If handler missing, return 5xx with observable logging.
- **Cache Policy**
- Attributes: `ttl_hint`, `validation_mode`, `disk_layout`, `requires_metadata_file`, `supports_streaming_write`, module-specific locator rewrite.
- Behavior: Used by module handlers to govern caching and revalidation.
## Relationships
- Hub Module 1:1 Module Handler (per module_key).
- Proxy Dispatcher 1:N Module Handler (registered handlers).
- Module Handler uses Cache Policy defined by its Hub Module.
## Identity & Uniqueness
- `module_key` is the unique identifier for module registration and dispatch.
- Handler map keys must not collide; duplicates cause startup failure.
## State & Lifecycle
- Registration (init/startup) → Handler binding → Runtime dispatch.
- Missing handler or duplicate registration causes startup rejection.
## Volume/Scale Assumptions
- Number of modules small (handful of warehouse types). Handler map fits in memory.
- Cache size/TTL managed per module; relies on existing filesystem cache layout.

View File

@@ -0,0 +1,81 @@
# Implementation Plan: Proxy Module Delegation
**Branch**: `005-proxy-module-delegation` | **Date**: 2025-11-17 | **Spec**: specs/005-proxy-module-delegation/spec.md
**Input**: Feature specification from `/specs/005-proxy-module-delegation/spec.md`
**Note**: This file captures planning up to Phase 2 (tasks generated separately).
## Summary
目标:让通用 proxy 只做路由分发,所有仓类型的缓存/回源/重写/错误处理下沉到各自 hubmodule handler新增仓类型仅需新增模块与 handler不再修改通用 proxy 分支同时保持现有仓docker/npm/pypi/composer/go功能与日志不回归。技术路线调整模块注册/调度接口,模块自管理缓存策略与路径重写,通用层只封装调度、统一日志与错误包装。
## Goals & Constraints Recap
- 通用层职责最小化:仅路由映射与 handler 调度,无类型分支或缓存策略逻辑。
- 模块自洽:每个模块自带元数据、缓存策略、路径重写与 handler新增模块不改通用代码。
- 兼容优先:现有仓库的缓存/日志/响应行为保持等价;日志字段保持 hub/domain/module_key/cache_hit/upstream_status/request_id。
- 控制面统一:所有行为仍由 `config.toml` 控制,缺失或重复模块注册需启动前失败。
## Technical Context
**Language/Version**: Go 1.25+ (静态链接,单二进制交付)
**Primary Dependencies**: Fiber v3HTTP 服务、Viper配置、Logrus + Lumberjack结构化日志 & 滚动)、标准库 `net/http`/`io`
**Storage**: 本地文件系统缓存目录 `StoragePath/<Hub>/<path>`(按模块定义的布局)
**Testing**: `go test ./...`,使用 `httptest`、临时目录和上游伪服务验证配置/缓存/代理路径
**Target Platform**: Linux/Unix CLI 进程,由 systemd/supervisor 管理,匿名下游客户端
**Project Type**: 单 Go 项目(`cmd/` 入口 + `internal/*` 包)
**Performance Goals**: 缓存命中直接返回;回源路径需流式转发,单请求常驻内存 <256MB命中/回源日志可追踪
**Constraints**: 禁止 Web UI 或账号体系;所有行为受单一 TOML 配置控制;每个 Hub 需独立 Domain 绑定;仅匿名访问
**Scale/Scope**: 支撑 Docker/NPM/Go/PyPI/Composer 多仓代理,面向弱网及离线缓存复用场景
## Current Dispatch & Branching (现状与移除点)
- router 层 (`internal/server/router.go`) 通过 `ensureRouterHubType` 针对 hub_type 做白名单;需移除类型判断,改为 module_key→handler 是否注册的检查。
- proxy 层 (`internal/proxy/handler.go`) 通过 `ensureProxyHubType` 再次按 hub_type 分支;迁移后应删除,转由模块 handler 自己决定支持策略。
- forwarder (`internal/proxy/forwarder.go`) 维护 module_handler map但默认 handler 仍被类型检查阻断;目标是保留 map/lookup去除类型特例。
- 移除点:去掉 hub_type 判定与每类型的特化分支将错误处理集中在“handler 缺失/异常”路径;模块内保留各自策略。
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
- Feature 仍然是“轻量多仓 CLI 代理”,未引入 Web UI、账号体系或与代理无关的能力。
- 仅使用 Go + 宪法指定依赖;任何新第三方库都已在本计划中说明理由与审核结论。
- 行为完全由 `config.toml` 控制,新增配置项已规划默认值、校验与迁移策略。
- 方案维持缓存优先 + 流式回源路径,并给出命中/回源/失败的日志与观测手段。
- 计划内列出了配置解析、缓存读写、Host Header 路由等强制测试与中文注释交付范围。
## Project Structure
### Documentation (this feature)
```text
specs/[###-feature]/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
```text
cmd/any-hub/main.go # CLI 入口、参数解析
internal/config/ # TOML 加载、默认值、校验
internal/server/ # Fiber 服务、路由、中间件
internal/cache/ # 磁盘/内存缓存与 .meta 管理
internal/proxy/ # 上游访问、缓存策略、流式复制
configs/ # 示例 config.toml如需
tests/ # `go test` 下的单元/集成测试,用临时目录
```
**Structure Decision**: 采用单 Go 项目结构,特性代码应放入上述现有目录;如需新增包或目录,必须解释其与 `internal/*` 的关系并给出后续维护策略。
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| *(none)* | - | - |

View File

@@ -0,0 +1,31 @@
# Quickstart: Proxy Module Delegation
1) 检出分支
```bash
git checkout 005-proxy-module-delegation
```
2) 跑现有测试基线
```bash
go test ./...
```
3) 添加新模块示例(开发)
-`internal/hubmodule/<module>` 下实现元数据,并在 `init()` 中调用 `hubmodule.MustRegister`
- 为该模块实现专属 handler可基于 `internal/proxy/handler.go` 拓展),在启动时通过 `proxy.RegisterModule(proxy.ModuleRegistration{Key: "<module_key>", Handler: yourHandler})` 绑定。
-`config.toml` 中把目标 Hub 的 `Module` 字段设为这个 `module_key`
4) 启动代理验证
```bash
make run
# or
go run . --config ./config.toml
```
5) 验证缓存与日志
- 对同一路径请求两次,观察首次 cache_hit=false、二次 cache_hit=true日志包含 module_key/hub/domain/upstream_status。
- 验证缺失 handler 时返回 5xx 且日志含错误字段。
6) 更新文档与计划
- 填充 tasks 清单(/speckit.tasks
- 提交前复查 `specs/005-proxy-module-delegation` 下的设计/研究文件。

View File

@@ -0,0 +1,19 @@
# Research: Proxy Module Delegation
## Decisions
- **模块调度边界**: 通用 proxy 仅负责路由到 module handler所有缓存/回源/重写由模块内实现。
- **Rationale**: 减少跨类型分支,新增仓无需改通用层,风险集中在各自模块。
- **Alternatives**: 保留通用 handler + 按类型分支(现状);放弃模块化,统一代码路径。均会牵扯多处改动且增加回归面,故弃用。
- **模块注册契约**: hubmodule 注册需同时提供元数据和 handler 绑定接口;缺 handler 视为配置错误。
- **Rationale**: 避免运行期静默回落,统一观测与错误路径。
- **Alternatives**: 允许回退到 legacy handler但会掩盖缺失违背模块自洽目标。
- **现有仓兼容**: docker/npm/pypi/go/composer 模块保留各自策略与路径重写,迁移时不得改变对外响应/日志字段。
- **Rationale**: 避免生产回归;满足 SC-001/SC-004。
- **Alternatives**: 统一一套通用策略;但会改变缓存键/TTL引入不必要风险。
## Clarifications Resolved
- None pending; spec中无 NEEDS CLARIFICATION。

View File

@@ -0,0 +1,97 @@
# Feature Specification: Proxy Module Delegation
**Feature Branch**: `005-proxy-module-delegation`
**Created**: 2025-11-17
**Status**: Draft
**Input**: User description: "通用的代理模块 internal/proxy 目录中存在大量的if判定对不同代理类型进行特殊化处理我想要的是在 hubmodule 中各自类型的代理完成自己缓存和代理功能的控制内部管理外部的proxy只负责把请求分发给不同类型的代理模块代理调度 internal/proxy/handler.go 不存在对任何类型代理的兼容和特殊性处理。请优化这块代码布局和逻辑分支请使用005开头。"
> 宪法对齐v1.0.0
> - 保持“轻量、匿名、CLI 多仓代理”定位:不得引入 Web UI、账号体系或与代理无关的范围。
> - 方案必须基于 Go 1.25+ 单二进制,依赖仅限 Fiber、Viper、Logrus/Lumberjack 及必要标准库。
> - 所有行为由单一 `config.toml` 控制;若需新配置项,需在规范中说明字段、默认值与迁移策略。
> - 设计需维护缓存优先 + 流式传输路径,并描述命中/回源/失败时的日志与观测需求。
> - 验收必须包含配置解析、缓存读写、Host Header 绑定等测试与中文注释交付约束。
## User Scenarios & Testing *(mandatory)*
### User Story 1 - 按模块扩展新仓类型 (Priority: P1)
作为平台工程师,我可以通过新增一个 hubmodule 模块(含元数据与代理实现)注册到系统,而不用改动通用 proxy即可支持新的仓库类型并完成缓存与回源逻辑。
**Why this priority**: 模块化是本次改造的核心目标,新仓类型落地必须依赖这一能力。
**Independent Test**: 仅新增一个示例模块并注册后,发起请求可完成回源与缓存,且无需修改通用 proxy 代码路径。
**Acceptance Scenarios**:
1. **Given** 新模块已在 hubmodule 注册,且 proxy 注册了对应 handler**When** 针对该模块域名发起 GET 请求,**Then** 请求被模块逻辑处理并写入缓存,日志包含 module_key。
2. **Given** 新模块没有覆写通用逻辑之外的分支,**When** 第二次请求同一资源,**Then** 返回缓存命中并不触发通用 proxy 中的类型分支。
---
### User Story 2 - 现有仓类型平滑迁移 (Priority: P1)
作为运维人员,我希望 Docker/NPM/PyPI/Composer 等已有仓在改造后行为不变,仍能缓存命中、回源、日志字段齐全。
**Why this priority**: 需要保证功能零回归,维护现网可用性。
**Independent Test**: 对每种仓库重复请求同一资源,两次请求分别观察首次 miss、二次 hit 的头与日志字段。
**Acceptance Scenarios**:
1. **Given** 缓存为空,**When** 首次请求 Docker manifest**Then** 回源成功、写入缓存,日志包含 cache_hit=false、module_key=docker。
2. **Given** 同一资源已缓存,**When** 第二次请求,**Then** 返回缓存cache_hit=true 且未触发任何 hub_type 判定错误。
---
### User Story 3 - 统一观测与错误处理 (Priority: P2)
作为 SRE我希望通用 proxy 仅负责调度,但仍能输出一致的请求日志与错误响应,即使模块缺失或模块内部出错。
**Why this priority**: 观测和故障定位需要统一格式,不因模块化而分裂。
**Independent Test**: 刻意注册缺失 handler 或让模块返回错误,观察通用层日志与响应代码符合约定。
**Acceptance Scenarios**:
1. **Given** 请求路由到未注册 handler 的模块,**When** 发起请求,**Then** 返回 5xx 并记录 module_key、hub、domain、error。
2. **Given** 模块内部返回错误,**When** 请求失败,**Then** 通用层仍输出结构化日志,错误码与 message 对齐错误策略。
---
### Edge Cases
- 如果 hub 的 module_key 未注册或 handler 未绑定,调度层应快速返回可观测的 5xx并记录 module_key、hub、domain、request_id。
- 模块 handler panic 或超时,通用 proxy 应捕获并返回统一错误响应,避免进程崩溃。
- 配置缺失或模块注册失败时,启动阶段需拒绝加载并给出清晰的报错,而非运行时才暴露。
- 请求方法不被模块支持(如 HEAD/PUT模块应返回合理状态码通用层不做类型判断。
- 缓存键或路径重写由模块负责,通用层不应叠加额外重写,避免路径错乱。
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: 通用 proxy 层只负责路由匹配与将请求分发给对应 module handler不再包含按 hub_type/module 的逻辑分支。
- **FR-002**: hubmodule 为每个仓类型提供独立的 handler/策略入口,包含缓存命中、回源、重写等行为,通用层无需了解细节。
- **FR-003**: Module 注册应同时提供元数据module_key、支持协议、默认策略与运行时 handler 绑定;缺失 handler 时请求需返回可观测错误。
- **FR-004**: 现有仓类型docker、npm、pypi、composer、go改造后行为与现状等价首次请求 miss 返回 200+cache miss二次请求命中缓存且日志字段不变hub、domain、module_key、cache_hit、upstream_status、elapsed_ms、request_id
- **FR-005**: 统一错误与超时处理:模块内部错误或 panic 被捕获并转化为 5xx JSON 响应,日志含 error、module_key、hub、domain。
- **FR-006**: 配置校验/启动流程应在模块注册缺失或重复时直接失败,并输出明确错误信息。
- **FR-007**: 支持新增模块的可插拔模式:新增模块仅需新增 hubmodule 包和 handler 注册,不需要改动通用 proxy 调度代码。
- **FR-008**: 保持现有缓存读写与流式返回路径:缓存命中直接返回,未命中流式回源并写缓存;各模块可自定义缓存键/TTL/验证策略。
### Key Entities
- **Hub Module**: 描述仓类型的元数据和代理行为缓存策略、路径重写、handler 入口)。
- **Module Handler**: 由模块实现的请求处理器,负责缓存、回源、重写、错误处理。
- **Proxy Dispatcher**: 通用层组件,仅根据路由/module_key 寻址 handler 并执行;提供统一日志、错误包装。
- **Cache Policy**: 由模块定义的 TTL、验证策略和路径布局用于缓存命中/重写决策。
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: 对 docker/npm/pypi/composer/go 各执行“首次 miss、二次 hit”请求链路返回的 `cache_hit``module_key``hub``domain` 日志字段保持现有值,命中率达到 100% 在重复请求场景。
- **SC-002**: 新增一个示例模块时,无需修改通用 proxy 文件即可完成注册与处理请求,验证请求往返成功且日志包含新 module_key。
- **SC-003**: 缺失 handler 或模块初始化失败时,请求返回 5xx 且日志/响应中的错误码一致,未出现 panic 或进程退出。
- **SC-004**: 改造后对现有仓库类型的端到端请求耗时及成功率与改造前相比吞吐不下降超过 5%,功能回归测试通过。

View File

@@ -0,0 +1,104 @@
# Tasks: Proxy Module Delegation
**Input**: Design documents from `/specs/005-proxy-module-delegation/`
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/, quickstart.md
**Tests**: 验收需覆盖配置校验、缓存读写、代理命中/回源、Host Header 绑定与结构化日志字段;针对各 user story 的验证可用现有 `go test` + integration stubs 完成。
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: 确认范围与基线,确保现有测试可运行
- [X] T001 复核规范/计划/研究,记录约束与目标到 specs/005-proxy-module-delegation/plan.md
- [X] T002 在仓库根目录执行基线 `go test ./...` 并记录当前失败用例(如有)
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: 梳理现有调度与接口约束,定义模块化契约
- [X] T003 分析并记录现有 hub_type 分支与 dispatch 流程internal/proxy/handler.go, internal/server/router.go明确移除点
- [X] T004 [P] 定义模块 handler 契约与注册接口internal/proxy/forwarder.go 或新建 internal/proxy/module.go供后续模块复用
**Checkpoint**: Foundational ready - user story implementation can now begin
---
## Phase 3: User Story 1 - 按模块扩展新仓类型 (Priority: P1) 🎯 MVP
**Goal**: 通用 proxy 只做分发,新增模块无需改通用分支即可处理缓存/回源
**Independent Test**: 引入一个新模块(示例 stub注册 handler 后单独请求能回源并缓存,日志含 module_key通用层无类型分支
### Implementation for User Story 1
- [X] T005 [US1] 重构 dispatch 层仅依赖 module handler map移除 hub_type 判断internal/proxy/forwarder.go, internal/server/router.go
- [X] T006 [P] [US1] 增加模块注册助手,要求元数据+handler 同时注册并校验唯一性internal/proxy/module_contract.go 等)
- [X] T007 [P] [US1] 调整主入口绑定默认/legacy handler并为新模块预留挂载点cmd/any-hub/main.go, internal/proxy/forwarder.go
- [X] T008 [US1] 更新 quickstart 说明新增模块的步骤与示例配置specs/005-proxy-module-delegation/quickstart.md
**Checkpoint**: User Story 1 independently testable
---
## Phase 4: User Story 2 - 现有仓类型平滑迁移 (Priority: P1)
**Goal**: Docker/NPM/PyPI/Composer/Go 行为与日志字段保持不变,缓存命中逻辑等价
**Independent Test**: 每个仓同一路径请求两次:首次 miss 写缓存,二次 hit日志含 hub/domain/module_key/cache_hit/upstream_status/request_id
### Implementation for User Story 2
- [X] T009 [US2] 迁移 Docker 模块到新 handler/注册模式保持路径重写与缓存策略不变internal/hubmodule/docker/, internal/proxy/* 如需)
- [X] T010 [P] [US2] 迁移 npm/pypi/go/composer/legacy 模块到新模式并保持兼容internal/hubmodule/{npm,pypi,go,composer,legacy}/
- [X] T011 [US2] 更新配置加载/校验默认值及示例,缺失 handler/重复模块时报错internal/config/loader.go, internal/config/validation.go, config.example.toml
- [X] T012 [P] [US2] 更新/新增集成场景确保日志与缓存行为等价tests/integration/*, internal/proxy/forwarder.go 观测字段)
**Checkpoint**: User Stories 1 AND 2 independently functional
---
## Phase 5: User Story 3 - 统一观测与错误处理 (Priority: P2)
**Goal**: 缺失 handler 或模块内部错误时输出一致的 5xx 与结构化日志
**Independent Test**: 触发未注册 handler、模块 panic/超时,统一返回 5xx JSON日志包含 error/module_key/hub/domain/request_id
### Implementation for User Story 3
- [X] T013 [US3] 实现缺失或重复 handler 的快速失败响应与日志internal/proxy/forwarder.go, internal/server/router.go
- [X] T014 [P] [US3] 为模块 handler 调用增加 panic/错误捕获与统一错误映射internal/proxy/forwarder.go, internal/proxy/handler.go
- [X] T015 [US3] 补充观测性字段与文档说明,确保错误/命中日志一致internal/logging/, docs/operations 或 specs/005-proxy-module-delegation/contracts/README.md
**Checkpoint**: All user stories independently functional
---
## Phase 6: Polish & Cross-Cutting Concerns
**Purpose**: 文档、格式化与回归收尾
- [ ] T016 更新 feature 文档/README说明新模块化调度与使用方式specs/005-proxy-module-delegation/contracts/README.md, README.md
- [ ] T017 [P] 运行 gofmt/go test 并记录结果(仓库根目录)
---
## Dependencies & Order
- Phase 1 → Phase 2 → Phase 3 (US1) → Phase 4 (US2) → Phase 5 (US3) → Phase 6
- User stories: US1 完成后再进行 US2US3 依赖 US1/US2 的调度能力和兼容性验证
## Parallel Execution Examples
- T004 与 T003 可并行(定义接口与调研现状分离)。
- 在 US2 中各模块迁移T009/T010可分拆并行。
- 日志/错误强化T014可与文档更新T015/T016并行。
## Implementation Strategy
- **MVP**: 完成 US1T005-T008即可验证模块化分发与新增模块示例。
- **Incremental**: 先迁移现有仓US2再补齐统一错误/观测US3最后收尾文档与回归。
- 持续运行 `go test ./...` 于每阶段完成后,确保回归可靠。