80 lines
2.2 KiB
Go
80 lines
2.2 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/update"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type RequestRestartUseCase struct {
|
|
jobs update.JobStore
|
|
helper update.HelperDetector
|
|
results update.ResultStore
|
|
requests update.RestartRequestStore
|
|
status updateStatusBuilder
|
|
now func() time.Time
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func NewRequestRestartUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, results update.ResultStore, requests update.RestartRequestStore, currentVersion string, now func() time.Time) *RequestRestartUseCase {
|
|
return &RequestRestartUseCase{
|
|
jobs: jobs,
|
|
helper: helper,
|
|
results: results,
|
|
requests: requests,
|
|
status: updateStatusBuilder{store: store, jobs: jobs, results: results, requests: requests, currentVersion: currentVersion, now: now},
|
|
now: now,
|
|
}
|
|
}
|
|
|
|
func (r *RequestRestartUseCase) Request(userId uint32, kind string) (update.UpdateStatus, error) {
|
|
if !r.helper.Installed() {
|
|
return update.UpdateStatus{}, update.ErrNotPrepared
|
|
}
|
|
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
|
|
current := r.status.build(true)
|
|
if err := refuseWhileBusy(current); err != nil {
|
|
return update.UpdateStatus{}, err
|
|
}
|
|
request, err := r.requestFor(kind, userId)
|
|
if err != nil {
|
|
return update.UpdateStatus{}, err
|
|
}
|
|
if err := r.results.Delete(); err != nil {
|
|
return update.UpdateStatus{}, err
|
|
}
|
|
if err := r.requests.Write(request); err != nil {
|
|
return update.UpdateStatus{}, err
|
|
}
|
|
return r.status.build(true), nil
|
|
}
|
|
|
|
func refuseWhileBusy(status update.UpdateStatus) error {
|
|
switch status.State {
|
|
case update.StateDownloading, update.StateVerifying:
|
|
return update.ErrJobInProgress
|
|
case update.StateRestarting:
|
|
return update.ErrRestartPending
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *RequestRestartUseCase) requestFor(kind string, userId uint32) (update.RestartRequest, error) {
|
|
request := update.RestartRequest{
|
|
Kind: update.RestartKindRestart,
|
|
RequestedAt: r.now().UTC(),
|
|
RequestedBy: userId,
|
|
}
|
|
if job, found := r.jobs.Load(); found && job.State == update.StateReady {
|
|
request.Kind = update.RestartKindUpdate
|
|
request.Tag = job.Tag
|
|
}
|
|
if kind != "" && kind != request.Kind {
|
|
return update.RestartRequest{}, update.ErrRestartKindMismatch
|
|
}
|
|
return request, nil
|
|
}
|