Coze源码分析-资源库-删除插件-后端源码-数据访问和基础设施层
5. 数据访问层
5.1 仓储接口定义
插件仓储接口
文件位置:backend/domain/plugin/repository/plugin.go
type PluginRepository interface {// DeleteDraftPlugin 删除插件草稿DeleteDraftPlugin(ctx context.Context, pluginID int64) error// DeleteAPPAllPlugins 删除应用下所有插件DeleteAPPAllPlugins(ctx context.Context, appID int64) (pluginIDs []int64, err error)// GetDraftPlugin 获取插件草稿GetDraftPlugin(ctx context.Context, pluginID int64, opt *dal.PluginSelectedOption) (*entity.PluginInfo, error)// 其他CRUD方法...
}
删除方法特点:
- 事务删除:DeleteDraftPlugin方法支持事务操作,确保数据一致性
- 批量删除:DeleteAPPAllPlugins支持批量删除应用下的所有插件
- 上下文支持:支持context.Context进行请求链路追踪
- 错误处理:返回error类型,便于上层进行错误处理
- ID定位:通过唯一pluginID精确定位要删除的插件资源
5.2 数据访问对象(DAO)
插件删除的具体实现
文件位置:backend/domain/plugin/repository/plugin_impl.go
插件删除操作涉及多个数据表的级联删除,需要通过事务确保数据一致性:
func (p *pluginRepoImpl) DeleteDraftPlugin(ctx context.Context, pluginID int64) (err error) {tx := p.query.Begin()if tx.Error != nil {return tx.Error}defer func() {if r := recover(); r != nil {if e := tx.Rollback(); e != nil {logs.CtxErrorf(ctx, "rollback failed, err=%v", e)}err = fmt.Errorf("catch panic: %v\nstack=%s", r, string(debug.Stack()))return}if err != nil {if e := tx.Rollback(); e != nil {logs.CtxErrorf(ctx, "rollback failed, err=%v", e)}}}()// 删除插件草稿数据err = p.pluginDraftDAO.DeleteWithTX(ctx, tx, pluginID)if err != nil {return err}// 删除插件基础数据err = p.pluginDAO.DeleteWithTX(ctx, tx, pluginID)if err != nil {return err}// 删除插件版本数据err = p.pluginVersionDAO.DeleteWithTX(ctx, tx, pluginID)if err != nil {return err}// 删除插件下的所有工具草稿err = p.toolDraftDAO.DeleteAllWithTX(ctx, tx, pluginID)if err != nil {return err}// 删除插件下的所有工具数据err = p.toolDAO.DeleteAllWithTX(ctx, tx, pluginID)if err != nil {return err}// 删除工具版本数据err = p.toolVersionDAO.DeleteWithTX(ctx, tx, pluginID)if err != nil {return err}return tx.Commit()
}
删除操作的关键特点:
- 事务保证:使用数据库事务确保所有删除操作的原子性
- 级联删除:删除插件时同时删除相关的工具、版本等数据
- 异常处理:完善的panic恢复和事务回滚机制
- 数据完整性:确保删除操作不会留下孤立的数据记录
- 多表协调:协调删除插件相关的多个数据表
删除涉及的数据表:
- plugin_draft:插件草稿表
- plugin:插件基础信息表
- plugin_version:插件版本表
- tool_draft:工具草稿表
- tool:工具信息表
- tool_version:工具版本表
PluginDraftDAO结构体
文件位置:backend/domain/plugin/internal/dal/plugin_draft.go
PluginDraftDAO是插件草稿数据访问的具体实现,负责与数据库进行交互,处理插件草稿资源的持久化操作。
package dalimport ("context""encoding/json""fmt""gorm.io/gen""gorm.io/gorm""github.com/coze-dev/coze-studio/backend/domain/plugin/entity""github.com/coze-dev/coze-studio/backend/domain/plugin/internal/dal/model""github.com/coze-dev/coze-studio/backend/domain/plugin/internal/dal/query""github.com/coze-dev/coze-studio/backend/infra/contract/idgen""github.com/coze-dev/coze-studio/backend/pkg/slices"
)type PluginDraftDAO struct {query *query.QueryidGen idgen.IDGenerator
}func NewPluginDraftDAO(db *gorm.DB, generator idgen.IDGenerator) *PluginDraftDAO {return &PluginDraftDAO{query: query.Use(db),idGen: generator,}
}
插件删除操作实现
删除插件草稿:
func (p *PluginDraftDAO) DeleteWithTX(ctx context.Context, tx *query.QueryTx, pluginID int64) (err error) {table := tx.PluginDraft_, err = table.WithContext(ctx).Where(table.ID.Eq(pluginID)).Delete()if err != nil {return err}return nil
}
ToolDraftDAO删除操作
文件位置:backend/domain/plugin/internal/dal/tool_draft.go
批量删除工具草稿:
func (t *ToolDraftDAO) DeleteAllWithTX(ctx context.Context, tx *query.QueryTx, pluginID int64) (err error) {const limit = 20table := tx.ToolDraftfor {info, err := table.WithContext(ctx).Where(table.PluginID.Eq(pluginID)).Limit(limit).Delete()if err != nil {return err}if info.RowsAffected < limit {break}}return nil
}
数据转换方法
DO到PO转换(Domain Object to Persistent Object):
func (p *PluginDraftDAO) pluginInfoDO2PO(plugin *entity.PluginInfo) *model.PluginDraft {mf, _ := plugin.Manifest.EncryptAuthPayload()return &model.PluginDraft{ID: plugin.ID,SpaceID: plugin.SpaceID,DeveloperID: plugin.DeveloperID,PluginType: int32(plugin.PluginType),IconURI: plugin.GetIconURI(),ServerURL: plugin.GetServerURL(),AppID: plugin.GetAPPID(),Manifest: mf,OpenapiDoc: plugin.OpenapiDoc,}
}
PO到DO转换(Persistent Object to Domain Object):
type pluginDraftPO model.PluginDraftfunc (p pluginDraftPO) ToDO() *entity.PluginInfo {plugin := &entity.PluginInfo{ID: p.ID,SpaceID: p.SpaceID,DeveloperID: p.DeveloperID,PluginType: common.PluginType(p.PluginType),IconURI: &p.IconURI,ServerURL: &p.ServerURL,APPID: &p.AppID,Manifest: p.Manifest,OpenapiDoc: p.OpenapiDoc,CreatedAt: p.CreatedAt,UpdatedAt: p.UpdatedAt,}return plugin
}
删除操作特点:
- 事务删除:DeleteWithTX方法支持事务操作,确保数据一致性
- 精确定位:通过pluginID精确定位要删除的插件资源
- 条件构建:使用GORM Gen生成的类型安全查询条件
- 物理删除:执行物理删除操作,从数据库中彻底移除记录
- 批量删除:ToolDraftDAO支持批量删除插件下的所有工具
- 分页删除:使用limit分页删除,避免大量数据删除时的性能问题
删除插件的完整数据访问流程:
在删除插件的场景中,数据访问层的操作流程如下:
- 删除前验证:调用GetDraftPlugin方法获取插件信息,验证资源存在性
- 权限检查:在应用层验证当前用户是否为插件开发者
- 事务开始:开启数据库事务,确保删除操作的原子性
- 级联删除:依次删除插件草稿、插件基础数据、版本数据、工具数据等
- 事务提交:所有删除操作成功后提交事务
- 错误回滚:任何删除操作失败时回滚事务,保证数据一致性
这种设计确保了删除操作的安全性、可靠性和数据完整性。
数据访问层删除操作总结:
删除插件在数据访问层的实现具有以下特点:
- 事务保证:所有删除操作在事务中执行,确保数据一致性
- 级联删除:自动删除插件相关的所有数据,包括工具、版本等
- 类型安全:使用GORM Gen生成的类型安全查询条件,避免SQL注入风险
- 错误处理:完善的错误处理和事务回滚机制
- 物理删除:执行真正的物理删除操作,彻底从数据库中移除记录
- 性能优化:通过分页删除和精确的WHERE条件,确保删除操作的高效执行
5.3 插件数据模型
PluginDraft数据模型
文件位置:backend/domain/plugin/internal/dal/model/plugin_draft.gen.go
该文件由GORM代码生成工具自动生成,定义了与数据库表对应的Go结构体。在删除插件操作中,该模型定义了数据库记录的结构,为删除操作提供了数据映射基础。
// Code generated by gorm.io/gen. DO NOT EDIT.
package modelconst TableNamePluginDraft = "plugin_draft"// PluginDraft plugin_draft
type PluginDraft struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement:true;comment:id" json:"id"` // idSpaceID int64 `gorm:"column:space_id;not null;comment:space id" json:"space_id"` // space idDeveloperID int64 `gorm:"column:developer_id;not null;comment:developer id" json:"developer_id"` // developer idPluginType int32 `gorm:"column:plugin_type;not null;comment:plugin type" json:"plugin_type"` // plugin typeIconURI string `gorm:"column:icon_uri;comment:icon uri" json:"icon_uri"` // icon uriServerURL string `gorm:"column:server_url;comment:server url" json:"server_url"` // server urlAppID int64 `gorm:"column:app_id;comment:app id" json:"app_id"` // app idManifest *PluginManifest `gorm:"column:manifest;comment:plugin manifest" json:"manifest"` // plugin manifestOpenapiDoc *Openapi3T `gorm:"column:openapi_doc;comment:openapi document" json:"openapi_doc"` // openapi documentCreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime:milli;comment:Create Time in Milliseconds" json:"created_at"` // Create Time in MillisecondsUpdatedAt int64 `gorm:"column:updated_at;not null;autoUpdateTime:milli;comment:Update Time in Milliseconds" json:"updated_at"` // Update Time in Milliseconds
}// TableName PluginDraft's table name
func (*PluginDraft) TableName() string {return TableNamePluginDraft
}
ToolDraft数据模型
文件位置:backend/domain/plugin/internal/dal/model/tool_draft.gen.go
// ToolDraft tool_draft
type ToolDraft struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement:true;comment:id" json:"id"` // idPluginID int64 `gorm:"column:plugin_id;not null;comment:plugin id" json:"plugin_id"` // plugin idSubURL string `gorm:"column:sub_url;comment:sub url" json:"sub_url"` // sub urlMethod string `gorm:"column:method;comment:http method" json:"method"` // http methodActivatedStatus int32 `gorm:"column:activated_status;comment:activated status" json:"activated_status"` // activated statusDebugStatus int32 `gorm:"column:debug_status;comment:debug status" json:"debug_status"` // debug statusOperation *Operation `gorm:"column:operation;comment:operation info" json:"operation"` // operation infoCreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime:milli;comment:Create Time in Milliseconds" json:"created_at"` // Create Time in MillisecondsUpdatedAt int64 `gorm:"column:updated_at;not null;autoUpdateTime:milli;comment:Update Time in Milliseconds" json:"updated_at"` // Update Time in Milliseconds
}
删除操作中的模型特点:
- 主键定位:ID字段作为主键,是删除操作的核心定位字段,确保精确删除
- 权限验证字段:DeveloperID字段用于删除前的权限验证,确保只有开发者可以删除
- 关联关系:PluginID字段建立插件与工具的关联关系,支持级联删除
- 字段映射:通过gorm标签定义字段与数据库列的映射关系,为删除操作提供准确的数据定位
- 约束定义:包含主键、非空、注释等数据库约束,确保删除操作的数据完整性
- 复杂类型:Manifest和OpenapiDoc字段存储JSON格式的复杂数据结构
- 审计追踪:CreatedAt和UpdatedAt字段支持删除操作的审计追踪和时间记录
- JSON序列化:通过json标签支持JSON序列化,便于删除操作的API响应和日志记录
5.4 GORM生成的查询接口
插件查询接口
文件位置:backend/domain/plugin/internal/dal/query/plugin_draft.gen.go
GORM Gen工具生成的类型安全查询接口,为删除插件操作提供了强大的数据访问能力。这些接口确保了删除操作的类型安全性和执行效率。
// pluginDraft plugin_draft
type pluginDraft struct {pluginDraftDoALL field.AsteriskID field.Int64 // idSpaceID field.Int64 // space idDeveloperID field.Int64 // developer idPluginType field.Int32 // plugin typeIconURI field.String // icon uriServerURL field.String // server urlAppID field.Int64 // app idManifest field.Field // plugin manifestOpenapiDoc field.Field // openapi documentCreatedAt field.Int64 // Create Time in MillisecondsUpdatedAt field.Int64 // Update Time in MillisecondsfieldMap map[string]field.Expr
}
工具查询接口
文件位置:backend/domain/plugin/internal/dal/query/tool_draft.gen.go
// toolDraft tool_draft
type toolDraft struct {toolDraftDoALL field.AsteriskID field.Int64 // idPluginID field.Int64 // plugin idSubURL field.String // sub urlMethod field.String // http methodActivatedStatus field.Int32 // activated statusDebugStatus field.Int32 // debug statusOperation field.Field // operation infoCreatedAt field.Int64 // Create Time in MillisecondsUpdatedAt field.Int64 // Update Time in MillisecondsfieldMap map[string]field.Expr
}
查询接口定义
type IPluginDraftDo interface {gen.SubQueryDebug() IPluginDraftDoWithContext(ctx context.Context) IPluginDraftDoWithResult(fc func(tx gen.Dao)) gen.ResultInfoReplaceDB(db *gorm.DB)ReadDB() IPluginDraftDoWriteDB() IPluginDraftDo// 删除操作相关方法Delete(conds ...gen.Condition) (gen.ResultInfo, error)Where(conds ...gen.Condition) IPluginDraftDo......
}type IToolDraftDo interface {gen.SubQueryDebug() IToolDraftDoWithContext(ctx context.Context) IToolDraftDo// 删除操作相关方法Delete(conds ...gen.Condition) (gen.ResultInfo, error)Where(conds ...gen.Condition) IToolDraftDo......
}
删除操作相关接口特点:
- Delete方法:提供类型安全的删除操作,支持条件删除
- Where条件:支持复杂的删除条件构建,确保精确删除
- 上下文支持:WithContext方法支持请求上下文传递
- 事务支持:支持在事务中执行删除操作,确保数据一致性
- 调试支持:Debug方法便于删除操作的SQL调试和优化
- 关联删除:ToolDraft通过PluginID字段支持级联删除操作
5.5 统一查询入口
文件位置:backend\domain\plugin\internal\dal\query\gen.go
该文件为删除插件操作提供了统一的查询入口和事务支持,确保删除操作的一致性和可靠性。
核心代码:
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.package queryimport ("context""database/sql""gorm.io/gorm""gorm.io/gen""gorm.io/plugin/dbresolver"
)var (Q = new(Query)PluginDraft *pluginDraftToolDraft *toolDraft
)func SetDefault(db *gorm.DB, opts ...gen.DOOption) {*Q = *Use(db, opts...)PluginDraft = &Q.PluginDraftToolDraft = &Q.ToolDraft
}func Use(db *gorm.DB, opts ...gen.DOOption) *Query {return &Query{db: db,PluginDraft: newPluginDraft(db, opts...),ToolDraft: newToolDraft(db, opts...),}
}type Query struct {db *gorm.DBPluginDraft pluginDraftToolDraft toolDraft
}func (q *Query) Available() bool { return q.db != nil }func (q *Query) clone(db *gorm.DB) *Query {return &Query{db: db,PluginDraft: q.PluginDraft.clone(db),ToolDraft: q.ToolDraft.clone(db),}
}func (q *Query) ReadDB() *Query {return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
}func (q *Query) WriteDB() *Query {return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
}func (q *Query) ReplaceDB(db *gorm.DB) *Query {return &Query{db: db,PluginDraft: q.PluginDraft.replaceDB(db),ToolDraft: q.ToolDraft.replaceDB(db),}
}type queryCtx struct {PluginDraft IPluginDraftDoToolDraft IToolDraftDo
}func (q *Query) WithContext(ctx context.Context) *queryCtx {return &queryCtx{PluginDraft: q.PluginDraft.WithContext(ctx),ToolDraft: q.ToolDraft.WithContext(ctx),}
}func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
}func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {tx := q.db.Begin(opts...)return &QueryTx{Query: q.clone(tx), Error: tx.Error}
}type QueryTx struct {*QueryError error
}func (q *QueryTx) Commit() error {return q.db.Commit().Error
}func (q *QueryTx) Rollback() error {return q.db.Rollback().Error
}func (q *QueryTx) SavePoint(name string) error {return q.db.SavePoint(name).Error
}func (q *QueryTx) RollbackTo(name string) error {return q.db.RollbackTo(name).Error
}
删除操作查询入口特点:
- 全局查询对象:提供全局的PluginDraft和ToolDraft查询对象,便于删除操作的统一管理
- 事务支持:Transaction方法支持在事务中执行删除操作,确保数据一致性
- 读写分离:ReadDB和WriteDB方法支持数据库读写分离,删除操作使用WriteDB
- 上下文传递:WithContext方法支持请求上下文在删除操作中的传递
- 数据库切换:ReplaceDB方法支持动态切换数据库连接,便于多环境部署
- 事务管理:Begin、Commit、Rollback等方法提供完整的事务管理能力
- 多表支持:同时支持PluginDraft和ToolDraft两个表的查询操作
5.6 数据访问层删除操作架构总结
删除插件在数据访问层的实现体现了现代Go应用的最佳实践:
技术特点:
- 类型安全:使用GORM Gen生成类型安全的查询接口,避免SQL注入和类型错误
- 分层设计:Repository接口抽象数据访问,DAO实现具体的数据库操作
- 错误处理:统一的错误码包装机制,便于上层进行错误分类和处理
- 事务支持:完整的事务支持,确保删除操作的原子性
- 性能优化:精确的WHERE条件和索引利用,确保删除操作的高效执行
- 级联删除:支持插件及其关联工具的级联删除操作
安全保障:
- 权限验证:通过DeveloperID字段确保只有开发者可以删除自己的插件
- 存在性检查:删除前验证插件是否存在,避免无效删除
- 物理删除:彻底从数据库中移除记录,确保数据清理的完整性
- 审计追踪:完整的时间戳记录,支持删除操作的审计和追踪
- 关联清理:确保删除插件时同时清理相关的工具数据
删除操作流程:
- 接口调用:上层通过Repository接口调用DeleteDraftPlugin方法
- 事务开启:开启数据库事务确保操作的原子性
- 级联删除:先删除关联的工具数据,再删除插件数据
- 事务提交:所有删除操作成功后提交事务
- 错误处理:任何步骤失败都会回滚事务并返回错误
这种设计确保了删除插件操作的安全性、可靠性和高性能,为上层业务逻辑提供了坚实的数据访问基础。
数据模型与查询文件依赖关系
数据库表结构 (schema.sql)(plugin_draft、tool_draft表)↓ gen_orm_query.go
模型文件 (model/plugin_draft.gen.go, model/tool_draft.gen.go) - 生成模型↓
查询文件 (query/plugin_draft.gen.go, query/tool_draft.gen.go) - 依赖对应模型↓
统一入口 (query/gen.go) - 依赖所有查询文件
数据访问层架构总结
分层架构:
业务服务层 (Service)↓
仓储接口层 (Repository Interface)↓
数据访问层 (DAO Implementation)↓
GORM查询层 (Generated Query)↓
数据模型层 (Generated Model)↓
数据库层 (MySQL)
删除插件在数据访问层的完整流程:
- 接口定义:
PluginRepository.DeleteDraftPlugin(ctx, ID)
定义删除操作契约 - DAO实现:
PluginDraftDAO.DeleteWithTX(tx, ID)
和ToolDraftDAO.DeleteAllWithTX(tx, pluginID)
实现具体删除逻辑 - 事务管理:使用事务确保插件和工具数据的一致性删除
- 级联删除:先删除工具数据,再删除插件数据
- 错误处理:包装删除异常为统一错误码
- 结果返回:删除成功返回nil,失败返回包装后的错误
设计优势:
- 接口抽象:通过Repository接口实现数据访问的抽象化
- 代码生成:使用GORM Gen自动生成类型安全的查询代码
- 错误处理:统一的错误包装和处理机制
- 事务支持:通过context传递支持数据库事务
- 删除安全:通过ID精确定位,避免误删除操作
- 性能优化:合理的索引设计和查询优化
- 可测试性:清晰的分层结构便于单元测试
- 可维护性:代码生成减少手工编写,降低维护成本
- 级联删除:支持插件及其关联数据的级联删除
删除操作的技术特点:
- 物理删除:当前实现为物理删除,直接从数据库中移除记录
- 事务操作:使用数据库事务确保插件和工具数据的一致性删除
- 索引优化:基于主键ID的删除操作,具有最佳的查询性能
- 错误分类:通过错误码区分不同类型的删除异常
- 审计支持:可通过数据库日志追踪删除操作的执行情况
- 关联清理:确保删除插件时同时清理相关的工具数据
6. 基础设施层
基础设施层为插件删除功能提供了核心的技术支撑,包括数据库连接、缓存管理、搜索引擎和事件处理等关键组件。这些组件通过契约层(Contract)和实现层(Implementation)的分离设计,确保了删除操作的可靠性、一致性和高性能。
6.1 数据库基础设施
数据库契约层
文件位置:backend/infra/contract/orm/database.go
package ormimport ("gorm.io/gorm"
)type DB = gorm.DB
设计作用:
- 为GORM数据库对象提供类型别名,统一数据库接口
- 作为契约层抽象,便于后续数据库实现的替换
- 为插件相关的数据访问层提供统一的数据库连接接口
MySQL数据库实现
文件位置:backend/infra/impl/mysql/mysql.go
package mysqlimport ("fmt""os""gorm.io/driver/mysql""gorm.io/gorm"
)func New() (*gorm.DB, error) {dsn := os.Getenv("MYSQL_DSN")db, err := gorm.Open(mysql.Open(dsn))if err != nil {return nil, fmt.Errorf("mysql open, dsn: %s, err: %w", dsn, err)}return db, nil
}
在插件删除中的作用:
- 为
PluginDraftDAO
和ToolDraftDAO
提供数据库连接,支持插件的删除操作 - 通过GORM ORM框架,执行安全的
plugin_draft
和tool_draft
表删除操作 - 支持事务处理,确保插件删除过程的数据一致性和原子性
- 连接池管理,提高插件并发删除的性能和稳定性
- 支持级联删除,确保插件和相关工具数据的一致性清理
删除操作初始化流程:
main.go → application.Init() → appinfra.Init() → mysql.New() → PluginDAO注入 → 执行删除
6.2 ID生成器基础设施
ID生成器契约层
文件位置:backend/infra/contract/idgen/idgen.go
package idgenimport ("context"
)type IDGenerator interface {GenID(ctx context.Context) (int64, error)GenMultiIDs(ctx context.Context, counts int) ([]int64, error)
}
ID生成器实现
文件位置:backend/infra/impl/idgen/idgen.go
type idGenImpl struct {cli cache.Cmdablenamespace string
}func (i *idGenImpl) GenID(ctx context.Context) (int64, error) {ids, err := i.GenMultiIDs(ctx, 1)if err != nil {return 0, err}return ids[0], nil
}func (i *idGenImpl) GenMultiIDs(ctx context.Context, counts int) ([]int64, error) {// 基于时间戳+计数器+服务器ID的分布式ID生成算法// ID格式:[32位秒级时间戳][10位毫秒][8位计数器][14位服务器ID]// ...
}
在插件删除中的作用:
- 虽然删除操作不需要生成新ID,但ID生成器为删除操作提供了重要支撑
- 在删除事件发布时,为事件生成唯一的事件ID,确保事件处理的幂等性
- 支持删除操作的审计日志ID生成,便于操作追踪和问题排查
- 为删除相关的临时资源(如删除任务、回滚记录)生成唯一标识
- 为插件删除过程中的中间状态记录生成唯一标识
删除操作中的ID使用流程:
PluginService.DeleteDraftPlugin() → 验证插件ID → 执行删除 → 生成事件ID → 发布删除事件
6.3 缓存系统基础设施
缓存契约层
文件位置:backend/infra/contract/cache/cache.go
package cachetype Cmdable interface {Pipeline() PipelinerStringCmdableHashCmdableGenericCmdableListCmdable
}type StringCmdable interface {Set(ctx context.Context, key string, value interface{}, expiration time.Duration) StatusCmdGet(ctx context.Context, key string) StringCmdIncrBy(ctx context.Context, key string, value int64) IntCmd
}
Redis缓存实现
文件位置:backend/infra/impl/cache/redis/redis.go
func New() cache.Cmdable {addr := os.Getenv("REDIS_ADDR")password := os.Getenv("REDIS_PASSWORD")return NewWithAddrAndPassword(addr, password)
}func NewWithAddrAndPassword(addr, password string) cache.Cmdable {rdb := redis.NewClient(&redis.Options{Addr: addr,Password: password,PoolSize: 100,MinIdleConns: 10,MaxIdleConns: 30,ConnMaxIdleTime: 5 * time.Minute,DialTimeout: 5 * time.Second,ReadTimeout: 3 * time.Second,WriteTimeout: 3 * time.Second,})return &redisImpl{client: rdb}
}
在插件删除中的作用:
- 权限验证缓存:缓存用户权限信息,快速验证删除权限
- 插件信息缓存:缓存待删除插件的基本信息,减少数据库查询
- 分布式锁:防止并发删除同一插件,确保删除操作的原子性
- 删除状态缓存:临时存储删除操作的状态,支持删除进度查询
- 事件去重:缓存已处理的删除事件ID,避免重复处理
- 关联数据缓存:缓存插件关联的工具信息,优化级联删除性能
删除操作缓存使用场景:
1. 权限缓存:user_perm:{user_id}:{space_id}:{plugin_id}
2. 插件缓存:plugin_info:{plugin_id}
3. 删除锁:lock:plugin_delete:{plugin_id}
4. 删除状态:delete_status:{plugin_id}:{operation_id}
5. 事件去重:event_processed:{event_id}
6. 工具关联:plugin_tools:{plugin_id}
6.4 ElasticSearch搜索基础设施
ElasticSearch契约层
文件位置:backend/infra/contract/es/es.go
package estype Client interface {Create(ctx context.Context, index, id string, document any) errorUpdate(ctx context.Context, index, id string, document any) errorDelete(ctx context.Context, index, id string) errorSearch(ctx context.Context, index string, req *Request) (*Response, error)Exists(ctx context.Context, index string) (bool, error)CreateIndex(ctx context.Context, index string, properties map[string]any) error
}type BulkIndexer interface {Add(ctx context.Context, item BulkIndexerItem) errorClose(ctx context.Context) error
}
ElasticSearch实现层
文件位置:backend/infra/impl/es/es_impl.go
func New() (es.Client, error) {version := os.Getenv("ES_VERSION")switch version {case "7":return newES7Client()case "8":return newES8Client()default:return newES8Client() // 默认使用ES8}
}
在插件删除中的作用:
- 索引删除:将删除的插件从ES的
coze_resource
索引中移除 - 搜索结果更新:确保删除的插件不再出现在搜索结果中
- 关联数据清理:清理与删除插件相关的搜索索引和元数据
- 实时同步:插件删除后实时从搜索引擎中移除
- 批量删除:支持批量删除插件时的批量索引清理
- 工具索引清理:同时清理插件关联的工具索引数据
删除操作的索引处理:
{"operation": "delete","res_id": 123456789,"res_type": 1,"delete_time": 1703123456789,"operator_id": 987654321,"space_id": 111222333
}
删除索引执行流程:
1. 用户删除插件 → API Gateway → PluginService.DeleteDraftPlugin()
2. 执行数据库删除 → 发布删除事件 → ES删除处理器
3. 构建删除请求 → esClient.Delete(ctx, "coze_resource", pluginID)
4. 索引清理 → 验证删除结果 → 记录删除日志
6.5 基础设施层架构优势
依赖倒置原则
- 契约层抽象:业务层依赖接口而非具体实现
- 实现层解耦:可以灵活替换数据库、缓存、搜索引擎的具体实现
- 测试友好:通过Mock接口进行单元测试
配置驱动
- 环境变量配置:通过环境变量控制各组件的连接参数
- 版本兼容:支持ES7/ES8版本切换,数据库驱动切换
- 性能调优:连接池、超时时间等参数可配置
高可用设计
- 连接池管理:数据库和Redis连接池,提高并发性能
- 错误处理:完善的错误处理和重试机制
- 监控支持:提供性能指标和健康检查接口
扩展性支持
- 水平扩展:分布式ID生成支持多实例部署
- 存储扩展:支持分库分表、读写分离
- 搜索扩展:支持ES集群部署和索引分片
这种基础设施层的设计为插件删除功能提供了稳定、高效、可扩展的技术底座,确保了删除操作在高并发场景下的安全性、一致性和可靠性。