package thin import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "bytes" "context" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "errors" "io" "log/slog" "os" "os/exec" "path/filepath" "slices" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // Candidates travel as packs (Mac runners spec ยง2). The primary uploads // the exact candidate a worker judges and publishes a worker's commit; a // worker receives the candidate. Chunks, upload requests and publications // are durable here, recorded with the frame id before the ack. const relaySchema = ` CREATE TABLE IF NOT EXISTS chunks (transfer TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, sha256 TEXT NOT NULL, header TEXT NOT NULL, step_id TEXT NOT NULL, attempt INTEGER NOT NULL, direction TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY (transfer, idx)); CREATE INDEX IF NOT EXISTS chunks_step ON chunks(step_id, attempt); CREATE TABLE IF NOT EXISTS uploads (transfer TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS publications (id TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS bases (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, body TEXT NOT NULL, base_sha TEXT NOT NULL DEFAULT '', reason TEXT NOT NULL DEFAULT '', state TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (step_id, attempt)); ` // Upload and publication states. const ( relayPending = "pending" relaySent = "sent" relayIndexed = "indexed" relayReported = "reported" // relayUnpushed: reported, not pushed; its repository stays for a // republish of the same commit. relayUnpushed = "unpushed" // relayRefused: a worker's upload of something it never sends. relayRefused = "refused" ) // AcceptChunk records one chunk exactly once; the caller acks after. func (s *State) AcceptChunk(ctx context.Context, frameID string, b wire.Blob) error { header, _ := json.Marshal(b.Transfer) data, err := base64.StdEncoding.DecodeString(b.Data) if err != nil { data = nil } return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh || data == nil { return err } _, err = t.Exec("INSERT INTO chunks(transfer, idx, total, sha256, header, step_id, attempt, direction, data) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", b.Transfer.ID, b.Index, b.Total, b.SHA256, string(header), b.Transfer.StepID, b.Transfer.Attempt, b.Transfer.Direction, data) return err }) } // AcceptUpload records a send_pack request exactly once. func (s *State) AcceptUpload(ctx context.Context, frameID string, c wire.SendPackCommand) error { raw, _ := json.Marshal(c) return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } _, err = t.Exec("INSERT INTO uploads(transfer, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Transfer.ID, string(raw), relayPending, now()) return err }) } // AcceptPublish records a publish command exactly once. func (s *State) AcceptPublish(ctx context.Context, frameID string, c wire.PublishCommand) error { raw, _ := json.Marshal(c) return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } _, err = t.Exec("INSERT INTO publications(id, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Publication, string(raw), relayPending, now()) return err }) } // AcceptPrepareBase records a prepare_base command exactly once. An // attempt is resolved once: asked again (a new frame for the same // attempt), it is answered with the base it was given, even if the // default branch has moved since. func (s *State) AcceptPrepareBase(ctx context.Context, frameID string, c wire.PrepareBaseCommand) error { raw, _ := json.Marshal(c) return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } var body, state, base, reason string err = t.QueryRow("SELECT body, state, base_sha, reason FROM bases WHERE step_id=? AND attempt=?", c.StepID, c.Attempt).Scan(&body, &state, &base, &reason) if errors.Is(err, sql.ErrNoRows) { _, err = t.Exec("INSERT INTO bases(step_id, attempt, body, state, created_at) VALUES(?,?,?,?,?)", c.StepID, c.Attempt, string(raw), relayPending, now()) return err } if err != nil || state != relayReported { return err } var was wire.PrepareBaseCommand if json.Unmarshal([]byte(body), &was) != nil || was.TaskID != c.TaskID { return nil } return s.enqueue(t, wire.FrameBase, "", wire.BaseReport{TaskID: was.TaskID, StepID: was.StepID, Attempt: was.Attempt, BaseSHA: base, Reason: reason}) }) } func (s *State) pendingBases(ctx context.Context) ([]wire.PrepareBaseCommand, error) { return relayRows[wire.PrepareBaseCommand](ctx, s, "SELECT body FROM bases WHERE state=? ORDER BY created_at", relayPending) } // reportBase records an attempt's base and queues its report, in one // transaction: the attempt is never resolved twice. func (s *State) reportBase(ctx context.Context, rep wire.BaseReport) error { return s.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE bases SET state=?, base_sha=?, reason=? WHERE step_id=? AND attempt=? AND state=?", relayReported, rep.BaseSHA, rep.Reason, rep.StepID, rep.Attempt, relayPending) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } return s.enqueue(t, wire.FrameBase, "", rep) }) } // ErrPackIncomplete means not every chunk of a transfer has arrived. var ErrPackIncomplete = errors.New("pack incomplete") // errPackRefused means the pack's chunks disagree or its digest is wrong. var errPackRefused = errors.New("pack refused") // pack reassembles a transfer's pack and checks its digest. want is the // header the receiver expects (its own step row): any other is refused. func (s *State) pack(ctx context.Context, want wire.TransferHeader) ([]byte, error) { rows, err := s.db.QueryContext(ctx, "SELECT idx, total, sha256, header, data FROM chunks WHERE transfer=? ORDER BY idx", want.ID) if err != nil { return nil, err } defer rows.Close() var buf bytes.Buffer n, total, digest := 0, -1, "" for rows.Next() { var idx, tot int var sum, header string var data []byte if err := rows.Scan(&idx, &tot, &sum, &header, &data); err != nil { return nil, err } var h wire.TransferHeader if json.Unmarshal([]byte(header), &h) != nil || h != want { return nil, errPackRefused } if total == -1 { total, digest = tot, sum } if tot > wire.MaxTransferChunks { // Declared too large to relay. return nil, errPackRefused } if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxTransferBytes { return nil, errPackRefused } buf.Write(data) n++ } if err := rows.Err(); err != nil { return nil, err } if total < 1 || n != total { return nil, ErrPackIncomplete } got := sha256.Sum256(buf.Bytes()) if hex.EncodeToString(got[:]) != digest { return nil, errPackRefused } return buf.Bytes(), nil } // inboundHeader is the transfer header a worker's step expects, from the // chunks that name its attempt. func (s *State) inboundHeader(ctx context.Context, r stepRow) (wire.TransferHeader, bool, error) { var header string err := s.db.QueryRowContext(ctx, "SELECT header FROM chunks WHERE step_id=? AND attempt=? AND direction=? ORDER BY idx LIMIT 1", r.StepID, r.Attempt, wire.TransferInbound).Scan(&header) if errors.Is(err, sql.ErrNoRows) { return wire.TransferHeader{}, false, nil } if err != nil { return wire.TransferHeader{}, false, err } var h wire.TransferHeader return h, true, json.Unmarshal([]byte(header), &h) } // dropChunks forgets a transfer's chunks. func (s *State) dropChunks(ctx context.Context, transfer string) error { _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE transfer=?", transfer) return err } // dropStepChunks forgets every chunk of an attempt. func (s *State) dropStepChunks(ctx context.Context, step string, attempt int64) error { _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE step_id=? AND attempt=?", step, attempt) return err } // queueUpload puts a pack's chunks in the outbox and marks the upload // sent, in one transaction: resent until acked, never built twice. func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []byte) error { sum := sha256.Sum256(pack) digest := hex.EncodeToString(sum[:]) total := (len(pack) + wire.MaxBlobChunk - 1) / wire.MaxBlobChunk if int64(len(pack)) > wire.MaxTransferBytes { // Too large to relay: one chunk says so (the instance refuses a // total past the bound and the checks end as not run). total = wire.MaxTransferChunks + 1 pack = pack[:wire.MaxBlobChunk] } return s.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE uploads SET state=? WHERE transfer=? AND state=?", relaySent, h.ID, relayPending) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } for i := 0; i*wire.MaxBlobChunk < len(pack); i++ { part := pack[i*wire.MaxBlobChunk : min(len(pack), (i+1)*wire.MaxBlobChunk)] if err := s.enqueue(t, wire.FrameBlob, "", wire.Blob{Transfer: h, Index: i, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(part)}); err != nil { return err } } return nil }) } // refuseUpload ends a send_pack that must never be answered. func (s *State) refuseUpload(ctx context.Context, transfer string) error { _, err := s.db.ExecContext(ctx, "UPDATE uploads SET state=? WHERE transfer=? AND state=?", relayRefused, transfer, relayPending) return err } func (s *State) pendingUploads(ctx context.Context) ([]wire.SendPackCommand, error) { return relayRows[wire.SendPackCommand](ctx, s, "SELECT body FROM uploads WHERE state=? ORDER BY created_at", relayPending) } func (s *State) openPublications(ctx context.Context) ([]pubRow, error) { rows, err := s.db.QueryContext(ctx, "SELECT body, state FROM publications WHERE state NOT IN (?,?) ORDER BY created_at", relayReported, relayUnpushed) if err != nil { return nil, err } defer rows.Close() var out []pubRow for rows.Next() { var body string var p pubRow if err := rows.Scan(&body, &p.state); err != nil { return nil, err } if err := json.Unmarshal([]byte(body), &p.PublishCommand); err != nil { return nil, err } out = append(out, p) } return out, rows.Err() } type pubRow struct { wire.PublishCommand state string } func relayRows[T any](ctx context.Context, s *State, q string, args ...any) ([]T, error) { rows, err := s.db.QueryContext(ctx, q, args...) if err != nil { return nil, err } defer rows.Close() var out []T for rows.Next() { var body string var v T if err := rows.Scan(&body); err != nil { return nil, err } if err := json.Unmarshal([]byte(body), &v); err != nil { return nil, err } out = append(out, v) } return out, rows.Err() } func (s *State) setPublication(ctx context.Context, id, state string) error { _, err := s.db.ExecContext(ctx, "UPDATE publications SET state=? WHERE id=?", state, id) return err } // reportPublished queues the publication's change diffs, then its // published report, and marks the publication reported, in one // transaction. func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport, diffs []wire.ChangeDiffUpload) error { return s.tx(ctx, func(t *sql.Tx) error { next := relayReported if !rep.Pushed { next = relayUnpushed } res, err := t.Exec("UPDATE publications SET state=? WHERE id=? AND state NOT IN (?,?)", next, rep.Publication, relayReported, relayUnpushed) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } for _, d := range diffs { if err := s.enqueue(t, wire.FrameChangeDiff, "", d); err != nil { return err } } return s.enqueue(t, wire.FramePublished, "", rep) }) } // Relay uploads packs the instance asks for and publishes workers' // commits, one at a time, from the durable tables. It runs at start (a // restart picks up where a crash left off) and when a command arrives. type Relay struct { State *State Engine *Engineer // Worker, on a worker, answers uploads of its committed candidates // (Mac Engineering); a worker has no bases or publications. Worker *Worker Notify func() Logger *slog.Logger retry time.Duration once sync.Once wake chan struct{} } func (x *Relay) init() { x.once.Do(func() { x.wake = make(chan struct{}, 1) }) } // Wake makes the relay look for work. func (x *Relay) Wake() { x.init() select { case x.wake <- struct{}{}: default: } } // Loop runs until ctx ends. func (x *Relay) Loop(ctx context.Context) { x.init() every := x.retry if every <= 0 { every = 10 * time.Second } tick := time.NewTicker(every) defer tick.Stop() for { x.Once(ctx) select { case <-ctx.Done(): return case <-x.wake: case <-tick.C: } } } // Once does what is pending now. func (x *Relay) Once(ctx context.Context) { if x.Worker != nil { x.workerUploads(ctx) return } bases, err := x.State.pendingBases(ctx) x.log("relay bases", err) for _, c := range bases { rep, done := x.Engine.prepareBase(ctx, c) if !done { continue } x.log("relay base", x.State.reportBase(context.WithoutCancel(ctx), rep)) x.notify() } ups, err := x.State.pendingUploads(ctx) x.log("relay uploads", err) for _, u := range ups { pack, err := x.Engine.packCommits(ctx, u.Transfer) if err != nil { x.log("relay pack", err) continue } x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack)) x.notify() } pubs, err := x.State.openPublications(ctx) x.log("relay publications", err) for _, p := range pubs { rep, diffs, done := x.Engine.publishWorker(ctx, p) if !done { continue } x.log("relay published", x.State.reportPublished(context.WithoutCancel(ctx), rep, diffs)) x.notify() } } // workerUploads answers each outbound send_pack from the worker's store: // the thin pack of a committed attempt's candidate, or, for one it must // never send, a refusal that stops it being tried again. func (x *Relay) workerUploads(ctx context.Context) { ups, err := x.State.pendingUploads(ctx) x.log("relay uploads", err) for _, u := range ups { pack, err := x.Worker.candidatePack(ctx, u.Transfer) if errors.Is(err, errPackRefused) { x.log("relay upload refused", errors.New("not a committed candidate of this worker")) x.log("relay upload", x.State.refuseUpload(ctx, u.Transfer.ID)) continue } if err != nil { x.log("relay pack", err) continue } x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack)) x.notify() } } func (x *Relay) notify() { if x.Notify != nil { x.Notify() } } func (x *Relay) log(msg string, err error) { if x.Logger != nil && err != nil { x.Logger.Warn(msg, "err", sanitize(err)) } } // prepareBase resolves a worker attempt's base as Engineer.Exec does on // the primary: fetch, then the default branch's tip. A repository with no // commits (never Mac work), one that is not a hub repository, a clone // that cannot be fetched, or a rebase round whose commits the clone does // not have, is base_unavailable. done is false only when ctx ended. func (e *Engineer) prepareBase(ctx context.Context, c wire.PrepareBaseCommand) (wire.BaseReport, bool) { rep := wire.BaseReport{TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Reason: wire.ReasonBaseUnavailable} if !c.Valid() || !forgekey.ValidHub(c.Repo) { return rep, true } fctx, cancel := context.WithTimeout(ctx, prepTimeout) defer cancel() if err := e.fetch(fctx, c.Repo); err != nil { if ctx.Err() != nil { return rep, false } e.log("prepare base fetch", err) return rep, true } tip, err := e.defaultTip(fctx, c.Repo) if err != nil { // ErrEmptyRepo included: a worker refuses an empty base. e.log("prepare base tip", err) return rep, true } if c.Rebase && (!e.hasCommit(fctx, c.Repo, c.FromBase) || !e.hasCommit(fctx, c.Repo, c.CandidateSHA)) { e.log("prepare base rebase", errors.New("the rebase round's commits are not in the clone")) return rep, true } rep.BaseSHA, rep.Reason = tip, "" return rep, true } // packCommits is the pack of exactly the commits the header names // (TransferHeader.Commits), each with its tree and blobs, and no history: // for a checks transfer the candidate alone, for an Engineering transfer // the base and, for a rebase round, the old base and the candidate. A // header that is not valid, a repository that is not a hub repository, // or a name that is not a full SHA is refused before git runs; a commit // the fresh clone does not have is refused before the pack is built. func (e *Engineer) packCommits(ctx context.Context, h wire.TransferHeader) ([]byte, error) { commits := h.Commits() if !forgekey.ValidHub(h.Repo) || !h.Valid() || len(commits) == 0 { return nil, errPackRefused } for _, c := range commits { if !shaPattern.MatchString(c) { return nil, errPackRefused } } ctx, cancel := context.WithTimeout(ctx, prepTimeout) defer cancel() if err := e.fetch(ctx, h.Repo); err != nil { return nil, err } for _, c := range commits { if !e.hasCommit(ctx, h.Repo, c) { return nil, errPackRefused } } env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" list := groupCommand(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + e.Clones.Path(h.Repo), "rev-list", "--objects", "--no-walk", "--end-of-options"}, commits...)...) pack := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "pack-objects", "--stdout", "-q") for k, v := range env { list.Env = append(list.Env, k+"="+v) pack.Env = append(pack.Env, k+"="+v) } objects, err := list.StdoutPipe() if err != nil { return nil, err } pack.Stdin = objects var out bytes.Buffer pack.Stdout = &limitWriter{w: &out, n: wire.MaxTransferBytes + 1} if err := list.Start(); err != nil { return nil, err } err = pack.Run() errList := list.Wait() if err := errors.Join(err, errList); err != nil { return nil, err } return out.Bytes(), nil } // limitWriter keeps at most n bytes and drops the rest (the caller sees // a pack past the bound by its length). type limitWriter struct { w io.Writer n int64 over bool // more was written than kept } func (l *limitWriter) Write(p []byte) (int, error) { if int64(len(p)) > l.n { l.over = true } if l.n <= 0 { return len(p), nil } k := min(int64(len(p)), l.n) if _, err := l.w.Write(p[:k]); err != nil { return 0, err } l.n -= k return len(p), nil } // relayFault, in tests, stops a publication at a named point ("indexed", // "pushed"), as a crash there would. var relayFault func(point string) bool // publishWorker publishes a worker's commit: its pack goes into a private // repository beside the clone, the commit must have the dispatched base // as its parent and a complete tree, the instance confirms the // publication right before the push, and forge pushes it with every check // it makes for the primary's own work (record, then reconcile, so a // repeat after a crash pushes nothing twice). Once pushed, and only // then, the candidate's change files and diffs on the base are measured // here, bound to the publication (publicationDiffs). The report echoes // the outcome the publish command named. done is false while it must be // tried again (chunks still arriving, no lease now). func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) { rep := wire.PublishedReport{Publication: p.Publication, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, CandidateSHA: p.CandidateSHA, OutcomePhase: p.OutcomePhase} fail := func(reason string) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) { rep.Pushed, rep.Reason = false, reason return rep, nil, true } if !slices.Contains(e.Owners, p.Person) || !forgekey.ValidHub(p.Repo) || !wire.ValidTaskBranch(p.Branch) || !shaPattern.MatchString(p.CandidateSHA) || !shaPattern.MatchString(p.BaseSHA) { return fail("policy_rejected") } dir := filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt)) if p.state != relayIndexed { pack, err := e.O.State.pack(ctx, wire.TransferHeader{ID: p.Transfer, Direction: wire.TransferOutbound, Repo: p.Repo, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, BaseSHA: p.BaseSHA, CandidateSHA: p.CandidateSHA}) switch { case errors.Is(err, ErrPackIncomplete): if _, statErr := os.Stat(dir); statErr != nil { return rep, nil, false } // Indexed before (a republish): the chunks are gone. case err != nil: e.log("publication pack", err) return fail("candidate_unavailable") default: if err := e.indexWorkerPack(ctx, p, dir, pack); err != nil { e.log("publication index", err) return fail("candidate_unavailable") } } if err := e.O.State.setPublication(ctx, p.Publication, relayIndexed); err != nil { return rep, nil, false } e.log("publication chunks", e.O.State.dropChunks(ctx, p.Transfer)) } if relayFault != nil && relayFault("indexed") { return rep, nil, false } if err := e.verifyWorkerCommit(ctx, p, dir); err != nil { e.log("publication verify", err) return fail("candidate_unavailable") } def, err := e.publishDefault(ctx, p.Repo) if err != nil { // The hub is unreachable: a failed push, which Retry publishes again. e.logDetail("publication default branch", err) return fail("push_failed") } // forge reports any failed confirmation as uncertain: remember why. var refused error confirm := func(ctx context.Context) error { if e.ConfirmPublication == nil { return nil } refused = e.ConfirmPublication(ctx, p.StepID, p.Attempt, p.Publication) return refused } err = forge.PushBranch(ctx, forge.BranchPush{Root: filepath.Join(e.root(), "publish"), Git: e.O.Runner.GitPath, GitDir: dir, Repo: p.Repo, Branch: p.Branch, Default: def, Base: p.BaseSHA, Commit: p.CandidateSHA, Key: p.TaskID + "/" + p.StepID + "/" + itoa(p.Attempt) + "/worker", Person: p.Person, Owners: e.Owners, Remote: func(ctx context.Context) (workspace.Remote, error) { return e.Forge.Remote(ctx, p.Repo, Push) }, Confirm: confirm}) if relayFault != nil && relayFault("pushed") { return rep, nil, false } switch { case err == nil: rep.Pushed = true if _, proposalErr := e.Forge.Propose(ctx, Proposal{Repo: p.Repo, Branch: p.Branch}); proposalErr != nil { rep.Reason = "proposal_failed" } var diffs []wire.ChangeDiffUpload rep.ChangeFiles, rep.DiffCollection, diffs = e.publicationDiffs(ctx, p, dir) return rep, diffs, true case errors.Is(refused, ErrWithdrawn): return fail("cancelled") case refused != nil: // No lease now (disconnected): try again later. return rep, nil, false case errors.Is(err, forge.ErrPushConflict): return fail("push_conflict") default: // The published report has no log tail (a wire change): the log // line keeps git's answer. e.logPush("publication push", err) return fail("push_failed") } } // indexWorkerPack makes a private repository that sees the clone's // objects (the base and its history) and indexes the worker's pack. func (e *Engineer) indexWorkerPack(ctx context.Context, p pubRow, dir string, pack []byte) error { if !e.hasCommit(ctx, p.Repo, p.BaseSHA) { if err := e.fetch(ctx, p.Repo); err != nil { return err } } git := func(stdin io.Reader, args ...string) error { cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...) cmd.Stdin = stdin for k, v := range workspace.GitEnvironment() { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Env = append(cmd.Env, "HOME=/nonexistent") return cmd.Run() } if err := os.MkdirAll(dir, 0700); err != nil { return err } if err := git(nil, "init", "-q", "--bare", "--template="); err != nil { return err } alt := filepath.Join(dir, "objects", "info", "alternates") if err := os.MkdirAll(filepath.Dir(alt), 0700); err != nil { return err } if err := os.WriteFile(alt, []byte(filepath.Join(e.Clones.Path(p.Repo), "objects")+"\n"), 0600); err != nil { return err } return git(bytes.NewReader(pack), "index-pack", "--stdin", "--fix-thin") } // hasCommit reports whether the project clone holds a commit. func (e *Engineer) hasCommit(ctx context.Context, repo, sha string) bool { cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(repo), "cat-file", "-e", sha+"^{commit}") for k, v := range workspace.GitEnvironment() { cmd.Env = append(cmd.Env, k+"="+v) } return cmd.Run() == nil } // verifyWorkerCommit: exactly the candidate, a commit whose one parent is // the dispatched base, with every object of its tree present. func (e *Engineer) verifyWorkerCommit(ctx context.Context, p pubRow, dir string) error { out := func(args ...string) (string, error) { cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...) for k, v := range workspace.GitEnvironment() { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Env = append(cmd.Env, "HOME=/nonexistent") raw, err := cmd.Output() return strings.TrimSpace(string(raw)), err } parents, err := out("rev-list", "--parents", "-n", "1", "--end-of-options", p.CandidateSHA) if err != nil { return err } if fields := strings.Fields(parents); len(fields) != 2 || fields[0] != p.CandidateSHA || fields[1] != p.BaseSHA { return errors.New("the worker's commit is not on the dispatched base") } _, err = out("rev-list", "--objects", "--no-walk", "--end-of-options", p.CandidateSHA) return err } // SweepPublications removes the private repositories of pushed // publications whose report the instance acked (an unpushed one keeps // its commit for Retry). func (e *Engineer) SweepPublications(ctx context.Context, s *State) { rows, err := s.db.QueryContext(ctx, "SELECT body FROM publications WHERE state=? AND NOT EXISTS (SELECT 1 FROM outbox WHERE kind=? AND acked=0 AND body LIKE '%' || publications.id || '%')", relayReported, wire.FramePublished) if err != nil { return } var keep []wire.PublishCommand for rows.Next() { var body string var p wire.PublishCommand if rows.Scan(&body) == nil && json.Unmarshal([]byte(body), &p) == nil { keep = append(keep, p) } } rows.Close() for _, p := range keep { _ = os.RemoveAll(filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt))) } }