| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | "testing/fstest" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | func TestCacheLockOwnerProcess(t *testing.T) { |
| 18 | path := os.Getenv("LAST30DAYS_TEST_CACHE_LOCK") |
| 19 | if path == "" { |
| 20 | return |
| 21 | } |
| 22 | file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | defer file.Close() |
| 27 | if err := lockCacheFile(file); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | if err := os.WriteFile(path+".ready", nil, 0o600); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | time.Sleep(time.Minute) |
| 34 | } |
| 35 | |
| 36 | func startCacheLockOwner(t *testing.T, path string) func() { |
| 37 | t.Helper() |
| 38 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | return startCacheTestProcess(t, "TestCacheLockOwnerProcess", []string{"LAST30DAYS_TEST_CACHE_LOCK=" + path}, path+".ready") |
| 42 | } |
| 43 | |
| 44 | func startCacheTestProcess(t *testing.T, test string, env []string, ready string) func() { |
| 45 | t.Helper() |
| 46 | executable, err := os.Executable() |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 51 | t.Cleanup(cancel) |
| 52 | cmd := exec.CommandContext(ctx, executable, "-test.run=^"+test+"$") |
| 53 | cmd.Env = append(os.Environ(), env...) |
| 54 | var output bytes.Buffer |
| 55 | cmd.Stdout = &output |
| 56 | cmd.Stderr = &output |
| 57 | if err := cmd.Start(); err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | var stopped sync.Once |
| 61 | stop := func() { |
| 62 | stopped.Do(func() { |
| 63 | _ = cmd.Process.Kill() |
| 64 | _ = cmd.Wait() |
| 65 | }) |
| 66 | } |
| 67 | t.Cleanup(stop) |
| 68 | deadline := time.Now().Add(10 * time.Second) |
| 69 | for { |
| 70 | if _, err := os.Stat(ready); err == nil { |
| 71 | return stop |
| 72 | } |
| 73 | if time.Now().After(deadline) { |
| 74 | stop() |
| 75 | t.Fatalf("child process did not become ready: %s", &output) |
| 76 | } |
| 77 | time.Sleep(10 * time.Millisecond) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | func cacheStagePaths(t *testing.T, base string) []string { |
| 82 | t.Helper() |
| 83 | paths, err := filepath.Glob(filepath.Join(cacheParentDir(base), "v1.tmp-*")) |
| 84 | if err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | var stages []string |
| 88 | for _, path := range paths { |
| 89 | if !strings.HasSuffix(path, ".lock") { |
| 90 | stages = append(stages, path) |
| 91 | } |
| 92 | } |
| 93 | return stages |
| 94 | } |
| 95 | |
| 96 | func TestEnsureReclaimsStagesAfterProcessDeath(t *testing.T) { |
| 97 | base := t.TempDir() |
| 98 | t.Setenv(CacheEnvOverride, base) |
| 99 | stopOwner := startCacheTestProcess(t, "TestEnsureConcurrentProcesses", |
| 100 | []string{"LAST30DAYS_TEST_EXTRACT_ROLE=paused"}, filepath.Join(base, "ready")) |
| 101 | stages := cacheStagePaths(t, base) |
| 102 | if len(stages) != 1 { |
| 103 | t.Fatalf("paused extractor stages = %v, want one", stages) |
| 104 | } |
| 105 | stopOwner() |
| 106 | cacheDir, err := EnsureUserCache(newTestFS(), "v1") |
| 107 | if err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | mustReadFile(t, filepath.Join(cacheDir, "last30days.py"), "# last30days entry\n") |
| 111 | if _, err := os.Stat(stages[0]); !errors.Is(err, os.ErrNotExist) { |
| 112 | t.Fatalf("dead extractor's stage was not reclaimed: %v", err) |
| 113 | } |
| 114 | if _, err := os.Stat(stages[0] + ".lock"); !errors.Is(err, os.ErrNotExist) { |
| 115 | t.Fatalf("dead extractor's ownership file was not reclaimed: %v", err) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | func TestEnsurePreservesActiveStagesAndReclaimsThemAfterOwnerDeath(t *testing.T) { |
| 120 | base := t.TempDir() |
| 121 | t.Setenv(CacheEnvOverride, base) |
| 122 | stopOwner := startCacheTestProcess(t, "TestEnsureConcurrentProcesses", |
| 123 | []string{"LAST30DAYS_TEST_EXTRACT_ROLE=paused"}, filepath.Join(base, "ready")) |
| 124 | stages := cacheStagePaths(t, base) |
| 125 | if len(stages) != 1 { |
| 126 | t.Fatalf("paused extractor stages = %v, want one", stages) |
| 127 | } |
| 128 | cacheDir, err := EnsureUserCache(newTestFS(), "v1") |
| 129 | if err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | mustReadFile(t, filepath.Join(stages[0], "alpha.txt"), "alpha") |
| 133 | stopOwner() |
| 134 | if _, err := EnsureUserCache(newTestFS(), "v1"); err != nil { |
| 135 | t.Fatalf("reuse completed cache: %v", err) |
| 136 | } |
| 137 | if _, err := os.Stat(stages[0]); !errors.Is(err, os.ErrNotExist) { |
| 138 | t.Fatalf("cached reuse did not reclaim dead extractor's stage: %v", err) |
| 139 | } |
| 140 | mustReadFile(t, filepath.Join(cacheDir, "last30days.py"), "# last30days entry\n") |
| 141 | } |
| 142 | |
| 143 | func TestEnsurePreservesUnmarkedStagingDirectories(t *testing.T) { |
| 144 | base := t.TempDir() |
| 145 | stage := filepath.Join(cacheParentDir(base), "v1.tmp-unmarked") |
| 146 | if err := os.MkdirAll(stage, 0o700); err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | if err := os.WriteFile(filepath.Join(stage, "legacy.txt"), []byte(base), 0o600); err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | if _, err := Ensure(newTestFS(), base, "v1"); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | mustReadFile(t, filepath.Join(stage, "legacy.txt"), base) |
| 156 | } |
| 157 | |
| 158 | func TestEnsureReclaimsUnownedStageRegistration(t *testing.T) { |
| 159 | base := t.TempDir() |
| 160 | parent := cacheParentDir(base) |
| 161 | if err := os.MkdirAll(parent, 0o700); err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | owner := filepath.Join(parent, "v1.tmp-abandoned.lock") |
| 165 | if err := os.WriteFile(owner, nil, 0o600); err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | if _, err := Ensure(newTestFS(), base, "v1"); err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | if _, err := os.Stat(owner); !errors.Is(err, os.ErrNotExist) { |
| 172 | t.Fatalf("abandoned registration was not reclaimed: %v", err) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func TestEnsureHeldPublicationLockTimesOut(t *testing.T) { |
| 177 | base := t.TempDir() |
| 178 | t.Setenv(CacheEnvOverride, base) |
| 179 | stopOwner := startCacheLockOwner(t, filepath.Join(cacheParentDir(base), "v1.lock")) |
| 180 | const callers = 4 |
| 181 | done := make(chan error, callers) |
| 182 | started := time.Now() |
| 183 | for range callers { |
| 184 | go func() { |
| 185 | _, err := EnsureUserCache(newTestFS(), "v1") |
| 186 | done <- err |
| 187 | }() |
| 188 | } |
| 189 | deadline := time.After(7 * time.Second) |
| 190 | var results []error |
| 191 | for range callers { |
| 192 | select { |
| 193 | case err := <-done: |
| 194 | results = append(results, err) |
| 195 | case <-deadline: |
| 196 | stopOwner() |
| 197 | for len(results) < callers { |
| 198 | select { |
| 199 | case err := <-done: |
| 200 | results = append(results, err) |
| 201 | case <-time.After(5 * time.Second): |
| 202 | t.Fatal("extraction did not finish after lock owner was killed") |
| 203 | } |
| 204 | } |
| 205 | t.Fatal("held publication lock exceeded the seven-second test deadline") |
| 206 | } |
| 207 | } |
| 208 | for _, err := range results { |
| 209 | if !errors.Is(err, os.ErrDeadlineExceeded) { |
| 210 | t.Fatalf("held publication lock: got %v, want deadline error", err) |
| 211 | } |
| 212 | } |
| 213 | t.Logf("all %d held-lock callers returned deadline errors after %s", callers, time.Since(started)) |
| 214 | if _, err := os.Stat(filepath.Join(cacheParentDir(base), "v1")); !errors.Is(err, os.ErrNotExist) { |
| 215 | t.Fatalf("timed-out contender published a cache: %v", err) |
| 216 | } |
| 217 | staged, err := filepath.Glob(filepath.Join(cacheParentDir(base), "v1.tmp-*")) |
| 218 | if err != nil || len(staged) != 0 { |
| 219 | t.Fatalf("timed-out contender left staging directories: %v, %v", staged, err) |
| 220 | } |
| 221 | stopOwner() |
| 222 | cacheDir, err := EnsureUserCache(newTestFS(), "v1") |
| 223 | if err != nil { |
| 224 | t.Fatalf("retry after lock owner death: %v", err) |
| 225 | } |
| 226 | mustReadFile(t, filepath.Join(cacheDir, "last30days.py"), "# last30days entry\n") |
| 227 | } |
| 228 | |
| 229 | func TestCacheLockExcludesOtherProcessesAndReleasesOnOwnerDeath(t *testing.T) { |
| 230 | path := filepath.Join(t.TempDir(), "cache.lock") |
| 231 | stopOwner := startCacheLockOwner(t, path) |
| 232 | file, err := os.OpenFile(path, os.O_RDWR, 0o600) |
| 233 | if err != nil { |
| 234 | t.Fatal(err) |
| 235 | } |
| 236 | defer file.Close() |
| 237 | done := make(chan error, 1) |
| 238 | go func() { done <- lockCacheFile(file) }() |
| 239 | select { |
| 240 | case err := <-done: |
| 241 | t.Fatalf("contender returned while another process held the lock: %v", err) |
| 242 | case <-time.After(250 * time.Millisecond): |
| 243 | } |
| 244 | stopOwner() |
| 245 | select { |
| 246 | case err := <-done: |
| 247 | if err != nil { |
| 248 | t.Fatalf("acquire after owner death: %v", err) |
| 249 | } |
| 250 | case <-time.After(3 * time.Second): |
| 251 | t.Fatal("lock was not released after owner death") |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | func TestEnsurePublicationTimeoutCleansOwnedStage(t *testing.T) { |
| 256 | base := t.TempDir() |
| 257 | t.Setenv(CacheEnvOverride, base) |
| 258 | src := newTestFS() |
| 259 | src["zeta.txt"] = &fstest.MapFile{Data: []byte("zeta")} |
| 260 | done := make(chan error, 1) |
| 261 | finished := false |
| 262 | t.Cleanup(func() { |
| 263 | _ = os.WriteFile(filepath.Join(base, "release"), nil, 0o600) |
| 264 | if !finished { |
| 265 | select { |
| 266 | case <-done: |
| 267 | case <-time.After(7 * time.Second): |
| 268 | t.Error("extractor did not finish during cleanup") |
| 269 | } |
| 270 | } |
| 271 | }) |
| 272 | go func() { |
| 273 | _, err := EnsureUserCache(pausedExtractionFS{FS: src, base: base}, "v1") |
| 274 | done <- err |
| 275 | }() |
| 276 | deadline := time.Now().Add(10 * time.Second) |
| 277 | for { |
| 278 | if _, err := os.Stat(filepath.Join(base, "ready")); err == nil { |
| 279 | break |
| 280 | } |
| 281 | if time.Now().After(deadline) { |
| 282 | t.Fatal("extractor did not pause before publication") |
| 283 | } |
| 284 | time.Sleep(10 * time.Millisecond) |
| 285 | } |
| 286 | stages := cacheStagePaths(t, base) |
| 287 | if len(stages) != 1 { |
| 288 | t.Fatalf("paused extractor stages = %v, want one", stages) |
| 289 | } |
| 290 | startCacheLockOwner(t, filepath.Join(cacheParentDir(base), "v1.lock")) |
| 291 | if err := os.WriteFile(filepath.Join(base, "release"), nil, 0o600); err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | select { |
| 295 | case err := <-done: |
| 296 | finished = true |
| 297 | if !errors.Is(err, os.ErrDeadlineExceeded) { |
| 298 | t.Fatalf("publication contention: got %v, want deadline error", err) |
| 299 | } |
| 300 | case <-time.After(7 * time.Second): |
| 301 | t.Fatal("publication contention exceeded the seven-second test deadline") |
| 302 | } |
| 303 | if _, err := os.Stat(stages[0]); !errors.Is(err, os.ErrNotExist) { |
| 304 | t.Fatalf("timed-out extractor retained its stage: %v", err) |
| 305 | } |
| 306 | if _, err := os.Stat(stages[0] + ".lock"); !errors.Is(err, os.ErrNotExist) { |
| 307 | t.Fatalf("timed-out extractor retained its ownership file: %v", err) |
| 308 | } |
| 309 | } |
| 310 |