package appstore import ( "context" "crypto/rand" "encoding/hex" "errors" "fmt" "os" "path/filepath" "strings" "sync" "time" ) // ErrTaskRunning is returned when another installation is still running. var ErrTaskRunning = errors.New("已有安装任务在执行,请等待完成") const ( // Long apt/build runs can emit tens of thousands of lines. The UI only // needs the recent tail; keeping the full output in RAM multiplies across // finished tasks and is the largest avoidable allocation in the panel. maxTaskLogLines = 1000 maxTaskHistory = 30 ) // TaskView is the JSON payload polled by the UI. type TaskView struct { ID string `json:"id"` App string `json:"app"` AppName string `json:"app_name"` Version string `json:"version"` Action string `json:"action"` Status string `json:"status"` // running | ok | failed Log []string `json:"log"` Error string `json:"error,omitempty"` StartedAt int64 `json:"started_at"` EndedAt int64 `json:"ended_at,omitempty"` } type task struct { mu sync.Mutex view TaskView logPath string } func (t *task) append(line string) { line = strings.TrimRight(line, "\r\n") if line == "" { return } t.mu.Lock() defer t.mu.Unlock() // Keep the payload bounded; long builds can emit thousands of lines. if len(t.view.Log) < maxTaskLogLines { t.view.Log = append(t.view.Log, line) } else if len(t.view.Log) == maxTaskLogLines { t.view.Log = append(t.view.Log, "…(日志过长,后续输出已省略)") } } func (t *task) snapshot() TaskView { t.mu.Lock() defer t.mu.Unlock() out := t.view out.Log = append([]string(nil), t.view.Log...) return out } func (t *task) finish(err error) { t.mu.Lock() if err != nil { t.view.Status = "failed" t.view.Error = err.Error() if len(t.view.Log) < maxTaskLogLines { t.view.Log = append(t.view.Log, "安装失败: "+err.Error()) } } else { t.view.Status = "ok" t.view.Log = append(t.view.Log, "完成") } t.view.EndedAt = time.Now().Unix() logPath := t.logPath logText := strings.Join(t.view.Log, "\n") + "\n" t.mu.Unlock() if logPath != "" { _ = os.MkdirAll(filepath.Dir(logPath), 0o700) _ = os.WriteFile(logPath, []byte(logText), 0o600) } } type runnerFunc func(ctx context.Context, t *task, script string) error type taskManager struct { mu sync.Mutex tasks map[string]*task order []string running bool logDir string } func newTaskManager(logDir string) *taskManager { return &taskManager{tasks: map[string]*task{}, logDir: logDir} } func (m *taskManager) start(def AppDef, ver Version, action, script string, run runnerFunc) (TaskView, error) { m.mu.Lock() if m.running { m.mu.Unlock() return TaskView{}, ErrTaskRunning } id := randomID() t := &task{ view: TaskView{ ID: id, App: def.ID, AppName: def.Name, Version: ver.Version, Action: action, Status: "running", StartedAt: time.Now().Unix(), }, logPath: filepath.Join(m.logDir, id+".log"), } m.tasks[id] = t m.order = append(m.order, id) m.running = true if len(m.order) > maxTaskHistory { for _, old := range m.order[:len(m.order)-maxTaskHistory] { delete(m.tasks, old) } m.order = m.order[len(m.order)-maxTaskHistory:] } m.mu.Unlock() t.append(fmt.Sprintf("==> %s %s %s", action, def.Name, ver.Version)) ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute) go func() { defer cancel() defer func() { m.mu.Lock() m.running = false m.mu.Unlock() }() var err error func() { defer func() { if rec := recover(); rec != nil { err = fmt.Errorf("安装器内部错误: %v", rec) } }() err = run(ctx, t, script) }() t.finish(err) }() return t.snapshot(), nil } func (m *taskManager) get(id string) (TaskView, bool) { m.mu.Lock() t, ok := m.tasks[id] m.mu.Unlock() if !ok { return TaskView{}, false } return t.snapshot(), true } func (m *taskManager) list(limit int) []TaskView { if limit <= 0 || limit > 50 { limit = 20 } m.mu.Lock() ids := append([]string(nil), m.order...) tasks := make(map[string]*task, len(m.tasks)) for k, v := range m.tasks { tasks[k] = v } m.mu.Unlock() out := make([]TaskView, 0, limit) for i := len(ids) - 1; i >= 0 && len(out) < limit; i-- { if t, ok := tasks[ids[i]]; ok { out = append(out, t.snapshot()) } } return out } func randomID() string { b := make([]byte, 6) if _, err := rand.Read(b); err != nil { return fmt.Sprintf("%d", time.Now().UnixNano()) } return hex.EncodeToString(b) }