package main import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "time" ) type Progress struct { Phase string `json:"phase"` Message string `json:"message"` Path string `json:"path"` Current int64 `json:"current"` Total int64 `json:"total"` Percent int `json:"percent"` } func (s *Server) persistBuild(b *Build) error { dir := filepath.Join(s.root, "artifacts", b.ID) if e := os.MkdirAll(dir, 0700); e != nil { return e } data, e := json.Marshal(b) if e != nil { return e } target := filepath.Join(dir, "build.json") if e = os.WriteFile(target+".tmp", data, 0600); e != nil { return e } if e = os.Rename(target+".tmp", target); e == nil { b.lastPersist = time.Now() } return e } func (s *Server) finishFailed(b *Build, e error) { s.mu.Lock() defer s.mu.Unlock() b.Status = "failed" if b.cancelled { b.Status = "cancelled" } b.Logs = append(b.Logs, e.Error()) b.Progress.Phase = "finished" s.projects[b.Project].Busy = false _ = s.persistBuild(b) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) } func (s *Server) recoverBuilds() { for p, pr := range s.projects { pr.Busy = false marker, e := os.ReadFile(filepath.Join(s.root, "projects", p, "active-build")) if e == nil { pr.Busy = true bid := strings.TrimSpace(string(marker)) if safeID.MatchString(bid) && s.builds[bid] == nil { s.builds[bid] = &Build{ID: bid, Project: p, Revision: pr.Revision, Status: "running", Logs: []string{}, Artifacts: []Artifact{}} } } } for _, b := range s.builds { if b.Status == "running" || b.Status == "queued" { b.Status = "interrupted" b.Progress.Phase = "interrupted" b.Logs = append(b.Logs, "服务曾重启,构建已中断。若工作区仍锁定,管理员需确认残留 Gradle 进程已停止,再移除 active-build 并重启服务。") if e := s.persistBuild(b); e != nil { fmt.Println("build recovery persistence failed:", e) } } } }