package app import ( "context" "errors" "sync/atomic" "testing" "time" "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/installer" ) func newTestCoordinator(t *testing.T) { t.Helper() old := installerDownloads installerDownloads = newInstallerCoordinator() t.Cleanup(func() { installerDownloads = old }) } func TestTaskInstallerPhaseTransitions(t *testing.T) { sent := newTestTasks(t) id := tasks.startWithInstaller("installer-download", "15.8.3", "", "offline", "15.8.3", TaskPhaseQueued, func() {}) if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseQueued || got.Step != installer.WaitingNote || got.InstallerKind != "offline" || got.InstallerVersion != "15.8.3" { t.Fatalf("initial queued task = %+v", got) } tasks.update(id, installer.Update{Kind: installer.KindStep, Message: "downloading macOS 15.8.3", Percent: -1}) if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseDownloading || got.Step != "downloading macOS 15.8.3" { t.Fatalf("after step = %+v", got) } tasks.update(id, installer.Update{Kind: installer.KindProgress, Done: 50, Total: 100, Percent: 50}) tasks.update(id, installer.Update{Kind: installer.KindNote, Message: installer.WaitingNote, Percent: -1}) if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseQueued || got.Percent != -1 || got.Done != 0 { t.Fatalf("after waiting note = %+v", got) } tasks.update(id, installer.Update{Kind: installer.KindProgress, Done: 60, Total: 100, Percent: 60}) if got := (*sent)[len(*sent)-1]; got.InstallerPhase != TaskPhaseDownloading || got.Percent != 60 { t.Fatalf("resumed progress = %+v", got) } tasks.clearInstallerPhase(id) if got := (*sent)[len(*sent)-1]; got.Status != TaskRunning || got.InstallerPhase != "" || got.Percent != -1 { t.Fatalf("after clearInstallerPhase = %+v", got) } tasks.finish(id, "", nil) if got := (*sent)[len(*sent)-1]; got.Status != TaskDone || got.InstallerPhase != "" { t.Fatalf("final task = %+v", got) } } func TestInstallerCoordinatorForwardDedupAndQueueing(t *testing.T) { newTestTasks(t) newTestCoordinator(t) vmTaskID := tasks.start("vm-create", "macos-tahoe", "macos-tahoe", func() {}) run1, owned1 := installerDownloads.acquireOrJoin("offline", "26.7.3", vmTaskID, "vm-create") if !owned1 || run1.currentPhase() != TaskPhaseDownloading { t.Fatalf("run1 owned=%v phase=%q", owned1, run1.currentPhase()) } // Duplicate DownloadInstaller for the same version returns the vm-create task ID. startedDup := false _, dupID, dupOwned := installerDownloads.reserveOrFind("offline", "26.7.3", "installer-download", func(string) string { startedDup = true return "should-not-create" }) if dupOwned || startedDup || dupID != vmTaskID { t.Fatalf("dup owned=%v started=%v id=%q want %q", dupOwned, startedDup, dupID, vmTaskID) } // A different version starts queued because another download is already active. var secondPhase string run2, id2, owned2 := installerDownloads.reserveOrFind("offline", "15.8.3", "installer-download", func(phase string) string { secondPhase = phase return tasks.startWithInstaller("installer-download", "15.8.3", "", "offline", "15.8.3", phase, func() {}) }) if !owned2 || secondPhase != TaskPhaseQueued || run2.currentPhase() != TaskPhaseQueued || id2 == "" { t.Fatalf("second run owned=%v phase=%q id=%q", owned2, secondPhase, id2) } installerDownloads.complete(run1, &installer.Result{Version: "26.7.3"}, nil) installerDownloads.complete(run2, &installer.Result{Version: "15.8.3"}, nil) } func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) { sent := newTestTasks(t) newTestCoordinator(t) a := &App{} // Standalone manual download is already running at 40%. dlID := tasks.startWithInstaller("installer-download", "26.7.3", "", "offline", "26.7.3", TaskPhaseDownloading, func() {}) dlRun, owned := installerDownloads.acquireOrJoin("offline", "26.7.3", dlID, "installer-download") if !owned { t.Fatal("expected standalone download to own run") } u40 := installer.Update{Kind: installer.KindProgress, Step: "downloading macOS Tahoe 26.7.3", Done: 400, Total: 1000, Percent: 40} tasks.update(dlID, u40) dlRun.publish(u40) // VM creation joins the in-progress download and mirrors 40% immediately. vmCtx, vmCancel := context.WithCancel(context.Background()) vmID := tasks.start("vm-create", "macos-tahoe", "macos-tahoe", vmCancel) var downloadCalls atomic.Int32 done := make(chan error, 1) go func() { _, err := a.ensureInstallerForTask(vmCtx, vmID, "vm-create", "macos-tahoe", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) { downloadCalls.Add(1) return &installer.Result{}, nil }) done <- err }() // Wait until vm-create mirrors progress. deadline := time.Now().Add(2 * time.Second) mirrored := false for time.Now().Before(deadline) { for _, task := range tasks.list() { if task.ID == vmID && task.InstallerVersion == "26.7.3" && task.Percent == 40 { mirrored = true break } } if mirrored { break } time.Sleep(10 * time.Millisecond) } if !mirrored { t.Fatalf("vm-create did not mirror in-progress download: %+v", *sent) } // Canceling vm-create stops only the VM creation; the standalone download remains active. vmCancel() select { case err := <-done: if !errors.Is(err, context.Canceled) { t.Fatalf("vm-create err = %v, want context.Canceled", err) } case <-time.After(2 * time.Second): t.Fatal("vm-create did not exit after cancel") } if downloadCalls.Load() != 0 { t.Fatalf("joiner invoked download func %d times", downloadCalls.Load()) } if !installerDownloads.hasActive("offline", "26.7.3") { t.Fatal("standalone download was unexpectedly cleared when vm-create canceled") } // A second VM creation joins and receives completion cleanly when standalone finishes. vm2ID := tasks.start("vm-create", "macos-tahoe-2", "macos-tahoe-2", func() {}) done2 := make(chan error, 1) go func() { res, err := a.ensureInstallerForTask(context.Background(), vm2ID, "vm-create", "macos-tahoe-2", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) { downloadCalls.Add(1) return nil, errors.New("should not download directly") }) if err == nil && (res == nil || res.Image != "C:/ok.img") { err = errors.New("missing result image") } done2 <- err }() time.Sleep(30 * time.Millisecond) installerDownloads.complete(dlRun, &installer.Result{Version: "26.7.3", Image: "C:/ok.img"}, nil) select { case err := <-done2: if err != nil { t.Fatalf("vm2 err = %v", err) } case <-time.After(2 * time.Second): t.Fatal("vm2 did not finish after standalone completed") } for _, task := range tasks.list() { if task.ID == vm2ID && task.InstallerPhase != "" { t.Fatalf("vm2 installer_phase was not cleared: %+v", task) } } } func TestInstallerCoordinatorPauseStandaloneCancelsWaitingVMAndTakeoverOnVMCancel(t *testing.T) { newTestTasks(t) newTestCoordinator(t) a := &App{} // Case 1: Pausing a standalone download cancels a VM creation waiting on it. dlID := tasks.startWithInstaller("installer-download", "26.7.3", "", "offline", "26.7.3", TaskPhaseDownloading, func() {}) dlRun, _ := installerDownloads.acquireOrJoin("offline", "26.7.3", dlID, "installer-download") vm1ID := tasks.start("vm-create", "vm-1", "vm-1", func() {}) done1 := make(chan error, 1) go func() { _, err := a.ensureInstallerForTask(context.Background(), vm1ID, "vm-create", "vm-1", "offline", "26.7.3", func(context.Context, func(installer.Update)) (*installer.Result, error) { return nil, errors.New("must not restart after explicit pause") }) done1 <- err }() time.Sleep(30 * time.Millisecond) installerDownloads.complete(dlRun, nil, context.Canceled) if err := <-done1; !errors.Is(err, context.Canceled) { t.Fatalf("waiting vm err = %v, want context.Canceled", err) } // Case 2: If VM A owns the download and is canceled, waiting VM B takes over. vmAID := tasks.start("vm-create", "vm-a", "vm-a", func() {}) vmARun, _ := installerDownloads.acquireOrJoin("offline", "26.7.3", vmAID, "vm-create") vmBID := tasks.start("vm-create", "vm-b", "vm-b", func() {}) var takeoverCalls atomic.Int32 doneB := make(chan error, 1) go func() { res, err := a.ensureInstallerForTask(context.Background(), vmBID, "vm-create", "vm-b", "offline", "26.7.3", func(ctx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) { takeoverCalls.Add(1) onUpdate(installer.Update{Kind: installer.KindProgress, Done: 100, Total: 100, Percent: 100}) return &installer.Result{Version: "26.7.3", Image: "C:/taken.img"}, nil }) if err == nil && (res == nil || res.Image != "C:/taken.img") { err = errors.New("missing takeover result") } doneB <- err }() time.Sleep(30 * time.Millisecond) installerDownloads.complete(vmARun, nil, context.Canceled) select { case err := <-doneB: if err != nil { t.Fatalf("takeover err = %v", err) } case <-time.After(2 * time.Second): t.Fatal("vm-b did not take over after vm-a canceled") } if takeoverCalls.Load() != 1 { t.Fatalf("takeover calls = %d, want 1", takeoverCalls.Load()) } } func TestHasCompleteCachedInstallerAndCreateTarget(t *testing.T) { items := []installer.Cached{ {Kind: "offline", Title: "macOS Tahoe", Version: "26.7.3", Partial: true}, {Kind: "offline", Title: "macOS Sequoia", Version: "15.8.3", Partial: false}, {Kind: "online", Title: "macOS Tahoe", Partial: false}, } if hasCompleteCachedInstaller(items, "offline", "26.7.3") { t.Fatal("partial offline installer must not count as complete") } if !hasCompleteCachedInstaller(items, "offline", "15.8.3") { t.Fatal("complete offline installer not recognized") } if hasCompleteCachedInstaller(items, "offline", "latest") { t.Fatal("symbolic latest must not bypass reims-util") } if !hasCompleteCachedInstaller(items, "online", "tahoe") { t.Fatal("complete online installer for tahoe not recognized") } if hasCompleteCachedInstaller(items, "online", "latest") { t.Fatal("online latest must not skip resolution") } if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "offline", MacOS: "26.7.3", Offline: true}); k != "offline" || v != "26.7.3" { t.Fatalf("offline target = %q, %q", k, v) } if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "apple", MacOS: "tahoe"}); k != "online" || v != "tahoe" { t.Fatalf("apple target = %q, %q", k, v) } if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "installer", Installer: "C:/a.img", MacOS: "26.7.3"}); k != "" || v != "" { t.Fatalf("local installer should not trigger download: %q, %q", k, v) } if k, v := createInstallerTarget(reims.CreateOpts{SourceMode: "disk", Disk: "C:/d.qcow2", MacOS: "26.7.3"}); k != "" || v != "" { t.Fatalf("existing disk should not trigger download: %q, %q", k, v) } }