package explain import ( "sync" "time" ) // A job's states. Idle means nothing has run since the server started. const ( Idle = "idle" Running = "running" Done = "done" Failed = "error" ) // Status is what the page polls for. type Status struct { State string `json:"state"` Error string `json:"error,omitempty"` Started *time.Time `json:"started,omitempty"` Finished *time.Time `json:"finished,omitempty"` // Result is a finished StartWith job's answer. Result any `json:"result,omitempty"` } // Jobs runs at most one explanation per problem at a time. An explanation // takes a minute or more, longer than nginx waits for a response, so the // request only starts it and the page polls. State is in memory: a restart // mid-job loses the job, and nothing is committed until it finishes. type Jobs struct { mu sync.Mutex m map[string]*Status } // Start runs fn in the background unless a job for name is running, and // reports whether it started. fn's error is shown to the admin, so it must // be a message meant for them. func (j *Jobs) Start(name string, fn func() error) bool { return j.StartWith(name, func() (any, error) { return nil, fn() }) } // StartWith is Start for a job whose answer is kept here rather than // committed: a done job's Status carries it until the next job for name // starts, or the server restarts. func (j *Jobs) StartWith(name string, fn func() (any, error)) bool { j.mu.Lock() defer j.mu.Unlock() if j.m == nil { j.m = map[string]*Status{} } if s := j.m[name]; s != nil && s.State == Running { return false } now := time.Now() j.m[name] = &Status{State: Running, Started: &now} go func() { res, err := fn() j.mu.Lock() defer j.mu.Unlock() end := time.Now() s := &Status{State: Done, Started: &now, Finished: &end, Result: res} if err != nil { s.State, s.Error, s.Result = Failed, err.Error(), nil } j.m[name] = s }() return true } // Get is name's latest job. func (j *Jobs) Get(name string) Status { j.mu.Lock() defer j.mu.Unlock() if s := j.m[name]; s != nil { return *s } return Status{State: Idle} }