| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "reasonix/desktop/internal/workspacestate" |
| 11 | "reasonix/internal/session" |
| 12 | ) |
| 13 | |
| 14 | // Measures the existing runtime-lock scope as well as elapsed deletion time. |
| 15 | // All content and registry writes are confined to the benchmark's temporary root. |
| 16 | func BenchmarkPurgeRuntimeLock(b *testing.B) { |
| 17 | for _, count := range []int{1, 8} { |
| 18 | b.Run(fmt.Sprintf("sessions-%d", count), func(b *testing.B) { |
| 19 | b.StopTimer() |
| 20 | root := b.TempDir() |
| 21 | var held time.Duration |
| 22 | for n := range b.N { |
| 23 | a := NewApp() |
| 24 | a.ctx = b.Context() |
| 25 | a.desktopSessions.root = filepath.Join(root, fmt.Sprint(n), "sessions") |
| 26 | store := workspacestate.NewStore(filepath.Join(root, fmt.Sprint(n), "registry.json")) |
| 27 | a.desktopSessions.workspaceState = store |
| 28 | if err := store.EnsureWorkspace(b.Context(), workspacestate.Workspace{ID: workspacestate.GlobalWorkspaceID, Visible: true}); err != nil { |
| 29 | b.Fatal(err) |
| 30 | } |
| 31 | refs := make([]session.SessionRef, count) |
| 32 | for i := range refs { |
| 33 | id := fmt.Sprintf("benchmark-%d", i) |
| 34 | refs[i] = session.SessionRef{HostID: localDesktopHostID, SessionID: id} |
| 35 | dir := filepath.Join(a.desktopSessions.root, id) |
| 36 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 37 | b.Fatal(err) |
| 38 | } |
| 39 | for j := range 128 / count { |
| 40 | if err := os.WriteFile(filepath.Join(dir, fmt.Sprint(j)), make([]byte, 4096), 0600); err != nil { |
| 41 | b.Fatal(err) |
| 42 | } |
| 43 | } |
| 44 | if err := store.AttachSession(b.Context(), "", workspacestate.GlobalWorkspaceID, id, ""); err != nil { |
| 45 | b.Fatal(err) |
| 46 | } |
| 47 | if err := store.ArchiveSession(b.Context(), id); err != nil { |
| 48 | b.Fatal(err) |
| 49 | } |
| 50 | } |
| 51 | state, err := store.Load(b.Context()) |
| 52 | if err != nil { |
| 53 | b.Fatal(err) |
| 54 | } |
| 55 | // Keep service construction outside the measured runtime lock. |
| 56 | a.desktopSessionService("") |
| 57 | b.StartTimer() |
| 58 | for _, ref := range refs { |
| 59 | release := a.lockRuntimeMutation("benchmark purge") |
| 60 | start := time.Now() |
| 61 | err := a.purgeCanonicalSession(b.Context(), ref, state.Generation) |
| 62 | held += time.Since(start) |
| 63 | release() |
| 64 | if err != nil { |
| 65 | b.Fatal(err) |
| 66 | } |
| 67 | } |
| 68 | b.StopTimer() |
| 69 | a.closeSessionServices() |
| 70 | } |
| 71 | b.ReportMetric(float64(held.Nanoseconds())/float64(b.N), "lock-ns/op") |
| 72 | }) |
| 73 | } |
| 74 | } |
| 75 |