feat: 完善远程构建恢复、工程同步与变体选择

增加持久化构建记录、历史 APK 恢复、断点下载、Gradle 缓存复用、系统代理与按工程选择服务端 JDK。

支持已有工程目录、Git 状态检查、原生忽略规则和文本换行等价比较,修复干净检出与历史同步快照不一致时的误拦截。

优化插件设备可选构建、侧栏滚动、左右日志布局、时间显示和构建变体快速选择,并补充部署与协议文档。

验证:17 项 Go 测试、22 项插件测试及 HTTP/HTTPS 两条端到端测试通过;Linux/macOS 服务端交叉编译通过。
This commit is contained in:
tongtong committed 2026-11-25 02:10:52 +08:00
1 parent 2203afde3c
commit 2cb70beb69
44 files changed
+3310 -236

No files matched your search

+207 -49
View File
@@ -22,6 +22,7 @@ import (
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
@@ -30,12 +31,14 @@ import (
)
type File struct {
Hash string `json:"hash"`
Data *string `json:"data,omitempty"`
Hash string `json:"hash"`
TextHash string `json:"textHash,omitempty"`
Data *string `json:"data,omitempty"`
}
type SyncRequest struct {
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Git *GitSnapshot `json:"git,omitempty"`
}
type Artifact struct {
Name string `json:"name"`
@@ -43,27 +46,37 @@ type Artifact struct {
Size int64 `json:"size"`
}
type Build struct {
ID string `json:"id"`
Project string `json:"project"`
Revision string `json:"revision"`
Task string `json:"task"`
Status string `json:"status"`
Logs []string `json:"logs"`
Artifacts []Artifact `json:"artifacts"`
cmd *exec.Cmd
cancelled bool
JavaHome string `json:"javaHome,omitempty"`
RequestID string `json:"clientRequestId,omitempty"`
CreatedAt int64 `json:"createdAt"`
Progress Progress `json:"progress"`
Environment map[string]string `json:"environment,omitempty"`
lastPersist time.Time
ID string `json:"id"`
Project string `json:"project"`
Revision string `json:"revision"`
Task string `json:"task"`
Status string `json:"status"`
Logs []string `json:"logs"`
Artifacts []Artifact `json:"artifacts"`
cmd *exec.Cmd
cancelled bool
}
type Project struct {
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Busy bool `json:"-"`
WorkspacePath string `json:"workspacePath,omitempty"`
Git *GitSnapshot `json:"git,omitempty"`
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Busy bool `json:"busy"`
}
type Server struct {
mu sync.Mutex
root, token string
tasks map[string]bool
projects map[string]*Project
builds map[string]*Build
mu sync.Mutex
root, token string
tasks map[string]bool
projects map[string]*Project
builds map[string]*Build
workspaceRoot string
environmentFile string
}
var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`)
@@ -91,7 +104,7 @@ func validPath(p string) bool {
}
}
for _, part := range strings.Split(p, "/") {
if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" {
if reservedSource(part) {
return false
}
}
@@ -102,6 +115,9 @@ func noLinks(root string) error {
if e != nil {
return e
}
if d.IsDir() && p != root && reservedSource(filepath.Base(p)) {
return filepath.SkipDir
}
if d.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("symlink forbidden: %s", p)
}
@@ -118,7 +134,12 @@ func decode(w http.ResponseWriter, r *http.Request, v any) error {
d.DisallowUnknownFields()
return d.Decode(v)
}
func (s *Server) work(p string) string { return filepath.Join(s.root, "projects", p, "work") }
func (s *Server) work(p string) string {
if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" {
return pr.WorkspacePath
}
return filepath.Join(s.root, "projects", p, "work")
}
func (s *Server) save(p string) error {
b, e := json.Marshal(s.projects[p])
if e != nil {
@@ -144,7 +165,24 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
fail := func(e error) { http.Error(w, e.Error(), 400) }
if r.URL.Path == "/api/v1/health" {
jsonOut(w, map[string]any{"version": "0.1.1", "os": runtime.GOOS, "sync": "http-manifest"})
jsonOut(w, map[string]any{"version": "0.4.1", "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true})
return
}
if r.URL.Path == "/api/v1/environment" && r.Method == "GET" {
cfg, e := s.buildEnvironment()
if e != nil {
fail(e)
return
}
jsonOut(w, cfg.summary())
return
}
if r.URL.Path == "/api/v1/jdks" && r.Method == "GET" {
s.jdks(w, r)
return
}
if r.URL.Path == "/api/v1/directories" && r.Method == "GET" {
s.browseDirectories(w, r)
return
}
if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" {
@@ -152,20 +190,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if parts[2] == "projects" {
if len(parts) == 3 && r.Method == "POST" {
p := id()
if e := os.MkdirAll(s.work(p), 0700); e != nil {
fail(e)
return
}
s.projects[p] = &Project{Files: map[string]File{}}
if e := s.save(p); e != nil {
fail(e)
return
}
jsonOut(w, map[string]string{"id": p})
if len(parts) == 4 && parts[3] == "check" && r.Method == "POST" {
s.checkWorkspace(w, r)
return
}
if len(parts) == 3 && r.Method == "POST" {
s.createProject(w, r)
return
}
if len(parts) != 5 || !safeID.MatchString(parts[3]) {
http.NotFound(w, r)
return
@@ -176,8 +209,28 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
if pr.WorkspacePath != "" {
if _, e := s.validateWorkspace(pr.WorkspacePath); e != nil {
fail(e)
return
}
}
if parts[4] == "manifest" && r.Method == "GET" {
jsonOut(w, pr)
jsonOut(w, s.manifest(p))
return
}
if parts[4] == "builds" && r.Method == "GET" {
items := []*Build{}
for _, b := range s.builds {
if b.Project == p && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) {
items = append(items, b)
}
}
sort.Slice(items, func(i, j int) bool { return items[i].CreatedAt > items[j].CreatedAt })
if len(items) > 50 {
items = items[:50]
}
jsonOut(w, map[string]any{"builds": items})
return
}
if parts[4] == "sync" && r.Method == "POST" {
@@ -194,6 +247,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(errors.New("revision and files required"))
return
}
if e := s.checkGit(p, req.Git); e != nil {
http.Error(w, e.Error(), 409)
return
}
if e := noLinks(s.work(p)); e != nil {
fail(e)
return
@@ -242,6 +299,11 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
}
previousFiles, baseErr := s.syncBase(p)
if baseErr != nil {
fail(baseErr)
return
}
// Validate the entire request before touching the working tree. Invalidate first:
// an interrupted commit must never permit building a mixed source revision.
pr.Revision = ""
@@ -249,8 +311,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(e)
return
}
for path := range pr.Files {
if _, ok := req.Files[path]; !ok {
for path := range previousFiles {
if _, ok := req.Files[path]; !ok && validPath(path) {
if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) {
fail(e)
return
@@ -270,9 +332,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
pr.Files = map[string]File{}
for path, f := range req.Files {
pr.Files[path] = File{Hash: f.Hash}
actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e != nil || actual.Hash != f.Hash {
fail(fmt.Errorf("source changed during sync: %s", path))
return
}
pr.Files[path] = actual
}
pr.Revision = req.Revision
pr.Git = req.Git
if e := s.save(p); e != nil {
pr.Revision = ""
fail(e)
@@ -283,8 +351,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if parts[4] == "builds" && r.Method == "POST" {
var req struct {
Revision string `json:"revision"`
Task string `json:"task"`
Revision string `json:"revision"`
Task string `json:"task"`
RequestID string `json:"clientRequestId"`
JavaHome string `json:"javaHome,omitempty"`
}
if e := decode(w, r, &req); e != nil {
fail(e)
@@ -294,11 +364,51 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(errors.New("task not allowed"))
return
}
if req.RequestID != "" {
if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`).MatchString(req.RequestID) {
fail(errors.New("invalid clientRequestId"))
return
}
for _, old := range s.builds {
if old.Project == p && old.RequestID == req.RequestID {
if old.Task != req.Task || old.Revision != req.Revision || old.JavaHome != req.JavaHome {
http.Error(w, "request ID already used with different parameters", 409)
return
}
jsonOut(w, old)
return
}
}
}
if pr.Busy || req.Revision == "" || pr.Revision != req.Revision {
http.Error(w, "busy or revision mismatch", 409)
return
}
b := &Build{ID: id(), Project: p, Revision: req.Revision, Task: req.Task, Status: "queued", Logs: []string{}, Artifacts: []Artifact{}}
if pr.WorkspacePath != "" {
if e := s.checkGit(p, pr.Git); e != nil {
http.Error(w, e.Error(), 409)
return
}
actual, e := sourceInventory(s.work(p))
if e != nil {
fail(e)
return
}
if !sameSourceHashes(pr.Files, actual) {
http.Error(w, "source changed after sync; sync again", 409)
return
}
}
javaHome, jdkErr := s.selectedJDK(req.JavaHome)
if jdkErr != nil {
fail(jdkErr)
return
}
b := &Build{JavaHome: javaHome, ID: id(), Project: p, Revision: req.Revision, Task: req.Task, RequestID: req.RequestID, CreatedAt: time.Now().UnixMilli(), Status: "queued", Logs: []string{}, Artifacts: []Artifact{}}
if e := s.persistBuild(b); e != nil {
fail(e)
return
}
if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil {
fail(e)
return
@@ -406,6 +516,9 @@ func (w buildWriter) Write(p []byte) (int, error) {
w.s.mu.Lock()
defer w.s.mu.Unlock()
w.b.Logs = append(w.b.Logs, string(p))
if time.Since(w.b.lastPersist) > time.Second {
_ = w.s.persistBuild(w.b)
}
return len(p), nil
}
func (s *Server) run(b *Build) {
@@ -413,11 +526,14 @@ func (s *Server) run(b *Build) {
if b.cancelled {
b.Status = "cancelled"
s.projects[b.Project].Busy = false
_ = s.persistBuild(b)
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
s.mu.Unlock()
return
}
b.Status = "running"
b.Progress = Progress{Phase: "preparing", Message: "正在检测工具版本、缓存及系统代理", Percent: -1}
_ = s.persistBuild(b)
s.mu.Unlock()
work := s.work(b.Project)
// Remove old APKs only. Retain compilation caches and all other Gradle outputs.
@@ -434,8 +550,31 @@ func (s *Server) run(b *Build) {
})
}
if err == nil {
cmd := gradleCommand(work, b.Task)
cfg, configErr := s.buildEnvironment()
if configErr != nil {
s.finishFailed(b, configErr)
return
}
if b.JavaHome != "" {
cfg.JavaHome = b.JavaHome
}
cmd, info, prepErr := s.prepareCommand(work, b.Task, cfg)
if prepErr != nil {
s.finishFailed(b, prepErr)
return
}
s.mu.Lock()
b.Environment = info
b.Progress = Progress{Phase: "building", Message: "执行项目 Wrapper,准备 Gradle 分发包", Path: info["distributionFile"], Percent: -1}
if info["execution"] == "installed-gradle" {
b.Progress.Message = "已复用 Gradle " + info["requestedGradleVersion"] + ";正在构建"
b.Progress.Path = info["executable"]
}
_ = s.persistBuild(b)
s.mu.Unlock()
buildWriter{s, b}.Write([]byte("构建环境: " + mustJSON(info) + "\n"))
cmd.Dir = work
cmd.Env = cfg.environ()
cmd.Stdout = buildWriter{s, b}
cmd.Stderr = cmd.Stdout
s.mu.Lock()
@@ -447,6 +586,8 @@ func (s *Server) run(b *Build) {
}
s.mu.Unlock()
if err == nil {
stopProgress := make(chan struct{})
go s.monitorDistribution(b, work, cfg, stopProgress)
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
@@ -458,6 +599,7 @@ func (s *Server) run(b *Build) {
err = errors.New("build timeout")
}
}
close(stopProgress)
}
}
artifacts := []Artifact{}
@@ -488,6 +630,7 @@ func (s *Server) run(b *Build) {
s.mu.Lock()
defer s.mu.Unlock()
b.cmd = nil
b.Progress.Phase = "finished"
b.Artifacts = artifacts
b.Status = "success"
if len(artifacts) == 0 && err == nil {
@@ -501,10 +644,7 @@ func (s *Server) run(b *Build) {
b.Status = "cancelled"
}
s.projects[b.Project].Busy = false
dir := filepath.Join(s.root, "artifacts", b.ID)
os.MkdirAll(dir, 0700)
data, _ := json.MarshalIndent(b, "", " ")
os.WriteFile(filepath.Join(dir, "build.json"), data, 0600)
_ = s.persistBuild(b)
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
}
func main() {
@@ -515,6 +655,8 @@ func main() {
key := flag.String("tls-key", "", "PEM private key path")
initHost := flag.String("init-tls-host", "", "generate a local certificate for this IP/hostname and exit")
tlsDir := flag.String("tls-dir", "./tls", "certificate output directory")
workspaceRoot := flag.String("workspace-root", "", "administrator allowed root for existing project folders; defaults to data/projects")
environmentFile := flag.String("environment-file", "", "trusted build environment JSON; reloaded for each build")
flag.Parse()
if *initHost != "" {
if e := initCertificate(*initHost, *tlsDir); e != nil {
@@ -541,6 +683,14 @@ func main() {
log.Fatal(e)
}
s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}}
s.environmentFile = *environmentFile
s.workspaceRoot = *workspaceRoot
if s.workspaceRoot == "" {
s.workspaceRoot = filepath.Join(abs, "projects")
}
if s.workspaceRoot, e = filepath.Abs(s.workspaceRoot); e != nil {
log.Fatal(e)
}
for _, t := range strings.Split(*tasks, ",") {
if !safeTask.MatchString(t) {
log.Fatal("invalid task")
@@ -552,15 +702,17 @@ func main() {
if !safeID.MatchString(entry.Name()) {
continue
}
if _, e := os.Stat(filepath.Join(abs, "projects", entry.Name(), "active-build")); e == nil {
log.Fatalf("unfinished build in project %s: stop its remaining Gradle processes, then remove active-build marker before restarting", entry.Name())
}
data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json"))
if e != nil {
continue
}
var p Project
if json.Unmarshal(data, &p) == nil {
if p.WorkspacePath != "" {
if _, e := s.validateWorkspace(p.WorkspacePath); e != nil {
log.Fatalf("workspace %s: %v", entry.Name(), e)
}
}
s.projects[entry.Name()] = &p
}
}
@@ -572,9 +724,15 @@ func main() {
}
var b Build
if json.Unmarshal(data, &b) == nil {
if b.CreatedAt == 0 {
if info, e := os.Stat(filepath.Join(abs, "artifacts", entry.Name(), "build.json")); e == nil {
b.CreatedAt = info.ModTime().UnixMilli()
}
}
s.builds[b.ID] = &b
}
}
s.recoverBuilds()
log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS)
srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second}
srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}