1 Star 0 Fork 0

Cruvie Kang/kk_go_kit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
kk_executor.go 2.36 KB
一键复制 编辑 原始数据 按行查看 历史
cruvie 提交于 2024-10-25 14:36 . 1.23.2
package kk_executor
import (
"errors"
"gitee.com/cruvie/kk_go_kit/kk_log"
"gitee.com/cruvie/kk_go_kit/kk_minio"
"gitee.com/cruvie/kk_go_kit/kk_stage"
"gorm.io/gorm"
"log/slog"
)
// Executor 失败时执行回滚程序
func Executor(stage *kk_stage.Stage, do func() error, failBack func() error) error {
newLog := kk_log.NewLog(&kk_log.LogOption{TraceId: stage.TraceId})
if do == nil {
panic("Executor do is nil")
}
doErr := do()
doErrLog := newLog.Copy().Error(doErr)
if doErr != nil {
slog.Info("Executor begin to roll back", doErrLog.Args()...)
if failBack != nil {
failBackErr := failBack()
if failBackErr != nil {
failBackErrLog := newLog.Copy().Error(failBackErr)
slog.Error("Executor fail to roll back", failBackErrLog.Args()...)
return failBackErrLog.ToError()
}
}
slog.Info("Executor success to roll back", newLog.Copy().Args()...)
}
return doErrLog.ToError()
}
// SyncExecutor sync executor
type SyncExecutor struct {
Stage *kk_stage.Stage
DB *gorm.DB
DBDo func(tx *gorm.DB) error
MinIOObjects []kk_minio.OPObject
}
func (e *SyncExecutor) check() {
if e.Stage == nil {
panic("Executor stage is nil")
}
if e.DBDo != nil && e.DB == nil {
panic("Executor DB is nil")
}
}
func (e *SyncExecutor) Execute() error {
e.check()
transaction := func() *gorm.DB {
if e.DBDo != nil {
return e.DB.Begin()
}
return nil
}()
err := Executor(e.Stage, func() error {
{
if e.DBDo != nil {
err := e.DBDo(transaction)
if err != nil {
return err
}
}
}
{
//upload opObjects
if len(e.MinIOObjects) > 0 {
err := kk_minio.BatchOperator(e.MinIOObjects, kk_minio.UploadFileStream)
if err != nil {
return err
}
}
}
{
//commit transaction finally
if transaction != nil {
if err := transaction.Commit().Error; err != nil {
return err
}
}
}
return nil
}, func() error {
var errs error
{
if transaction != nil {
if err := transaction.Rollback().Error; err != nil {
errs = errors.Join(errs, err)
}
}
}
{
//delete opObjects
if len(e.MinIOObjects) > 0 {
err := kk_minio.BatchOperator(e.MinIOObjects, kk_minio.RemoveObject)
errs = errors.Join(errs, err)
err = kk_minio.BatchOperator(e.MinIOObjects, kk_minio.RemoveIncompleteObject)
errs = errors.Join(errs, err)
}
}
return errs
})
return err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cruvie/kk_go_kit.git
git@gitee.com:cruvie/kk_go_kit.git
cruvie
kk_go_kit
kk_go_kit
v0.1.2

搜索帮助