mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-30 14:26:36 +08:00
dbaa3bf140
docs(changelog): 修正表述笔误
refactor(cordis): 磁盘缓存改用上上游能力并清理本地副本
按上游/下游归属规约:类型断言守卫已回流 Wavelet(f3d85d5,附回归用例),
本仓库删除 OpenFlare/plugins/server/pkg/cache 整包并改 import 到
Wavelet/pkg/cache/disk,同步后与上游零漂移。
验证:go build 通过;go test ./... exit 0(137 包 ok);256 条路由对拍与
232 条 swagger 操作均零差异;make build-all 四进制;前端零改动。
docs(cordis): 记录 T1 清理结果与五个复用阻塞点
refactor(cordis): server 复用上游 pkg 能力并删除等价本地副本
按上游/下游归属规约清理重复实现,删除 7 个与上游等价的本地包并改 import:
shared/response→pkg/response、pkg/{logger,mail,trace,httppool,cache/ram}→
上游同名包、infra/persistence/batchwriter→pkg/batchwriter。逐项核过差异:
httppool 逐字节相同;logger 的 Config 字段完全一致;response 的 7 个 Abort*
一致;cache/ram 换过去顺带把裸 go 变回带 panic 恢复的 util.Go。
两处非等价差异按语义处理:
- batchwriter.Stats 与 status DTO 原为类型别名,改为消费侧逐字段转换,
避免 model 反向依赖基础设施类型;
- 上游 pkg/idgen 要求显式 Init(本地副本为懒加载自动初始化),本次保留本地
副本,待与 infra 初始化一并迁移(已登记在清理计划)。
验证:go build 通过;go test ./... exit 0(138 包 ok);256 条路由对拍零差异;
make swagger 232 条操作零增减,且归一化后与旧文档深度相等——差异仅为
response.Any / logger.LogEntry 两个定义名随包路径改名,接口形状未变。
chore(cordis): 回流内核与 pkg/util 通用能力并清理 vendoring 污染
按新增的上游/下游归属规约:HandleRaw/BasePath 与版本比较、网络、格式化助手
属通用能力,已提交到 Wavelet 分支 feat/cordis-router-raw-routes,本仓库改为
纯同步获取(pkg/util 已零漂移),补丁登记保留至上游合并。
同时修掉我此前 git add -A 造成的污染:首次 vendoring 把上游工作区里被
gitignore 的运行期产物一起提交进来(upload 的 diskcache 缓存块 650 个与
driver_http/dist 前端构建物 380 个,共 12872 行/1030 文件)。sync-upstream.sh
现显式排除 uploads/dist/data/*.db,.gitignore 补上对应兜底规则。
AGENTS.md 增加上游/下游改动归属规约,并把仍指向前 Cordis 布局的硬性约束
(internal/router + Serve、internal/repository/logstore、internal/platform/bootstrap、
internal/cmd)改到当前插件路径。
验证:go build 通过;go test ./... exit 0(144 包 ok);make swagger 232 条
操作与基线逐条一致;make build-all 四进制;gofmt 干净。
feat(cordis): server 插件化并改由内核挂载控制面路由
新增 plugins/server/plugin.go:Apply 以 ctx.Router().Group(app.api_prefix)
声明根级与 /v1 全部路由;33 个注册函数由 *gin.RouterGroup 改为
core.RouterExtension,RegisterCollection 改用内核新增的 HandleRaw 保留
尾部斜杠变体,AdminMiddlewares 返回 []any(Go 不允许把 []T 展开为 ...any)。
删除 router.Serve 与 registerRoutes,装配根改为 core.App +
driver_http.New(WithEngine(router.BuildEngine())),监听、信号与优雅退出归内核;
前端 SPA 的 NoRoute 兜底因内核暂无贡献点而保留在引擎层。
路由保真证据:plugin_parity_test 对拍 baseline/routes-engine.txt 的 256 条
(方法 路径) 零差异;go test ./... exit 0(144 包 ok,含真实 handler 的
openflare/integration 用例走同一条挂载路径);make swagger 232 条操作与基线
逐条一致;golangci-lint 0 issues;make build-all 四进制;embed_frontend
标签编译通过;前端零改动。
已知待补:带 Redis 的实机 HTTP 冒烟(本机 6379 未启动,session store 与
改造前一样在建店阶段即 fatal),以及 bootstrap 的任务/设置/迁移注册迁入 Apply。
feat(core): RouterExtension 增加 HandleRaw 与 BasePath 以保真尾部斜杠路由
server 插件化的前置:Handle 经 cleanPath 会剥掉尾部斜杠,无法表达
/resource 与 /resource/ 两条不同路由,而 OpenFlare 有 20 个历史 list
端点两者都注册且部署关闭了 RedirectTrailingSlash,缺失即 404。新增
HandleRaw 与 BasePath(作用域包装器同样登记反注册),补 extpoints 用例;
并把 router.Serve 拆出 BuildEngine 以便交给 driver_http.WithEngine 复用,
新增路由表导出 harness,固化 256 条 (方法 路径) 基线供插件化对拍。
上游补丁登记于 backend/OpenFlare/upstream-patches.md,同步脚本改为按目录
前缀输出差异并在同步后提醒确认补丁是否仍在。
验证:go build 通过;go test ./... exit 0(143 包 ok);gofmt 干净。
docs(cordis): 记录 server 插件接入内核的可行路径与内核能力缺口
feat(cordis): agent/relay/flared 落地为内核驱动插件
三个边缘守护进程各新增 plugin.go,实现 core.Plugin + core.Driver
(自定义 DriverType 与同名 profile),装配与生命周期从 main 迁入
Apply/Start/Stop:Apply 负责 JSON 配置加载、运行环境与用户确保、
openresty/frps/frpc 管理器与各服务装配;Start 以 util.Go 拉起阻塞式
runner 与 GeoIP 周期更新;Stop 收敛主循环结果并在超时时报错而非静默。
入口改为 core.NewApp(core.WithProfile(...)) + Prepare/Run,保持
-config 旗标、默认路径、退出码与启动/停止日志不变。
验证:go build 通过;go test ./... exit 0(143 包 ok,含 3 个插件身份
与配置失败路径测试);make build-all 四进制产出;三进制实跑缺失配置
均 exit 1 且错误链保留 load {agent,relay,flared} config 原因;gofmt 干净。
refactor(cordis): 按功能职责拆分为 4 个插件与 share 共享层
backend/OpenFlare 不再平铺遗留分层,改为 plugins/{server,agent,relay,flared}
加 share/:控制面业务(openflare/admin/oauth/user/upload/cap/config/health 与
repository/model/infra/router 等支撑层)归 server;三个边缘守护进程各自成插件;
被两个以上插件消费的 protocol/geoip/wsclient/render/pagesarchive/edge 归 share。
同时把 pkg/util 与 buildinfo 合并回上游 pkg(上游已覆盖全部符号,仅 8 个函数与
2 个类型为 OpenFlare 独有,已一并迁入),装配根统一到 backend/cmd(含三个 daemon
入口),Dockerfile 与 release 工作流的构建路径和 -X 注入路径同步更新。
验证:go build 通过;go test ./... exit 0(141 包 ok);make swagger exit 0 且
232 条 API 操作与基线逐条一致;make build-all 产出 4 进制;-X 注入经二进制
strings 实测生效;日志后端直连门禁改写为按 server 插件业务域扫描并在扫描数为 0
时报错(防门禁静默失效);前端零改动。
feat(cordis): 落地 backend/share 共享层与上游同步脚本
跨插件共享资源(控制消息协议、GeoIP+iputil、边缘守护进程日志)从下游包
移入 backend/share,并声明其只能依赖 core/pkg 与标准/第三方库,禁止反向
引用下游业务与具体插件实现;新增 scripts/sync-upstream.sh 只覆盖
backend/{core,pkg,plugins},同步后 --check 报告零差异,证明与上游逐字一致。
go build 通过,go test ./... exit 0(142 包 ok),前端零改动。
refactor(cordis): 采用与 Wavelet 同构的单模块布局并引入上游内核
按上游结构落位:backend/{core,pkg,plugins} 为 Wavelet 上游拷贝,OpenFlare
全部业务收拢到上游 downstream 所对应的位置 backend/OpenFlare/,模块名保持
Wavelet 以保证上游 import 路径逐字一致、同步零改写;三个 daemon 入口移至
backend/OpenFlare/cmd,backend/cmd 与 main.go 作为控制面装配根。
行为不变:go build 通过,142 个测试包全绿(含上游插件测试),232 条 API
操作与改造前逐条一致,四进制产物正常,前端零改动。swagger 暂只扫描下游代码,
待 P4 挂载上游路由后再纳入 plugins/。
style: 修正模块路径改写导致的 import 分组排序漂移
refactor(layout): Go 代码迁入 backend/ 并将模块名简化为 OpenFlare
对齐上游 Wavelet 的仓库布局,为以第二 module 形态 vendoring Cordis 内核与
平台插件做准备:模块路径整体改写为 OpenFlare,Go 目标加 cd backend,
swaggo 产物移至 backend/docs 并把 json/yaml 复制回 docs/ 供站点消费,
Dockerfile 与 release 工作流的构建目录、ldflags 模块路径同步更新。
行为保持不变:232 条路由与改造前逐条一致,95 个测试包全绿,
四进制产物正常,前端零改动。
chore(cordis): 落地改造计划与 schema/路由基线
新增 legacy_dump_test 迁移快照 harness:在临时 sqlite 库上按生产顺序
(goose.UpTo → zone 导入 → goose.Up)跑完 76 个历史迁移并导出 schema 与
版本序列,作为改造前后一致性门禁的唯一事实来源。同时记录 232 条路由清单
与 foundation 实施计划。
docs(cordis): add OpenFlare Cordis 架构改造设计
明确上游以第二 module 形态 vendoring 进 backend/Wavelet、4 个插件
(server/agent/relay/flared) 全部装载内核,并规定保留 76 个历史 goose
迁移 + 一次性版本 stamp 桥接的迁移方案,配套三方 schema 一致性门禁,
确保已部署库不重跑历史、不丢数据。
400 lines
12 KiB
Go
400 lines
12 KiB
Go
// Copyright 2026 Arctel.net
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package task
|
|
|
|
import (
|
|
"Wavelet/core/contracts"
|
|
"Wavelet/pkg/logger"
|
|
"Wavelet/pkg/util"
|
|
"Wavelet/plugins/domain/upload/models"
|
|
"Wavelet/plugins/domain/upload/shared"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"golang.org/x/sync/errgroup"
|
|
|
|
uploadstats "Wavelet/plugins/domain/upload/stats"
|
|
uploadstorage "Wavelet/plugins/domain/upload/storage"
|
|
)
|
|
|
|
const (
|
|
// StorageMigrationTask is the task name for storage migration.
|
|
StorageMigrationTask = uploadstorage.StorageMigrationTask
|
|
// TaskTypeStorageMigration is the task metadata type for storage migration.
|
|
TaskTypeStorageMigration = "storage_migration"
|
|
)
|
|
|
|
// StorageMigrationMeta describes the manually dispatchable migration task.
|
|
var StorageMigrationMeta = contracts.TaskMetaDTO{
|
|
Type: TaskTypeStorageMigration,
|
|
AsynqTask: StorageMigrationTask,
|
|
Name: "迁移文件存储",
|
|
DisplayName: "迁移文件存储",
|
|
Description: "将活动存储中的文件迁移到待切换的目标存储,迁移期间文件系统保持只读",
|
|
Category: taskCategoryUpload,
|
|
SupportsTime: false,
|
|
MaxRetry: 1,
|
|
Queue: taskQueueDefault,
|
|
Retryable: true,
|
|
Params: []contracts.TaskParamDTO{
|
|
{
|
|
Name: "target",
|
|
Label: "目标存储配置 (JSON)",
|
|
Type: "text",
|
|
Required: true,
|
|
Placeholder: `{"driver": "s3", "local": {"root": "."}, "s3": {"bucket": "my-bucket"}}`,
|
|
Description: "待迁移到的目标存储引擎完整配置 JSON 字符串",
|
|
},
|
|
},
|
|
}
|
|
|
|
// MigrationHandler copies stored objects and activates the target backend.
|
|
type MigrationHandler struct{}
|
|
|
|
// ValidatePayload rejects duplicate active migrations through the task framework.
|
|
func (h *MigrationHandler) ValidatePayload(payload []byte) ([]byte, error) {
|
|
normalized, _, err := uploadstorage.NormalizeMigrationPayload(context.Background(), payload)
|
|
if err != nil {
|
|
return payload, err
|
|
}
|
|
active, err := hasUnresolvedMigrationTask(context.Background())
|
|
if err != nil {
|
|
return payload, err
|
|
}
|
|
if active {
|
|
return payload, fmt.Errorf("storage migration task is already unresolved")
|
|
}
|
|
return normalized, nil
|
|
}
|
|
|
|
// Execute migrates all unique active-storage objects to the pending backend.
|
|
func (h *MigrationHandler) Execute(ctx context.Context, payload []byte) (*contracts.TaskResultDTO, error) {
|
|
cache := shared.GetCache(ctx)
|
|
if cache != nil {
|
|
const (
|
|
cleanupTimeout = 5 * time.Second
|
|
renewalInterval = 10 * time.Minute
|
|
)
|
|
|
|
lockKey := "lock:storage:migrate"
|
|
var lockVal string
|
|
if err := cache.Get(ctx, lockKey, &lockVal); err == nil && lockVal != "" {
|
|
return nil, errors.New("另一个存储迁移任务正在运行中")
|
|
}
|
|
_ = cache.Set(ctx, lockKey, "locked", time.Hour)
|
|
|
|
stopRenewal := make(chan struct{})
|
|
//nolint:contextcheck
|
|
defer func() {
|
|
close(stopRenewal)
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), cleanupTimeout)
|
|
defer cancel()
|
|
_ = cache.Delete(cleanupCtx, lockKey)
|
|
}()
|
|
|
|
util.Go(func() {
|
|
ticker := time.NewTicker(renewalInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
renewCtx, cancel := context.WithTimeout(context.Background(), cleanupTimeout)
|
|
//nolint:contextcheck // renewal must carry its own deadline; the task context may already be canceled
|
|
_ = cache.Set(renewCtx, lockKey, "locked", time.Hour)
|
|
cancel()
|
|
case <-stopRenewal:
|
|
return
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
active, err := uploadstorage.LoadStorageConfig(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("load active storage config: %w", err)
|
|
}
|
|
target, err := uploadstorage.ParseMigrationTargetConfig(ctx, payload)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if target.Driver == active.Driver {
|
|
if err := uploadstorage.SaveActiveConfig(ctx, target); err != nil {
|
|
return nil, fmt.Errorf("activate same-driver storage config: %w", err)
|
|
}
|
|
message := fmt.Sprintf("存储配置已更新,活动存储保持为 %s", target.Driver)
|
|
logger.InfoF(ctx, "%s", message)
|
|
return &contracts.TaskResultDTO{Message: message}, nil
|
|
}
|
|
|
|
total, err := countStorageObjects(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("count source objects: %w", err)
|
|
}
|
|
if total == 0 {
|
|
if err := uploadstorage.SaveActiveConfig(ctx, target); err != nil {
|
|
return nil, fmt.Errorf("activate empty storage config: %w", err)
|
|
}
|
|
message := fmt.Sprintf("当前存储没有需要迁移的对象,活动存储已切换为 %s", target.Driver)
|
|
logger.InfoF(ctx, "%s", message)
|
|
return &contracts.TaskResultDTO{Message: message}, nil
|
|
}
|
|
|
|
storageSvc := shared.GetStorage(ctx)
|
|
if storageSvc == nil {
|
|
return nil, errors.New("source storage service not available")
|
|
}
|
|
|
|
logger.InfoF(ctx, "开始存储迁移: %s -> %s,总对象数: %d", active.Driver, target.Driver, total)
|
|
migrated, err := migrateObjects(ctx, storageSvc, storageSvc, total)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := uploadstorage.SaveActiveConfig(ctx, target); err != nil {
|
|
return nil, fmt.Errorf("activate target storage: %w", err)
|
|
}
|
|
message := fmt.Sprintf("存储迁移完成,共迁移 %d 个对象,活动存储已切换为 %s", migrated, target.Driver)
|
|
logger.InfoF(ctx, "%s", message)
|
|
return &contracts.TaskResultDTO{Message: message}, nil
|
|
}
|
|
|
|
func countStorageObjects(ctx context.Context) (int64, error) {
|
|
var count int64
|
|
db := shared.GetDB(ctx)
|
|
if db == nil {
|
|
return 0, errors.New("database not available")
|
|
}
|
|
err := db.Model(&models.Upload{}).
|
|
Where("status != ?", models.UploadStatusDeleted).
|
|
Distinct("file_path").
|
|
Count(&count).Error
|
|
return count, err
|
|
}
|
|
|
|
func hasUnresolvedMigrationTask(ctx context.Context) (bool, error) {
|
|
execution, ok, err := uploadstorage.LatestMigrationExecution(ctx)
|
|
if err != nil || !ok || execution == nil {
|
|
return false, err
|
|
}
|
|
return execution.Status == "pending" || execution.Status == "running", nil
|
|
}
|
|
|
|
type migrationObject struct {
|
|
FilePath string `gorm:"column:file_path"`
|
|
FileSize int64 `gorm:"column:file_size"`
|
|
MimeType string `gorm:"column:mime_type"`
|
|
Hash string `gorm:"column:hash"`
|
|
}
|
|
|
|
type storageReaderWriter interface {
|
|
Get(ctx context.Context, key string) (*contracts.StorageObject, error)
|
|
Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) (contracts.StoragePutResult, error)
|
|
}
|
|
|
|
func migrateObjects(
|
|
ctx context.Context,
|
|
sourceBackend storageReaderWriter,
|
|
targetBackend storageReaderWriter,
|
|
total int64,
|
|
) (int64, error) {
|
|
const batchSize = 50
|
|
const migrationConcurrency = 10
|
|
const sha256HexLength = 64
|
|
var migrated int64
|
|
var lastFilePath string
|
|
db := shared.GetDB(ctx)
|
|
if db == nil {
|
|
return 0, errors.New("database not available")
|
|
}
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
return atomic.LoadInt64(&migrated), fmt.Errorf("storage migration canceled: %w", err)
|
|
}
|
|
|
|
logger.InfoF(ctx, "正在查询待迁移对象批次,当前已完成迁移: %d/%d", atomic.LoadInt64(&migrated), total)
|
|
|
|
var objects []migrationObject
|
|
query := db.Model(&models.Upload{}).
|
|
Select("file_path, MAX(file_size) AS file_size, MAX(mime_type) AS mime_type, MAX(hash) AS hash").
|
|
Where("status != ?", models.UploadStatusDeleted)
|
|
if lastFilePath != "" {
|
|
query = query.Where("file_path > ?", lastFilePath)
|
|
}
|
|
if err := query.Group("file_path").
|
|
Order("file_path ASC").
|
|
Limit(batchSize).
|
|
Scan(&objects).Error; err != nil {
|
|
return atomic.LoadInt64(&migrated), fmt.Errorf("query source objects: %w", err)
|
|
}
|
|
if len(objects) == 0 {
|
|
logger.InfoF(ctx, "所有对象迁移完毕")
|
|
break
|
|
}
|
|
|
|
lastFilePath = objects[len(objects)-1].FilePath
|
|
logger.InfoF(ctx, "获取当前批次迁移对象,批次大小: %d,实际获取对象数: %d", batchSize, len(objects))
|
|
|
|
var g errgroup.Group
|
|
g.SetLimit(migrationConcurrency)
|
|
|
|
for _, object := range objects {
|
|
obj := object
|
|
g.Go(func() error {
|
|
if err := migrateSingleObject(ctx, sourceBackend, targetBackend, obj, sha256HexLength); err != nil {
|
|
return err
|
|
}
|
|
atomic.AddInt64(&migrated, 1)
|
|
return nil
|
|
})
|
|
}
|
|
|
|
if err := g.Wait(); err != nil {
|
|
return atomic.LoadInt64(&migrated), err
|
|
}
|
|
|
|
logger.InfoF(ctx, "当前批次迁移完成。迁移进度: %d/%d", atomic.LoadInt64(&migrated), total)
|
|
}
|
|
return atomic.LoadInt64(&migrated), nil
|
|
}
|
|
|
|
func migrateSingleObject(
|
|
ctx context.Context,
|
|
sourceBackend storageReaderWriter,
|
|
targetBackend storageReaderWriter,
|
|
obj migrationObject,
|
|
sha256HexLength int,
|
|
) error {
|
|
if shouldSkipMigration(ctx, sourceBackend, targetBackend, obj) {
|
|
logger.InfoF(ctx, "[跳过迁移] 目标存储已存在相同文件: %s", obj.FilePath)
|
|
return nil
|
|
}
|
|
|
|
logger.InfoF(ctx, "[迁移开始] 正在从源存储读取文件: %s", obj.FilePath)
|
|
source, err := sourceBackend.Get(ctx, obj.FilePath)
|
|
if err != nil {
|
|
if isNotFoundError(err) {
|
|
return markMissingMigrationObjectDeleted(ctx, obj.FilePath, err)
|
|
}
|
|
return fmt.Errorf("open source object %q: %w", obj.FilePath, err)
|
|
}
|
|
logger.InfoF(ctx, "[传输中] 正在向目标存储上传文件: %s (大小: %d 字节, 类型: %s)", obj.FilePath, obj.FileSize, obj.MimeType)
|
|
targetResult, putErr := targetBackend.Put(ctx, obj.FilePath, source.Body, obj.FileSize, obj.MimeType)
|
|
closeErr := source.Body.Close()
|
|
if putErr != nil {
|
|
return fmt.Errorf("copy object %q: %w", obj.FilePath, putErr)
|
|
}
|
|
if closeErr != nil {
|
|
return fmt.Errorf("close source object %q: %w", obj.FilePath, closeErr)
|
|
}
|
|
|
|
if len(obj.Hash) == sha256HexLength {
|
|
logger.InfoF(ctx, "[校验中] 正在对目标文件进行数据一致性校验 (SHA-256): %s", targetResult.Key)
|
|
targetObj, getErr := targetBackend.Get(ctx, targetResult.Key)
|
|
if getErr != nil {
|
|
return fmt.Errorf("retrieve target object for verification %q: %w", obj.FilePath, getErr)
|
|
}
|
|
if targetObj == nil || targetObj.Body == nil {
|
|
return fmt.Errorf("retrieve target object for verification %q: object or body is nil", obj.FilePath)
|
|
}
|
|
h := sha256.New()
|
|
if _, copyErr := io.Copy(h, targetObj.Body); copyErr != nil {
|
|
_ = targetObj.Body.Close()
|
|
return fmt.Errorf("read target object for verification %q: %w", obj.FilePath, copyErr)
|
|
}
|
|
_ = targetObj.Body.Close()
|
|
|
|
computedHash := hex.EncodeToString(h.Sum(nil))
|
|
if computedHash != obj.Hash {
|
|
return fmt.Errorf("integrity check failed for %q: got hash %s, want %s", obj.FilePath, computedHash, obj.Hash)
|
|
}
|
|
logger.InfoF(ctx, "[校验通过] 文件一致性校验成功: %s", targetResult.Key)
|
|
}
|
|
|
|
db := shared.GetDB(ctx)
|
|
if targetResult.Key != obj.FilePath && db != nil {
|
|
logger.InfoF(ctx, "[更新数据库] 正在更新文件路径: %s -> %s", obj.FilePath, targetResult.Key)
|
|
if err := db.Model(&models.Upload{}).
|
|
Where("file_path = ? AND status != ?", obj.FilePath, models.UploadStatusDeleted).
|
|
Update("file_path", targetResult.Key).Error; err != nil {
|
|
return fmt.Errorf("update migrated object %q: %w", obj.FilePath, err)
|
|
}
|
|
}
|
|
logger.InfoF(ctx, "[迁移成功] 文件已完成迁移: %s", targetResult.Key)
|
|
return nil
|
|
}
|
|
|
|
func shouldSkipMigration(
|
|
ctx context.Context,
|
|
sourceBackend storageReaderWriter,
|
|
targetBackend storageReaderWriter,
|
|
obj migrationObject,
|
|
) bool {
|
|
if sourceBackend == targetBackend {
|
|
return false
|
|
}
|
|
targetObj, err := targetBackend.Get(ctx, obj.FilePath)
|
|
if err != nil || targetObj == nil || targetObj.Body == nil {
|
|
return false
|
|
}
|
|
defer func() {
|
|
_ = targetObj.Body.Close()
|
|
}()
|
|
|
|
return targetObj.ContentLength == obj.FileSize
|
|
}
|
|
|
|
func markMissingMigrationObjectDeleted(
|
|
ctx context.Context,
|
|
filePath string,
|
|
sourceErr error,
|
|
) error {
|
|
logger.WarnF(ctx, "警告: 源存储中物理文件不存在,标记为已删除并跳过: %s (错误: %v)", filePath, sourceErr)
|
|
db := shared.GetDB(ctx)
|
|
if db == nil {
|
|
return errors.New("database not available")
|
|
}
|
|
|
|
var affectedUploads []models.Upload
|
|
if err := db.
|
|
Where("file_path = ? AND status != ?", filePath, models.UploadStatusDeleted).
|
|
Find(&affectedUploads).Error; err != nil {
|
|
return fmt.Errorf("load missing object uploads %q: %w", filePath, err)
|
|
}
|
|
if err := db.Model(&models.Upload{}).
|
|
Where("file_path = ?", filePath).
|
|
Update("status", models.UploadStatusDeleted).Error; err != nil {
|
|
return fmt.Errorf("update missing object %q: %w", filePath, err)
|
|
}
|
|
for i := range affectedUploads {
|
|
_ = uploadstats.ApplyUploadStatsRemove(ctx, &affectedUploads[i])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isNotFoundError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return true
|
|
}
|
|
errStr := strings.ToLower(err.Error())
|
|
for _, sub := range []string{"not found", "nosuchkey", "nosuchbucket", "404", "does not exist"} {
|
|
if strings.Contains(errStr, sub) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|