devbox/cmd/devbox-hub/lock_test.go
shoemoney f51e69839a
Some checks are pending
CI / vet-build-test (push) Waiting to run
fix(hub): flock gc against backup so a sweep can't strand a backup mid-copy 🔒💾
`backup` does VACUUM INTO (DB snapshot) then copies the blob tree; a concurrent
gc sweep could delete a blob the snapshot references between those steps,
producing a backup that's internally inconsistent — a dangling ref you'd only
discover on restore. Now gc sweeps (the --gc-every ticker AND `gc`) and `backup`
take an exclusive flock on <data>/.lock, so they can't overlap. Dry-run gc skips
the lock (read-only, must not block a long backup). unix flock (auto-released on
crash); no-op stub on non-unix (the hub ships linux/darwin).

Test: TestDataLockMutualExclusion. Cross-builds clean for windows + linux/arm64.
2026-06-30 17:27:00 -05:00

39 lines
1 KiB
Go

//go:build unix
package main
import (
"os"
"path/filepath"
"syscall"
"testing"
)
// TestDataLockMutualExclusion proves dataLock actually excludes a concurrent
// holder — the property gc/backup serialization depends on.
func TestDataLockMutualExclusion(t *testing.T) {
data := t.TempDir()
release, err := dataLock(data)
if err != nil {
t.Fatalf("dataLock: %v", err)
}
// A second exclusive, non-blocking flock must FAIL while the lock is held.
f, err := os.OpenFile(filepath.Join(data, ".lock"), os.O_RDWR, 0o600)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
t.Fatal("second flock acquired while the lock was held — no mutual exclusion")
}
release()
// After release, the lock is acquirable again.
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
t.Fatalf("flock should succeed after release: %v", err)
}
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
}