feat: 重构 pkg/ast/provider 模块,优化代码组织逻辑和功能实现
## 主要改进 ### 架构重构 - 将单体 provider.go 拆分为多个专门的模块文件 - 实现了清晰的职责分离和模块化设计 - 遵循 SOLID 原则,提高代码可维护性 ### 新增功能 - **验证规则系统**: 实现了完整的 provider 验证框架 - **报告生成器**: 支持多种格式的验证报告 (JSON/HTML/Markdown/Text) - **解析器优化**: 重新设计了解析流程,提高性能和可扩展性 - **错误处理**: 增强了错误处理和诊断能力 ### 修复关键 Bug - 修复 @provider(job) 注解缺失 __job 注入参数的问题 - 统一了 job 和 cronjob 模式的处理逻辑 - 确保了 provider 生成的正确性和一致性 ### 代码质量提升 - 添加了完整的测试套件 - 引入了 golangci-lint 代码质量检查 - 优化了代码格式和结构 - 增加了详细的文档和规范 ### 文件结构优化 ``` pkg/ast/provider/ ├── types.go # 类型定义 ├── parser.go # 解析器实现 ├── validator.go # 验证规则 ├── report_generator.go # 报告生成 ├── renderer.go # 渲染器 ├── comment_parser.go # 注解解析 ├── modes.go # 模式定义 ├── errors.go # 错误处理 └── validator_test.go # 测试文件 ``` ### 兼容性 - 保持向后兼容性 - 支持现有的所有 provider 模式 - 优化了 API 设计和用户体验 This completes the implementation of T025-T029 tasks following TDD principles, including validation rules implementation and critical bug fixes.
This commit is contained in:
394
specs/001-pkg-ast-provider/contracts/parser-api.md
Normal file
394
specs/001-pkg-ast-provider/contracts/parser-api.md
Normal file
@@ -0,0 +1,394 @@
|
||||
# Parser API Contract
|
||||
|
||||
## 概述
|
||||
|
||||
定义 pkg/ast/provider 包的解析器 API 契约,确保向后兼容性和一致的接口设计。
|
||||
|
||||
## 核心接口
|
||||
|
||||
### Parser Interface
|
||||
```go
|
||||
// Parser 定义 provider 解析器接口
|
||||
type Parser interface {
|
||||
// ParseFile 解析单个 Go 文件
|
||||
ParseFile(filename string) ([]*Provider, error)
|
||||
|
||||
// ParseDir 解析目录中的所有 Go 文件
|
||||
ParseDir(dirname string) ([]*Provider, error)
|
||||
|
||||
// ParseString 解析字符串内容
|
||||
ParseString(content string, filename string) ([]*Provider, error)
|
||||
|
||||
// SetConfig 设置解析器配置
|
||||
SetConfig(config ParserConfig) error
|
||||
|
||||
// GetConfig 获取当前配置
|
||||
GetConfig() ParserConfig
|
||||
}
|
||||
```
|
||||
|
||||
### Validator Interface
|
||||
```go
|
||||
// Validator 定义 provider 验证器接口
|
||||
type Validator interface {
|
||||
// Validate 验证 provider 配置
|
||||
Validate(p *Provider) []error
|
||||
|
||||
// ValidateComment 验证 provider 注释
|
||||
ValidateComment(comment *ProviderComment) []error
|
||||
}
|
||||
```
|
||||
|
||||
### Renderer Interface
|
||||
```go
|
||||
// Renderer 定义 provider 渲染器接口
|
||||
type Renderer interface {
|
||||
// Render 渲染 provider 代码
|
||||
Render(filename string, providers []*Provider) error
|
||||
|
||||
// RenderTemplate 使用自定义模板渲染
|
||||
RenderTemplate(filename string, providers []*Provider, template string) error
|
||||
}
|
||||
```
|
||||
|
||||
## 数据结构
|
||||
|
||||
### Provider
|
||||
```go
|
||||
// Provider 表示一个依赖注入提供者
|
||||
type Provider struct {
|
||||
StructName string `json:"struct_name"`
|
||||
ReturnType string `json:"return_type"`
|
||||
Mode ProviderMode `json:"mode"`
|
||||
ProviderGroup string `json:"provider_group"`
|
||||
GrpcRegisterFunc string `json:"grpc_register_func"`
|
||||
NeedPrepareFunc bool `json:"need_prepare_func"`
|
||||
InjectParams map[string]InjectParam `json:"inject_params"`
|
||||
Imports map[string]string `json:"imports"`
|
||||
PkgName string `json:"pkg_name"`
|
||||
ProviderFile string `json:"provider_file"`
|
||||
SourceLocation SourceLocation `json:"source_location"`
|
||||
}
|
||||
```
|
||||
|
||||
### ProviderComment
|
||||
```go
|
||||
// ProviderComment 表示解析的 provider 注释
|
||||
type ProviderComment struct {
|
||||
RawText string `json:"raw_text"`
|
||||
Mode ProviderMode `json:"mode"`
|
||||
Injection InjectionMode `json:"injection"`
|
||||
ReturnType string `json:"return_type"`
|
||||
Group string `json:"group"`
|
||||
IsValid bool `json:"is_valid"`
|
||||
Errors []string `json:"errors"`
|
||||
Location SourceLocation `json:"location"`
|
||||
}
|
||||
```
|
||||
|
||||
### InjectParam
|
||||
```go
|
||||
// InjectParam 表示注入参数
|
||||
type InjectParam struct {
|
||||
Star string `json:"star"`
|
||||
Type string `json:"type"`
|
||||
Package string `json:"package"`
|
||||
PackageAlias string `json:"package_alias"`
|
||||
FieldName string `json:"field_name"`
|
||||
InjectTag string `json:"inject_tag"`
|
||||
}
|
||||
```
|
||||
|
||||
## 枚举类型
|
||||
|
||||
### ProviderMode
|
||||
```go
|
||||
// ProviderMode 定义 provider 模式
|
||||
type ProviderMode string
|
||||
|
||||
const (
|
||||
ModeDefault ProviderMode = ""
|
||||
ModeGRPC ProviderMode = "grpc"
|
||||
ModeEvent ProviderMode = "event"
|
||||
ModeJob ProviderMode = "job"
|
||||
ModeCronJob ProviderMode = "cronjob"
|
||||
ModeModel ProviderMode = "model"
|
||||
)
|
||||
```
|
||||
|
||||
### InjectionMode
|
||||
```go
|
||||
// InjectionMode 定义注入模式
|
||||
type InjectionMode string
|
||||
|
||||
const (
|
||||
InjectionDefault InjectionMode = ""
|
||||
InjectionOnly InjectionMode = "only"
|
||||
InjectionExcept InjectionMode = "except"
|
||||
)
|
||||
```
|
||||
|
||||
## 配置结构
|
||||
|
||||
### ParserConfig
|
||||
```go
|
||||
// ParserConfig 定义解析器配置
|
||||
type ParserConfig struct {
|
||||
StrictMode bool `json:"strict_mode"` // 严格模式
|
||||
AllowTestFile bool `json:"allow_test_file"` // 是否允许解析测试文件
|
||||
IgnorePattern string `json:"ignore_pattern"` // 忽略文件模式
|
||||
MaxFileSize int64 `json:"max_file_size"` // 最大文件大小
|
||||
EnableCache bool `json:"enable_cache"` // 启用缓存
|
||||
CacheTTL int `json:"cache_ttl"` // 缓存 TTL(秒)
|
||||
}
|
||||
```
|
||||
|
||||
### DefaultConfig
|
||||
```go
|
||||
// DefaultConfig 返回默认配置
|
||||
func DefaultConfig() ParserConfig {
|
||||
return ParserConfig{
|
||||
StrictMode: false,
|
||||
AllowTestFile: false,
|
||||
IgnorePattern: "*.gen.go",
|
||||
MaxFileSize: 1024 * 1024, // 1MB
|
||||
EnableCache: false,
|
||||
CacheTTL: 300, // 5 分钟
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 工厂函数
|
||||
|
||||
### NewParser
|
||||
```go
|
||||
// NewParser 创建新的解析器实例
|
||||
func NewParser(config ParserConfig) (Parser, error)
|
||||
|
||||
// NewParserWithContext 创建带上下文的解析器
|
||||
func NewParserWithContext(ctx context.Context, config ParserConfig) (Parser, error)
|
||||
|
||||
// NewDefaultParser 创建默认配置的解析器
|
||||
func NewDefaultParser() (Parser, error)
|
||||
```
|
||||
|
||||
### NewValidator
|
||||
```go
|
||||
// NewValidator 创建新的验证器实例
|
||||
func NewValidator() (Validator, error)
|
||||
|
||||
// NewCustomValidator 创建自定义验证器
|
||||
func NewCustomValidator(rules []ValidationRule) (Validator, error)
|
||||
```
|
||||
|
||||
### NewRenderer
|
||||
```go
|
||||
// NewRenderer 创建新的渲染器实例
|
||||
func NewRenderer() (Renderer, error)
|
||||
|
||||
// NewRendererWithTemplate 创建带自定义模板的渲染器
|
||||
func NewRendererWithTemplate(template string) (Renderer, error)
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
### Error Types
|
||||
```go
|
||||
// ParseError 解析错误
|
||||
type ParseError struct {
|
||||
File string `json:"file"`
|
||||
Line int `json:"line"`
|
||||
Column int `json:"column"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ValidationError 验证错误
|
||||
type ValidationError struct {
|
||||
Field string `json:"field"`
|
||||
Value string `json:"value"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// GenerationError 生成错误
|
||||
type GenerationError struct {
|
||||
File string `json:"file"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ConfigurationError 配置错误
|
||||
type ConfigurationError struct {
|
||||
Field string `json:"field"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
```
|
||||
|
||||
### Error Interface
|
||||
```go
|
||||
// ProviderError 定义 provider 相关错误接口
|
||||
type ProviderError interface {
|
||||
error
|
||||
Code() string
|
||||
Details() map[string]interface{}
|
||||
IsRetryable() bool
|
||||
}
|
||||
```
|
||||
|
||||
## 兼容性保证
|
||||
|
||||
### 向后兼容
|
||||
- 所有公共 API 保持向后兼容
|
||||
- 结构体字段只能添加,不能删除或重命名
|
||||
- 接口方法只能添加,不能删除或修改签名
|
||||
|
||||
### 废弃策略
|
||||
- 废弃的 API 会标记为 deprecated
|
||||
- 废弃的 API 会在至少 2 个主版本后移除
|
||||
- 提供迁移指南和工具
|
||||
|
||||
## 版本控制
|
||||
|
||||
### 版本格式
|
||||
- 遵循语义化版本控制 (SemVer)
|
||||
- 主版本:不兼容的 API 变更
|
||||
- 次版本:向下兼容的功能性新增
|
||||
- 修订号:向下兼容的问题修正
|
||||
|
||||
### 版本检查
|
||||
```go
|
||||
// Version 返回当前版本
|
||||
func Version() string
|
||||
|
||||
// Compatible 检查版本兼容性
|
||||
func Compatible(version string) bool
|
||||
```
|
||||
|
||||
## 性能要求
|
||||
|
||||
### 解析性能
|
||||
- 单个文件解析时间 < 100ms
|
||||
- 目录解析时间 < 1s(100 个文件以内)
|
||||
- 内存使用 < 50MB(正常情况)
|
||||
|
||||
### 生成性能
|
||||
- 代码生成时间 < 200ms
|
||||
- 模板渲染时间 < 50ms
|
||||
- 生成的代码大小合理(< 10KB per provider)
|
||||
|
||||
## 安全考虑
|
||||
|
||||
### 输入验证
|
||||
- 所有输入参数必须验证
|
||||
- 文件路径必须安全检查
|
||||
- 防止路径遍历攻击
|
||||
|
||||
### 资源限制
|
||||
- 最大文件大小限制
|
||||
- 最大递归深度限制
|
||||
- 最大并发处理数限制
|
||||
|
||||
## 扩展点
|
||||
|
||||
### 自定义模式
|
||||
```go
|
||||
// RegisterProviderMode 注册自定义 provider 模式
|
||||
func RegisterProviderMode(mode string, handler ProviderModeHandler) error
|
||||
|
||||
// ProviderModeHandler provider 模式处理器接口
|
||||
type ProviderModeHandler interface {
|
||||
Parse(comment string) (*ProviderComment, error)
|
||||
Validate(comment *ProviderComment) error
|
||||
Generate(comment *ProviderComment) (*Provider, error)
|
||||
}
|
||||
```
|
||||
|
||||
### 自定义验证器
|
||||
```go
|
||||
// ValidationRule 验证规则接口
|
||||
type ValidationRule interface {
|
||||
Name() string
|
||||
Validate(p *Provider) error
|
||||
}
|
||||
|
||||
// RegisterValidationRule 注册验证规则
|
||||
func RegisterValidationRule(rule ValidationRule) error
|
||||
```
|
||||
|
||||
### 自定义渲染器
|
||||
```go
|
||||
// TemplateFunction 模板函数类型
|
||||
type TemplateFunction func(args ...interface{}) (interface{}, error)
|
||||
|
||||
// RegisterTemplateFunction 注册模板函数
|
||||
func RegisterTemplateFunction(name string, fn TemplateFunction) error
|
||||
```
|
||||
|
||||
## 测试契约
|
||||
|
||||
### 单元测试
|
||||
```go
|
||||
// TestParserContract 测试解析器契约
|
||||
func TestParserContract(t *testing.T) {
|
||||
parser := NewDefaultParser()
|
||||
|
||||
// 测试基本功能
|
||||
providers, err := parser.ParseFile("testdata/simple.go")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, providers)
|
||||
|
||||
// 测试错误处理
|
||||
_, err = parser.ParseFile("testdata/invalid.go")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
```
|
||||
|
||||
### 集成测试
|
||||
```go
|
||||
// TestFullWorkflow 测试完整工作流
|
||||
func TestFullWorkflow(t *testing.T) {
|
||||
// 解析 -> 验证 -> 生成 -> 验证结果
|
||||
}
|
||||
```
|
||||
|
||||
### 基准测试
|
||||
```go
|
||||
// BenchmarkParser 基准测试
|
||||
func BenchmarkParser(b *testing.B) {
|
||||
parser := NewDefaultParser()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, err := parser.ParseFile("testdata/large.go")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 监控和日志
|
||||
|
||||
### 日志接口
|
||||
```go
|
||||
// Logger 定义日志接口
|
||||
type Logger interface {
|
||||
Debug(msg string, fields ...interface{})
|
||||
Info(msg string, fields ...interface{})
|
||||
Warn(msg string, fields ...interface{})
|
||||
Error(msg string, fields ...interface{})
|
||||
}
|
||||
|
||||
// SetLogger 设置日志器
|
||||
func SetLogger(logger Logger)
|
||||
```
|
||||
|
||||
### 指标接口
|
||||
```go
|
||||
// Metrics 定义指标接口
|
||||
type Metrics interface {
|
||||
Counter(name string, value int64, tags ...string)
|
||||
Timer(name string, value time.Duration, tags ...string)
|
||||
Gauge(name string, value float64, tags ...string)
|
||||
}
|
||||
|
||||
// SetMetrics 设置指标收集器
|
||||
func SetMetrics(metrics Metrics)
|
||||
```
|
||||
657
specs/001-pkg-ast-provider/contracts/validation-rules.md
Normal file
657
specs/001-pkg-ast-provider/contracts/validation-rules.md
Normal file
@@ -0,0 +1,657 @@
|
||||
# Validation Rules Contract
|
||||
|
||||
## 概述
|
||||
|
||||
定义 pkg/ast/provider 包的验证规则契约,确保 provider 配置的正确性和一致性。
|
||||
|
||||
## 验证规则分类
|
||||
|
||||
### 1. 结构验证规则
|
||||
|
||||
#### 命名规则
|
||||
```go
|
||||
// StructNameRule 验证结构体名称
|
||||
type StructNameRule struct{}
|
||||
|
||||
func (r *StructNameRule) Name() string {
|
||||
return "struct_name"
|
||||
}
|
||||
|
||||
func (r *StructNameRule) Validate(p *Provider) error {
|
||||
if p.StructName == "" {
|
||||
return &ValidationError{
|
||||
Field: "StructName",
|
||||
Value: "",
|
||||
Message: "struct name cannot be empty",
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidGoIdentifier(p.StructName) {
|
||||
return &ValidationError{
|
||||
Field: "StructName",
|
||||
Value: p.StructName,
|
||||
Message: "struct name must be a valid Go identifier",
|
||||
}
|
||||
}
|
||||
|
||||
if !isExported(p.StructName) {
|
||||
return &ValidationError{
|
||||
Field: "StructName",
|
||||
Value: p.StructName,
|
||||
Message: "struct name must be exported (start with uppercase letter)",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### 包名规则
|
||||
```go
|
||||
// PackageNameRule 验证包名
|
||||
type PackageNameRule struct{}
|
||||
|
||||
func (r *PackageNameRule) Name() string {
|
||||
return "package_name"
|
||||
}
|
||||
|
||||
func (r *PackageNameRule) Validate(p *Provider) error {
|
||||
if p.PkgName == "" {
|
||||
return &ValidationError{
|
||||
Field: "PkgName",
|
||||
Value: "",
|
||||
Message: "package name cannot be empty",
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidGoIdentifier(p.PkgName) {
|
||||
return &ValidationError{
|
||||
Field: "PkgName",
|
||||
Value: p.PkgName,
|
||||
Message: "package name must be a valid Go identifier",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 类型验证规则
|
||||
|
||||
#### 返回类型规则
|
||||
```go
|
||||
// ReturnTypeRule 验证返回类型
|
||||
type ReturnTypeRule struct{}
|
||||
|
||||
func (r *ReturnTypeRule) Name() string {
|
||||
return "return_type"
|
||||
}
|
||||
|
||||
func (r *ReturnTypeRule) Validate(p *Provider) error {
|
||||
if p.ReturnType == "" {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: "",
|
||||
Message: "return type cannot be empty",
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidGoType(p.ReturnType) {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: p.ReturnType,
|
||||
Message: "return type must be a valid Go type",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### 模式验证规则
|
||||
```go
|
||||
// ProviderModeRule 验证 provider 模式
|
||||
type ProviderModeRule struct {
|
||||
validModes map[ProviderMode]bool
|
||||
}
|
||||
|
||||
func NewProviderModeRule() *ProviderModeRule {
|
||||
return &ProviderModeRule{
|
||||
validModes: map[ProviderMode]bool{
|
||||
ModeDefault: true,
|
||||
ModeGRPC: true,
|
||||
ModeEvent: true,
|
||||
ModeJob: true,
|
||||
ModeCronJob: true,
|
||||
ModeModel: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProviderModeRule) Name() string {
|
||||
return "provider_mode"
|
||||
}
|
||||
|
||||
func (r *ProviderModeRule) Validate(p *Provider) error {
|
||||
if !r.validModes[p.Mode] {
|
||||
return &ValidationError{
|
||||
Field: "Mode",
|
||||
Value: string(p.Mode),
|
||||
Message: fmt.Sprintf("invalid provider mode: %s", p.Mode),
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 依赖注入验证规则
|
||||
|
||||
#### 注入参数规则
|
||||
```go
|
||||
// InjectParamsRule 验证注入参数
|
||||
type InjectParamsRule struct{}
|
||||
|
||||
func (r *InjectParamsRule) Name() string {
|
||||
return "inject_params"
|
||||
}
|
||||
|
||||
func (r *InjectParamsRule) Validate(p *Provider) error {
|
||||
// 验证注入参数不为标量类型
|
||||
for name, param := range p.InjectParams {
|
||||
if isScalarType(param.Type) {
|
||||
return &ValidationError{
|
||||
Field: fmt.Sprintf("InjectParams.%s", name),
|
||||
Value: param.Type,
|
||||
Message: fmt.Sprintf("scalar type '%s' cannot be injected", param.Type),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 only 模式下的 inject:true 标签
|
||||
if p.InjectionMode == InjectionOnly {
|
||||
for name, param := range p.InjectParams {
|
||||
if param.InjectTag != "true" {
|
||||
return &ValidationError{
|
||||
Field: fmt.Sprintf("InjectParams.%s", name),
|
||||
Value: param.InjectTag,
|
||||
Message: "all fields must have inject:\"true\" tag in 'only' mode",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 except 模式下的 inject:false 标签
|
||||
if p.InjectionMode == InjectionExcept {
|
||||
for name, param := range p.InjectParams {
|
||||
if param.InjectTag == "false" {
|
||||
return &ValidationError{
|
||||
Field: fmt.Sprintf("InjectParams.%s", name),
|
||||
Value: param.InjectTag,
|
||||
Message: "fields with inject:\"false\" tag should not be included in 'except' mode",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### 包别名规则
|
||||
```go
|
||||
// PackageAliasRule 验证包别名
|
||||
type PackageAliasRule struct{}
|
||||
|
||||
func (r *PackageAliasRule) Name() string {
|
||||
return "package_alias"
|
||||
}
|
||||
|
||||
func (r *PackageAliasRule) Validate(p *Provider) error {
|
||||
// 收集所有包别名
|
||||
aliases := make(map[string]string)
|
||||
for alias, pkg := range p.Imports {
|
||||
if existing, exists := aliases[alias]; exists && existing != pkg {
|
||||
return &ValidationError{
|
||||
Field: "Imports",
|
||||
Value: alias,
|
||||
Message: fmt.Sprintf("duplicate package alias '%s' for different packages", alias),
|
||||
}
|
||||
}
|
||||
aliases[alias] = pkg
|
||||
}
|
||||
|
||||
// 验证注入参数的包别名
|
||||
for name, param := range p.InjectParams {
|
||||
if param.PackageAlias != "" {
|
||||
if _, exists := aliases[param.PackageAlias]; !exists {
|
||||
return &ValidationError{
|
||||
Field: fmt.Sprintf("InjectParams.%s", name),
|
||||
Value: param.PackageAlias,
|
||||
Message: fmt.Sprintf("undefined package alias '%s'", param.PackageAlias),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 模式特定验证规则
|
||||
|
||||
#### gRPC 模式规则
|
||||
```go
|
||||
// GRPCModeRule 验证 gRPC 模式特定规则
|
||||
type GRPCModeRule struct{}
|
||||
|
||||
func (r *GRPCModeRule) Name() string {
|
||||
return "grpc_mode"
|
||||
}
|
||||
|
||||
func (r *GRPCModeRule) Validate(p *Provider) error {
|
||||
if p.Mode != ModeGRPC {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 验证 gRPC 注册函数
|
||||
if p.GrpcRegisterFunc == "" {
|
||||
return &ValidationError{
|
||||
Field: "GrpcRegisterFunc",
|
||||
Value: "",
|
||||
Message: "gRPC register function cannot be empty in gRPC mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证返回类型
|
||||
if p.ReturnType != "contracts.Initial" {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: p.ReturnType,
|
||||
Message: "return type must be 'contracts.Initial' in gRPC mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 provider 组
|
||||
if p.ProviderGroup != "atom.GroupInitial" {
|
||||
return &ValidationError{
|
||||
Field: "ProviderGroup",
|
||||
Value: p.ProviderGroup,
|
||||
Message: "provider group must be 'atom.GroupInitial' in gRPC mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证必须包含 __grpc 注入参数
|
||||
if _, exists := p.InjectParams["__grpc"]; !exists {
|
||||
return &ValidationError{
|
||||
Field: "InjectParams",
|
||||
Value: "",
|
||||
Message: "gRPC provider must include '__grpc' injection parameter",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### Event 模式规则
|
||||
```go
|
||||
// EventModeRule 验证 Event 模式特定规则
|
||||
type EventModeRule struct{}
|
||||
|
||||
func (r *EventModeRule) Name() string {
|
||||
return "event_mode"
|
||||
}
|
||||
|
||||
func (r *EventModeRule) Validate(p *Provider) error {
|
||||
if p.Mode != ModeEvent {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 验证返回类型
|
||||
if p.ReturnType != "contracts.Initial" {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: p.ReturnType,
|
||||
Message: "return type must be 'contracts.Initial' in event mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 provider 组
|
||||
if p.ProviderGroup != "atom.GroupInitial" {
|
||||
return &ValidationError{
|
||||
Field: "ProviderGroup",
|
||||
Value: p.ProviderGroup,
|
||||
Message: "provider group must be 'atom.GroupInitial' in event mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证必须包含 __event 注入参数
|
||||
if _, exists := p.InjectParams["__event"]; !exists {
|
||||
return &ValidationError{
|
||||
Field: "InjectParams",
|
||||
Value: "",
|
||||
Message: "event provider must include '__event' injection parameter",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### Job 模式规则
|
||||
```go
|
||||
// JobModeRule 验证 Job 模式特定规则
|
||||
type JobModeRule struct{}
|
||||
|
||||
func (r *JobModeRule) Name() string {
|
||||
return "job_mode"
|
||||
}
|
||||
|
||||
func (r *JobModeRule) Validate(p *Provider) error {
|
||||
if p.Mode != ModeJob && p.Mode != ModeCronJob {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 验证返回类型
|
||||
if p.ReturnType != "contracts.Initial" {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: p.ReturnType,
|
||||
Message: "return type must be 'contracts.Initial' in job mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 provider 组
|
||||
if p.ProviderGroup != "atom.GroupInitial" {
|
||||
return &ValidationError{
|
||||
Field: "ProviderGroup",
|
||||
Value: p.ProviderGroup,
|
||||
Message: "provider group must be 'atom.GroupInitial' in job mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证必须包含 __job 注入参数
|
||||
if _, exists := p.InjectParams["__job"]; !exists {
|
||||
return &ValidationError{
|
||||
Field: "InjectParams",
|
||||
Value: "",
|
||||
Message: "job provider must include '__job' injection parameter",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
#### Model 模式规则
|
||||
```go
|
||||
// ModelModeRule 验证 Model 模式特定规则
|
||||
type ModelModeRule struct{}
|
||||
|
||||
func (r *ModelModeRule) Name() string {
|
||||
return "model_mode"
|
||||
}
|
||||
|
||||
func (r *ModelModeRule) Validate(p *Provider) error {
|
||||
if p.Mode != ModeModel {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 验证返回类型
|
||||
if p.ReturnType != "contracts.Initial" {
|
||||
return &ValidationError{
|
||||
Field: "ReturnType",
|
||||
Value: p.ReturnType,
|
||||
Message: "return type must be 'contracts.Initial' in model mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 provider 组
|
||||
if p.ProviderGroup != "atom.GroupInitial" {
|
||||
return &ValidationError{
|
||||
Field: "ProviderGroup",
|
||||
Value: p.ProviderGroup,
|
||||
Message: "provider group must be 'atom.GroupInitial' in model mode",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证必须设置 NeedPrepareFunc
|
||||
if !p.NeedPrepareFunc {
|
||||
return &ValidationError{
|
||||
Field: "NeedPrepareFunc",
|
||||
Value: "false",
|
||||
Message: "model provider must set NeedPrepareFunc to true",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 注释验证规则
|
||||
|
||||
#### 注释格式规则
|
||||
```go
|
||||
// CommentFormatRule 验证注释格式
|
||||
type CommentFormatRule struct{}
|
||||
|
||||
func (r *CommentFormatRule) Name() string {
|
||||
return "comment_format"
|
||||
}
|
||||
|
||||
func (r *CommentFormatRule) Validate(p *Provider) error {
|
||||
if p.Comment == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
comment := p.Comment
|
||||
|
||||
// 验证注释必须以 @provider 开头
|
||||
if !strings.HasPrefix(comment.RawText, "@provider") {
|
||||
return &ValidationError{
|
||||
Field: "Comment.RawText",
|
||||
Value: comment.RawText,
|
||||
Message: "provider comment must start with '@provider'",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证模式格式
|
||||
if comment.Mode != "" && !isValidProviderMode(comment.Mode) {
|
||||
return &ValidationError{
|
||||
Field: "Comment.Mode",
|
||||
Value: string(comment.Mode),
|
||||
Message: fmt.Sprintf("invalid provider mode: %s", comment.Mode),
|
||||
}
|
||||
}
|
||||
|
||||
// 验证注入模式
|
||||
if comment.Injection != "" && !isValidInjectionMode(comment.Injection) {
|
||||
return &ValidationError{
|
||||
Field: "Comment.Injection",
|
||||
Value: string(comment.Injection),
|
||||
Message: fmt.Sprintf("invalid injection mode: %s", comment.Injection),
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### 6. 文件路径验证规则
|
||||
|
||||
#### 文件路径规则
|
||||
```go
|
||||
// FilePathRule 验证文件路径
|
||||
type FilePathRule struct{}
|
||||
|
||||
func (r *FilePathRule) Name() string {
|
||||
return "file_path"
|
||||
}
|
||||
|
||||
func (r *FilePathRule) Validate(p *Provider) error {
|
||||
if p.ProviderFile == "" {
|
||||
return &ValidationError{
|
||||
Field: "ProviderFile",
|
||||
Value: "",
|
||||
Message: "provider file path cannot be empty",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证文件扩展名
|
||||
if !strings.HasSuffix(p.ProviderFile, ".go") {
|
||||
return &ValidationError{
|
||||
Field: "ProviderFile",
|
||||
Value: p.ProviderFile,
|
||||
Message: "provider file must have .go extension",
|
||||
}
|
||||
}
|
||||
|
||||
// 验证文件路径安全性
|
||||
if !isSafeFilePath(p.ProviderFile) {
|
||||
return &ValidationError{
|
||||
Field: "ProviderFile",
|
||||
Value: p.ProviderFile,
|
||||
Message: "provider file path is not safe",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
## 验证器注册
|
||||
|
||||
### 默认验证器
|
||||
```go
|
||||
// DefaultValidator 返回默认验证器
|
||||
func DefaultValidator() Validator {
|
||||
validator := NewCompositeValidator()
|
||||
|
||||
// 注册所有验证规则
|
||||
validator.AddRule(&StructNameRule{})
|
||||
validator.AddRule(&PackageNameRule{})
|
||||
validator.AddRule(&ReturnTypeRule{})
|
||||
validator.AddRule(NewProviderModeRule())
|
||||
validator.AddRule(&InjectParamsRule{})
|
||||
validator.AddRule(&PackageAliasRule{})
|
||||
validator.AddRule(&GRPCModeRule{})
|
||||
validator.AddRule(&EventModeRule{})
|
||||
validator.AddRule(&JobModeRule{})
|
||||
validator.AddRule(&ModelModeRule{})
|
||||
validator.AddRule(&CommentFormatRule{})
|
||||
validator.AddRule(&FilePathRule{})
|
||||
|
||||
return validator
|
||||
}
|
||||
```
|
||||
|
||||
### 自定义验证器
|
||||
```go
|
||||
// CompositeValidator 组合验证器
|
||||
type CompositeValidator struct {
|
||||
rules []ValidationRule
|
||||
}
|
||||
|
||||
func NewCompositeValidator() *CompositeValidator {
|
||||
return &CompositeValidator{
|
||||
rules: make([]ValidationRule, 0),
|
||||
}
|
||||
}
|
||||
|
||||
func (v *CompositeValidator) AddRule(rule ValidationRule) {
|
||||
v.rules = append(v.rules, rule)
|
||||
}
|
||||
|
||||
func (v *CompositeValidator) Validate(p *Provider) []error {
|
||||
var errors []error
|
||||
|
||||
for _, rule := range v.rules {
|
||||
if err := rule.Validate(p); err != nil {
|
||||
errors = append(errors, err)
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
```
|
||||
|
||||
## 验证结果
|
||||
|
||||
### 验证报告
|
||||
```go
|
||||
// ValidationReport 验证报告
|
||||
type ValidationReport struct {
|
||||
Provider *Provider `json:"provider"`
|
||||
Errors []error `json:"errors"`
|
||||
Warnings []error `json:"warnings"`
|
||||
IsValid bool `json:"is_valid"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// ValidateProvider 验证 provider 并生成报告
|
||||
func ValidateProvider(p *Provider) *ValidationReport {
|
||||
report := &ValidationReport{
|
||||
Provider: p,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
validator := DefaultValidator()
|
||||
errors := validator.Validate(p)
|
||||
|
||||
if len(errors) == 0 {
|
||||
report.IsValid = true
|
||||
} else {
|
||||
report.Errors = errors
|
||||
report.IsValid = false
|
||||
}
|
||||
|
||||
return report
|
||||
}
|
||||
```
|
||||
|
||||
## 性能考虑
|
||||
|
||||
### 验证性能优化
|
||||
- 快速失败:遇到第一个错误立即返回
|
||||
- 缓存验证结果
|
||||
- 并行验证独立规则
|
||||
- 懒加载验证器
|
||||
|
||||
### 内存优化
|
||||
- 重用验证器实例
|
||||
- 避免重复分配错误对象
|
||||
- 使用对象池管理验证器
|
||||
|
||||
## 扩展性
|
||||
|
||||
### 自定义规则注册
|
||||
```go
|
||||
// RegisterValidationRule 注册全局验证规则
|
||||
func RegisterValidationRule(name string, rule ValidationRule) error {
|
||||
// 实现规则注册逻辑
|
||||
}
|
||||
|
||||
// GetValidationRule 获取验证规则
|
||||
func GetValidationRule(name string) (ValidationRule, bool) {
|
||||
// 实现规则获取逻辑
|
||||
}
|
||||
```
|
||||
|
||||
### 规则优先级
|
||||
```go
|
||||
// PrioritizedRule 优先级规则
|
||||
type PrioritizedRule struct {
|
||||
Rule ValidationRule
|
||||
Priority int
|
||||
}
|
||||
|
||||
// PriorityValidator 优先级验证器
|
||||
type PriorityValidator struct {
|
||||
rules []PrioritizedRule
|
||||
}
|
||||
|
||||
func (v *PriorityValidator) Validate(p *Provider) []error {
|
||||
// 按优先级执行验证
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user