Route generic App and CLI code through lifecycle and driver models. Move native macOS detail, create, settings and legacy flows into explicit files, share progress and redaction through host, and enforce the boundary with a file-scoped architecture ratchet.
406 lines
11 KiB
Go
406 lines
11 KiB
Go
package app
|
|
|
|
// Long-running work (installer downloads, VM creation) is tracked as tasks and
|
|
// pushed to the frontend as "reims:task" events (docs/design-guidelines.md §7.3), so
|
|
// progress is a progress bar rather than one log line per percent.
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
|
)
|
|
|
|
const (
|
|
TaskRunning = "running"
|
|
TaskDone = "done"
|
|
TaskFailed = "failed"
|
|
TaskCanceled = "canceled"
|
|
|
|
TaskPhaseQueued = "queued"
|
|
TaskPhaseDownloading = "downloading"
|
|
)
|
|
|
|
// Task is one tracked job as the frontend sees it.
|
|
type Task struct {
|
|
ID string `json:"id"`
|
|
Kind string `json:"kind"` // "installer-download" | "recovery-download" | "vm-create" | "runtime-install" | "app-update"
|
|
Subject string `json:"subject"` // release ("26.7.3") or VM name
|
|
VM string `json:"vm,omitempty"`
|
|
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached
|
|
InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest")
|
|
InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active
|
|
Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8"
|
|
Done int64 `json:"done"`
|
|
Total int64 `json:"total"` // 0 when unknown
|
|
Percent float64 `json:"percent"` // -1 when unknown
|
|
Rate float64 `json:"rate"` // bytes per second, 0 when unknown
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
Result string `json:"result,omitempty"`
|
|
Cancelable bool `json:"cancelable"`
|
|
StartedAt int64 `json:"started_at"` // unix ms
|
|
UpdatedAt int64 `json:"updated_at"`
|
|
}
|
|
|
|
type taskEntry struct {
|
|
task Task
|
|
cancel context.CancelFunc
|
|
lastEmit time.Time
|
|
rate rateMeter
|
|
}
|
|
|
|
type taskManager struct {
|
|
mu sync.Mutex
|
|
seq int
|
|
tasks map[string]*taskEntry
|
|
emit func(Task)
|
|
}
|
|
|
|
// tasks is the process-wide manager; App methods below use it. Kept out of the
|
|
// App struct so this file stays self-contained.
|
|
var tasks = &taskManager{tasks: map[string]*taskEntry{}}
|
|
|
|
// emitInterval caps progress events per task; step and status changes always go out.
|
|
const emitInterval = 200 * time.Millisecond
|
|
|
|
// finishedTTL is how long finished tasks stay in GetTasks.
|
|
const finishedTTL = 10 * time.Minute
|
|
|
|
func (m *taskManager) start(kind, subject, vm string, cancel context.CancelFunc) string {
|
|
return m.startWithInstaller(kind, subject, vm, "", "", "", cancel)
|
|
}
|
|
|
|
func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, installerVersion, installerPhase string, cancel context.CancelFunc) string {
|
|
m.mu.Lock()
|
|
m.seq++
|
|
id := fmt.Sprintf("%s-%d", kind, m.seq)
|
|
now := time.Now().UnixMilli()
|
|
step := ""
|
|
if installerPhase == TaskPhaseQueued {
|
|
step = host.WaitingNote
|
|
}
|
|
e := &taskEntry{
|
|
task: Task{
|
|
ID: id, Kind: kind, Subject: subject, VM: vm,
|
|
InstallerKind: installerKind, InstallerVersion: installerVersion, InstallerPhase: installerPhase,
|
|
Step: step, Percent: -1, Status: TaskRunning, Cancelable: cancel != nil,
|
|
StartedAt: now, UpdatedAt: now,
|
|
},
|
|
cancel: cancel,
|
|
}
|
|
m.tasks[id] = e
|
|
m.pruneLocked()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
return id
|
|
}
|
|
|
|
// setInstaller attaches installer download metadata and phase to a running task.
|
|
func (m *taskManager) setInstaller(id, kind, version, phase string) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerKind = kind
|
|
e.task.InstallerVersion = version
|
|
e.task.InstallerPhase = phase
|
|
if phase == TaskPhaseQueued {
|
|
e.task.Step = host.WaitingNote
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
// clearInstallerPhase marks a task's installer download stage complete while
|
|
// keeping the task running for any remaining work (e.g. OpenCore / disk creation).
|
|
func (m *taskManager) clearInstallerPhase(id string) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
if e.task.InstallerPhase == "" {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerPhase = ""
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
// update applies an upstream progress report to the task.
|
|
func (m *taskManager) update(id string, u host.Update) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
force := false
|
|
switch u.Kind {
|
|
case host.KindNote:
|
|
if u.Message != host.WaitingNote || e.task.InstallerKind == "" {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
if e.task.InstallerPhase == TaskPhaseQueued && e.task.Step == u.Message {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerPhase = TaskPhaseQueued
|
|
e.task.Step = u.Message
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
force = true
|
|
case host.KindStep:
|
|
if e.task.InstallerPhase == TaskPhaseQueued {
|
|
e.task.InstallerPhase = TaskPhaseDownloading
|
|
force = true
|
|
}
|
|
force = force || e.task.Step != u.Message
|
|
e.task.Step = u.Message
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
case host.KindProgress:
|
|
if e.task.InstallerPhase == TaskPhaseQueued {
|
|
e.task.InstallerPhase = TaskPhaseDownloading
|
|
force = true
|
|
}
|
|
if u.Step != "" && u.Step != e.task.Step {
|
|
e.task.Step = u.Step
|
|
e.rate = rateMeter{}
|
|
force = true
|
|
}
|
|
e.task.Done, e.task.Total, e.task.Percent = u.Done, u.Total, u.Percent
|
|
e.task.Rate = e.rate.add(u.Done)
|
|
force = force || u.Percent >= 100
|
|
default:
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
if !force && time.Since(e.lastEmit) < emitInterval {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.lastEmit = time.Now()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
func (m *taskManager) finish(id string, result string, err error) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
switch {
|
|
case err == nil:
|
|
e.task.Status = TaskDone
|
|
e.task.Result = result
|
|
if e.task.Total > 0 {
|
|
e.task.Done, e.task.Percent = e.task.Total, 100
|
|
}
|
|
case errors.Is(err, context.Canceled) || strings.Contains(err.Error(), context.Canceled.Error()):
|
|
e.task.Status = TaskCanceled
|
|
default:
|
|
e.task.Status = TaskFailed
|
|
e.task.Error = err.Error()
|
|
}
|
|
e.task.InstallerPhase = ""
|
|
e.task.Cancelable = false
|
|
e.task.Rate = 0
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
e.cancel = nil
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
func (m *taskManager) cancel(id string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
e, ok := m.tasks[id]
|
|
if !ok {
|
|
return fmt.Errorf("no task %s", id)
|
|
}
|
|
if e.cancel == nil {
|
|
return fmt.Errorf("task %s can't be stopped", id)
|
|
}
|
|
e.cancel()
|
|
return nil
|
|
}
|
|
|
|
func (m *taskManager) cancelAll() {
|
|
m.mu.Lock()
|
|
cancels := make([]context.CancelFunc, 0, len(m.tasks))
|
|
for _, e := range m.tasks {
|
|
if e.cancel != nil {
|
|
cancels = append(cancels, e.cancel)
|
|
}
|
|
}
|
|
m.mu.Unlock()
|
|
for _, fn := range cancels {
|
|
fn()
|
|
}
|
|
}
|
|
|
|
func (m *taskManager) dismiss(id string) {
|
|
m.mu.Lock()
|
|
if e, ok := m.tasks[id]; ok && e.task.Status != TaskRunning {
|
|
delete(m.tasks, id)
|
|
}
|
|
m.mu.Unlock()
|
|
}
|
|
|
|
func (m *taskManager) list() []Task {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.pruneLocked()
|
|
out := make([]Task, 0, len(m.tasks))
|
|
for _, e := range m.tasks {
|
|
out = append(out, e.task)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].StartedAt < out[j].StartedAt })
|
|
return out
|
|
}
|
|
|
|
func (m *taskManager) pruneLocked() {
|
|
cutoff := time.Now().Add(-finishedTTL).UnixMilli()
|
|
for id, e := range m.tasks {
|
|
if e.task.Status != TaskRunning && e.task.UpdatedAt < cutoff {
|
|
delete(m.tasks, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (m *taskManager) send(t Task) {
|
|
m.mu.Lock()
|
|
emit := m.emit
|
|
m.mu.Unlock()
|
|
if emit != nil {
|
|
emit(t)
|
|
}
|
|
}
|
|
|
|
// rateMeter is bytes per second over a sliding window of about five seconds.
|
|
type rateMeter struct {
|
|
at []time.Time
|
|
done []int64
|
|
}
|
|
|
|
func (r *rateMeter) add(done int64) float64 {
|
|
now := time.Now()
|
|
r.at = append(r.at, now)
|
|
r.done = append(r.done, done)
|
|
for len(r.at) > 2 && now.Sub(r.at[0]) > 5*time.Second {
|
|
r.at, r.done = r.at[1:], r.done[1:]
|
|
}
|
|
dt := now.Sub(r.at[0]).Seconds()
|
|
if dt < 1 || done < r.done[0] {
|
|
return 0
|
|
}
|
|
return float64(done-r.done[0]) / dt
|
|
}
|
|
|
|
// ── App bindings ─────────────────────────────────────────────
|
|
|
|
func (a *App) taskEmitter() func(Task) {
|
|
return func(t Task) {
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:task", t)
|
|
}
|
|
}
|
|
}
|
|
|
|
// GetTasks lists running tasks and ones finished in the last few minutes.
|
|
func (a *App) GetTasks() []Task {
|
|
a.ensureTaskEmitter()
|
|
return tasks.list()
|
|
}
|
|
|
|
// CancelTask stops a cancelable task (a download pauses; rerunning resumes it).
|
|
func (a *App) CancelTask(id string) error { return tasks.cancel(id) }
|
|
|
|
// DismissTask forgets a finished task.
|
|
func (a *App) DismissTask(id string) { tasks.dismiss(id) }
|
|
|
|
func (a *App) ensureTaskEmitter() {
|
|
tasks.mu.Lock()
|
|
if tasks.emit == nil {
|
|
tasks.emit = a.taskEmitter()
|
|
}
|
|
tasks.mu.Unlock()
|
|
}
|
|
|
|
// ctlTaskWriter returns a writer for reims-ctl output that routes progress
|
|
// lines into a task and everything else to the log. reims-ctl prints its
|
|
// progress as "<step>: N% of <size>" (host.ParseCtlLine), sometimes behind
|
|
// a "<vm>: " prefix, which is dropped from the step. Each new step is logged
|
|
// once, so the log keeps the milestones without one line per percent.
|
|
// finish closes the task with the command's error.
|
|
func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) {
|
|
_, w, finish = a.ctlTaskWriterWithCancel(kind, vm, nil)
|
|
return w, finish
|
|
}
|
|
|
|
func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) {
|
|
a.ensureTaskEmitter()
|
|
id = tasks.start(kind, vm, vm, cancel)
|
|
lastStep := ""
|
|
lastLogAt := time.Now()
|
|
trim := func(s string) string { return strings.TrimPrefix(s, vm+": ") }
|
|
w = vmstart.LineWriter(func(line string) {
|
|
u, ok := host.ParseCtlLine(line)
|
|
if !ok {
|
|
return
|
|
}
|
|
if u.Kind == host.KindProgress {
|
|
u.Step = trim(u.Step)
|
|
if u.Step != lastStep {
|
|
lastStep = u.Step
|
|
lastLogAt = time.Now()
|
|
a.emitLog(vm, u.Step)
|
|
} else if time.Since(lastLogAt) >= 30*time.Second {
|
|
lastLogAt = time.Now()
|
|
if u.Total > 0 {
|
|
a.emitLog(vm, fmt.Sprintf("%s: %.0f%% (%.1f / %.1f MB)", u.Step, u.Percent, float64(u.Done)/1e6, float64(u.Total)/1e6))
|
|
} else if u.Done > 0 {
|
|
a.emitLog(vm, fmt.Sprintf("%s: %.1f MB", u.Step, float64(u.Done)/1e6))
|
|
}
|
|
}
|
|
tasks.update(id, u)
|
|
return
|
|
}
|
|
a.emitLog(vm, line)
|
|
step := trim(u.Message)
|
|
lastStep = step
|
|
lastLogAt = time.Now()
|
|
tasks.update(id, host.Update{Kind: host.KindStep, Message: step, Percent: -1})
|
|
})
|
|
return id, w, func(err error) { tasks.finish(id, "", err) }
|
|
}
|