Initial commit: archer, a Go-native MySQL/MariaDB table archiver
Renamed from arcdb: module path, cmd/archer, internal/archererr, docs, build scripts and ARCHER_* environment variables. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
bc4a6b504f
99 files changed
+12752
No files matched your search
@@ -0,0 +1,56 @@
|
||||
// Package atomicfile 提供 Windows 上更稳健的原子文件替换。
|
||||
//
|
||||
// 直接 os.Rename 在 Windows 上走 MoveFileEx(MOVEFILE_REPLACE_EXISTING),
|
||||
// 只要目标文件此刻被任何进程以「不共享删除」方式打开(杀毒软件实时扫描、
|
||||
// Windows Search 索引器、编辑器预览等都会这样),就会返回
|
||||
// ERROR_ACCESS_DENIED,而且这种占用通常是毫秒级的瞬时状态。
|
||||
// 因此这里对 rename 做有限次指数退避重试;非 Windows 平台无此问题,
|
||||
// 但同样行为无害(第一次就成功)。
|
||||
package atomicfile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// renameRetries 是 rename 的最大尝试次数(含首次)。
|
||||
const renameRetries = 12
|
||||
|
||||
// Replace 原子地用 tmp 覆盖 final。tmp 与 final 必须在同一文件系统内。
|
||||
//
|
||||
// 失败时保留 tmp 供调用者排查,并返回最后一次 rename 的原始错误。
|
||||
func Replace(tmp, final string) error {
|
||||
var err error
|
||||
delay := time.Millisecond
|
||||
for i := 0; i < renameRetries; i++ {
|
||||
if err = os.Rename(tmp, final); err == nil {
|
||||
return nil
|
||||
}
|
||||
// 非 Windows 上的失败基本都是真错误(跨设备、权限、目录不存在),
|
||||
// 重试无意义,立即返回。
|
||||
if runtime.GOOS != "windows" || !isTransient(err) {
|
||||
return err
|
||||
}
|
||||
time.Sleep(delay)
|
||||
if delay < 20*time.Millisecond {
|
||||
delay *= 2
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w (after %d attempts; the file is likely held open by "+
|
||||
"antivirus or the search indexer)", err, renameRetries)
|
||||
}
|
||||
|
||||
// isTransient 判断 rename 失败是否属于「目标被短暂占用」。
|
||||
//
|
||||
// 只识别 Windows 上真实的瞬时错误码。os.Rename 已经把 Win32 错误包成
|
||||
// *os.LinkError,其 Err 是 syscall.Errno,可直接与 syscall 常量比较。
|
||||
func isTransient(err error) bool {
|
||||
var le *os.LinkError
|
||||
if !errors.As(err, &le) {
|
||||
return false
|
||||
}
|
||||
return isTransientErrno(le.Err)
|
||||
}
|
||||
Reference in new issue
Block a user