oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "amadan.net/oficina/equipo/internal/wire/forgekey"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "database/sql"
9 "encoding/base64"
10 "encoding/hex"
11 "encoding/json"
12 "errors"
13 "io"
14 "log/slog"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "slices"
19 "strings"
20 "sync"
21 "time"
22
23 "amadan.net/oficina/equipo/internal/runner/forge"
24 "amadan.net/oficina/equipo/internal/runner/workspace"
25 "amadan.net/oficina/equipo/internal/wire"
26)
27
28// Candidates travel as packs (Mac runners spec §2). The primary uploads
29// the exact candidate a worker judges and publishes a worker's commit; a
30// worker receives the candidate. Chunks, upload requests and publications
31// are durable here, recorded with the frame id before the ack.
32
33const relaySchema = `
34CREATE 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));
35CREATE INDEX IF NOT EXISTS chunks_step ON chunks(step_id, attempt);
36CREATE TABLE IF NOT EXISTS uploads (transfer TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL);
37CREATE TABLE IF NOT EXISTS publications (id TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL);
38CREATE 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));
39`
40
41// Upload and publication states.
42const (
43 relayPending = "pending"
44 relaySent = "sent"
45 relayIndexed = "indexed"
46 relayReported = "reported"
47 // relayUnpushed: reported, not pushed; its repository stays for a
48 // republish of the same commit.
49 relayUnpushed = "unpushed"
50 // relayRefused: a worker's upload of something it never sends.
51 relayRefused = "refused"
52)
53
54// AcceptChunk records one chunk exactly once; the caller acks after.
55func (s *State) AcceptChunk(ctx context.Context, frameID string, b wire.Blob) error {
56 header, _ := json.Marshal(b.Transfer)
57 data, err := base64.StdEncoding.DecodeString(b.Data)
58 if err != nil {
59 data = nil
60 }
61 return s.tx(ctx, func(t *sql.Tx) error {
62 fresh, err := seen(t, frameID)
63 if err != nil || !fresh || data == nil {
64 return err
65 }
66 _, 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)
67 return err
68 })
69}
70
71// AcceptUpload records a send_pack request exactly once.
72func (s *State) AcceptUpload(ctx context.Context, frameID string, c wire.SendPackCommand) error {
73 raw, _ := json.Marshal(c)
74 return s.tx(ctx, func(t *sql.Tx) error {
75 fresh, err := seen(t, frameID)
76 if err != nil || !fresh {
77 return err
78 }
79 _, err = t.Exec("INSERT INTO uploads(transfer, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Transfer.ID, string(raw), relayPending, now())
80 return err
81 })
82}
83
84// AcceptPublish records a publish command exactly once.
85func (s *State) AcceptPublish(ctx context.Context, frameID string, c wire.PublishCommand) error {
86 raw, _ := json.Marshal(c)
87 return s.tx(ctx, func(t *sql.Tx) error {
88 fresh, err := seen(t, frameID)
89 if err != nil || !fresh {
90 return err
91 }
92 _, err = t.Exec("INSERT INTO publications(id, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Publication, string(raw), relayPending, now())
93 return err
94 })
95}
96
97// AcceptPrepareBase records a prepare_base command exactly once. An
98// attempt is resolved once: asked again (a new frame for the same
99// attempt), it is answered with the base it was given, even if the
100// default branch has moved since.
101func (s *State) AcceptPrepareBase(ctx context.Context, frameID string, c wire.PrepareBaseCommand) error {
102 raw, _ := json.Marshal(c)
103 return s.tx(ctx, func(t *sql.Tx) error {
104 fresh, err := seen(t, frameID)
105 if err != nil || !fresh {
106 return err
107 }
108 var body, state, base, reason string
109 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)
110 if errors.Is(err, sql.ErrNoRows) {
111 _, err = t.Exec("INSERT INTO bases(step_id, attempt, body, state, created_at) VALUES(?,?,?,?,?)", c.StepID, c.Attempt, string(raw), relayPending, now())
112 return err
113 }
114 if err != nil || state != relayReported {
115 return err
116 }
117 var was wire.PrepareBaseCommand
118 if json.Unmarshal([]byte(body), &was) != nil || was.TaskID != c.TaskID {
119 return nil
120 }
121 return s.enqueue(t, wire.FrameBase, "", wire.BaseReport{TaskID: was.TaskID, StepID: was.StepID, Attempt: was.Attempt, BaseSHA: base, Reason: reason})
122 })
123}
124
125func (s *State) pendingBases(ctx context.Context) ([]wire.PrepareBaseCommand, error) {
126 return relayRows[wire.PrepareBaseCommand](ctx, s, "SELECT body FROM bases WHERE state=? ORDER BY created_at", relayPending)
127}
128
129// reportBase records an attempt's base and queues its report, in one
130// transaction: the attempt is never resolved twice.
131func (s *State) reportBase(ctx context.Context, rep wire.BaseReport) error {
132 return s.tx(ctx, func(t *sql.Tx) error {
133 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)
134 if err != nil {
135 return err
136 }
137 if n, _ := res.RowsAffected(); n != 1 {
138 return nil
139 }
140 return s.enqueue(t, wire.FrameBase, "", rep)
141 })
142}
143
144// ErrPackIncomplete means not every chunk of a transfer has arrived.
145var ErrPackIncomplete = errors.New("pack incomplete")
146
147// errPackRefused means the pack's chunks disagree or its digest is wrong.
148var errPackRefused = errors.New("pack refused")
149
150// pack reassembles a transfer's pack and checks its digest. want is the
151// header the receiver expects (its own step row): any other is refused.
152func (s *State) pack(ctx context.Context, want wire.TransferHeader) ([]byte, error) {
153 rows, err := s.db.QueryContext(ctx, "SELECT idx, total, sha256, header, data FROM chunks WHERE transfer=? ORDER BY idx", want.ID)
154 if err != nil {
155 return nil, err
156 }
157 defer rows.Close()
158 var buf bytes.Buffer
159 n, total, digest := 0, -1, ""
160 for rows.Next() {
161 var idx, tot int
162 var sum, header string
163 var data []byte
164 if err := rows.Scan(&idx, &tot, &sum, &header, &data); err != nil {
165 return nil, err
166 }
167 var h wire.TransferHeader
168 if json.Unmarshal([]byte(header), &h) != nil || h != want {
169 return nil, errPackRefused
170 }
171 if total == -1 {
172 total, digest = tot, sum
173 }
174 if tot > wire.MaxTransferChunks {
175 // Declared too large to relay.
176 return nil, errPackRefused
177 }
178 if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxTransferBytes {
179 return nil, errPackRefused
180 }
181 buf.Write(data)
182 n++
183 }
184 if err := rows.Err(); err != nil {
185 return nil, err
186 }
187 if total < 1 || n != total {
188 return nil, ErrPackIncomplete
189 }
190 got := sha256.Sum256(buf.Bytes())
191 if hex.EncodeToString(got[:]) != digest {
192 return nil, errPackRefused
193 }
194 return buf.Bytes(), nil
195}
196
197// inboundHeader is the transfer header a worker's step expects, from the
198// chunks that name its attempt.
199func (s *State) inboundHeader(ctx context.Context, r stepRow) (wire.TransferHeader, bool, error) {
200 var header string
201 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)
202 if errors.Is(err, sql.ErrNoRows) {
203 return wire.TransferHeader{}, false, nil
204 }
205 if err != nil {
206 return wire.TransferHeader{}, false, err
207 }
208 var h wire.TransferHeader
209 return h, true, json.Unmarshal([]byte(header), &h)
210}
211
212// dropChunks forgets a transfer's chunks.
213func (s *State) dropChunks(ctx context.Context, transfer string) error {
214 _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE transfer=?", transfer)
215 return err
216}
217
218// dropStepChunks forgets every chunk of an attempt.
219func (s *State) dropStepChunks(ctx context.Context, step string, attempt int64) error {
220 _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE step_id=? AND attempt=?", step, attempt)
221 return err
222}
223
224// queueUpload puts a pack's chunks in the outbox and marks the upload
225// sent, in one transaction: resent until acked, never built twice.
226func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []byte) error {
227 sum := sha256.Sum256(pack)
228 digest := hex.EncodeToString(sum[:])
229 total := (len(pack) + wire.MaxBlobChunk - 1) / wire.MaxBlobChunk
230 if int64(len(pack)) > wire.MaxTransferBytes {
231 // Too large to relay: one chunk says so (the instance refuses a
232 // total past the bound and the checks end as not run).
233 total = wire.MaxTransferChunks + 1
234 pack = pack[:wire.MaxBlobChunk]
235 }
236 return s.tx(ctx, func(t *sql.Tx) error {
237 res, err := t.Exec("UPDATE uploads SET state=? WHERE transfer=? AND state=?", relaySent, h.ID, relayPending)
238 if err != nil {
239 return err
240 }
241 if n, _ := res.RowsAffected(); n != 1 {
242 return nil
243 }
244 for i := 0; i*wire.MaxBlobChunk < len(pack); i++ {
245 part := pack[i*wire.MaxBlobChunk : min(len(pack), (i+1)*wire.MaxBlobChunk)]
246 if err := s.enqueue(t, wire.FrameBlob, "", wire.Blob{Transfer: h, Index: i, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(part)}); err != nil {
247 return err
248 }
249 }
250 return nil
251 })
252}
253
254// refuseUpload ends a send_pack that must never be answered.
255func (s *State) refuseUpload(ctx context.Context, transfer string) error {
256 _, err := s.db.ExecContext(ctx, "UPDATE uploads SET state=? WHERE transfer=? AND state=?", relayRefused, transfer, relayPending)
257 return err
258}
259
260func (s *State) pendingUploads(ctx context.Context) ([]wire.SendPackCommand, error) {
261 return relayRows[wire.SendPackCommand](ctx, s, "SELECT body FROM uploads WHERE state=? ORDER BY created_at", relayPending)
262}
263
264func (s *State) openPublications(ctx context.Context) ([]pubRow, error) {
265 rows, err := s.db.QueryContext(ctx, "SELECT body, state FROM publications WHERE state NOT IN (?,?) ORDER BY created_at", relayReported, relayUnpushed)
266 if err != nil {
267 return nil, err
268 }
269 defer rows.Close()
270 var out []pubRow
271 for rows.Next() {
272 var body string
273 var p pubRow
274 if err := rows.Scan(&body, &p.state); err != nil {
275 return nil, err
276 }
277 if err := json.Unmarshal([]byte(body), &p.PublishCommand); err != nil {
278 return nil, err
279 }
280 out = append(out, p)
281 }
282 return out, rows.Err()
283}
284
285type pubRow struct {
286 wire.PublishCommand
287 state string
288}
289
290func relayRows[T any](ctx context.Context, s *State, q string, args ...any) ([]T, error) {
291 rows, err := s.db.QueryContext(ctx, q, args...)
292 if err != nil {
293 return nil, err
294 }
295 defer rows.Close()
296 var out []T
297 for rows.Next() {
298 var body string
299 var v T
300 if err := rows.Scan(&body); err != nil {
301 return nil, err
302 }
303 if err := json.Unmarshal([]byte(body), &v); err != nil {
304 return nil, err
305 }
306 out = append(out, v)
307 }
308 return out, rows.Err()
309}
310
311func (s *State) setPublication(ctx context.Context, id, state string) error {
312 _, err := s.db.ExecContext(ctx, "UPDATE publications SET state=? WHERE id=?", state, id)
313 return err
314}
315
316// reportPublished queues the publication's change diffs, then its
317// published report, and marks the publication reported, in one
318// transaction.
319func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport, diffs []wire.ChangeDiffUpload) error {
320 return s.tx(ctx, func(t *sql.Tx) error {
321 next := relayReported
322 if !rep.Pushed {
323 next = relayUnpushed
324 }
325 res, err := t.Exec("UPDATE publications SET state=? WHERE id=? AND state NOT IN (?,?)", next, rep.Publication, relayReported, relayUnpushed)
326 if err != nil {
327 return err
328 }
329 if n, _ := res.RowsAffected(); n != 1 {
330 return nil
331 }
332 for _, d := range diffs {
333 if err := s.enqueue(t, wire.FrameChangeDiff, "", d); err != nil {
334 return err
335 }
336 }
337 return s.enqueue(t, wire.FramePublished, "", rep)
338 })
339}
340
341// Relay uploads packs the instance asks for and publishes workers'
342// commits, one at a time, from the durable tables. It runs at start (a
343// restart picks up where a crash left off) and when a command arrives.
344type Relay struct {
345 State *State
346 Engine *Engineer
347 // Worker, on a worker, answers uploads of its committed candidates
348 // (Mac Engineering); a worker has no bases or publications.
349 Worker *Worker
350 Notify func()
351 Logger *slog.Logger
352 retry time.Duration
353 once sync.Once
354 wake chan struct{}
355}
356
357func (x *Relay) init() { x.once.Do(func() { x.wake = make(chan struct{}, 1) }) }
358
359// Wake makes the relay look for work.
360func (x *Relay) Wake() {
361 x.init()
362 select {
363 case x.wake <- struct{}{}:
364 default:
365 }
366}
367
368// Loop runs until ctx ends.
369func (x *Relay) Loop(ctx context.Context) {
370 x.init()
371 every := x.retry
372 if every <= 0 {
373 every = 10 * time.Second
374 }
375 tick := time.NewTicker(every)
376 defer tick.Stop()
377 for {
378 x.Once(ctx)
379 select {
380 case <-ctx.Done():
381 return
382 case <-x.wake:
383 case <-tick.C:
384 }
385 }
386}
387
388// Once does what is pending now.
389func (x *Relay) Once(ctx context.Context) {
390 if x.Worker != nil {
391 x.workerUploads(ctx)
392 return
393 }
394 bases, err := x.State.pendingBases(ctx)
395 x.log("relay bases", err)
396 for _, c := range bases {
397 rep, done := x.Engine.prepareBase(ctx, c)
398 if !done {
399 continue
400 }
401 x.log("relay base", x.State.reportBase(context.WithoutCancel(ctx), rep))
402 x.notify()
403 }
404 ups, err := x.State.pendingUploads(ctx)
405 x.log("relay uploads", err)
406 for _, u := range ups {
407 pack, err := x.Engine.packCommits(ctx, u.Transfer)
408 if err != nil {
409 x.log("relay pack", err)
410 continue
411 }
412 x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack))
413 x.notify()
414 }
415 pubs, err := x.State.openPublications(ctx)
416 x.log("relay publications", err)
417 for _, p := range pubs {
418 rep, diffs, done := x.Engine.publishWorker(ctx, p)
419 if !done {
420 continue
421 }
422 x.log("relay published", x.State.reportPublished(context.WithoutCancel(ctx), rep, diffs))
423 x.notify()
424 }
425}
426
427// workerUploads answers each outbound send_pack from the worker's store:
428// the thin pack of a committed attempt's candidate, or, for one it must
429// never send, a refusal that stops it being tried again.
430func (x *Relay) workerUploads(ctx context.Context) {
431 ups, err := x.State.pendingUploads(ctx)
432 x.log("relay uploads", err)
433 for _, u := range ups {
434 pack, err := x.Worker.candidatePack(ctx, u.Transfer)
435 if errors.Is(err, errPackRefused) {
436 x.log("relay upload refused", errors.New("not a committed candidate of this worker"))
437 x.log("relay upload", x.State.refuseUpload(ctx, u.Transfer.ID))
438 continue
439 }
440 if err != nil {
441 x.log("relay pack", err)
442 continue
443 }
444 x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack))
445 x.notify()
446 }
447}
448
449func (x *Relay) notify() {
450 if x.Notify != nil {
451 x.Notify()
452 }
453}
454
455func (x *Relay) log(msg string, err error) {
456 if x.Logger != nil && err != nil {
457 x.Logger.Warn(msg, "err", sanitize(err))
458 }
459}
460
461// prepareBase resolves a worker attempt's base as Engineer.Exec does on
462// the primary: fetch, then the default branch's tip. A repository with no
463// commits (never Mac work), one that is not a hub repository, a clone
464// that cannot be fetched, or a rebase round whose commits the clone does
465// not have, is base_unavailable. done is false only when ctx ended.
466func (e *Engineer) prepareBase(ctx context.Context, c wire.PrepareBaseCommand) (wire.BaseReport, bool) {
467 rep := wire.BaseReport{TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Reason: wire.ReasonBaseUnavailable}
468 if !c.Valid() || !forgekey.ValidHub(c.Repo) {
469 return rep, true
470 }
471 fctx, cancel := context.WithTimeout(ctx, prepTimeout)
472 defer cancel()
473 if err := e.fetch(fctx, c.Repo); err != nil {
474 if ctx.Err() != nil {
475 return rep, false
476 }
477 e.log("prepare base fetch", err)
478 return rep, true
479 }
480 tip, err := e.defaultTip(fctx, c.Repo)
481 if err != nil {
482 // ErrEmptyRepo included: a worker refuses an empty base.
483 e.log("prepare base tip", err)
484 return rep, true
485 }
486 if c.Rebase && (!e.hasCommit(fctx, c.Repo, c.FromBase) || !e.hasCommit(fctx, c.Repo, c.CandidateSHA)) {
487 e.log("prepare base rebase", errors.New("the rebase round's commits are not in the clone"))
488 return rep, true
489 }
490 rep.BaseSHA, rep.Reason = tip, ""
491 return rep, true
492}
493
494// packCommits is the pack of exactly the commits the header names
495// (TransferHeader.Commits), each with its tree and blobs, and no history:
496// for a checks transfer the candidate alone, for an Engineering transfer
497// the base and, for a rebase round, the old base and the candidate. A
498// header that is not valid, a repository that is not a hub repository,
499// or a name that is not a full SHA is refused before git runs; a commit
500// the fresh clone does not have is refused before the pack is built.
501func (e *Engineer) packCommits(ctx context.Context, h wire.TransferHeader) ([]byte, error) {
502 commits := h.Commits()
503 if !forgekey.ValidHub(h.Repo) || !h.Valid() || len(commits) == 0 {
504 return nil, errPackRefused
505 }
506 for _, c := range commits {
507 if !shaPattern.MatchString(c) {
508 return nil, errPackRefused
509 }
510 }
511 ctx, cancel := context.WithTimeout(ctx, prepTimeout)
512 defer cancel()
513 if err := e.fetch(ctx, h.Repo); err != nil {
514 return nil, err
515 }
516 for _, c := range commits {
517 if !e.hasCommit(ctx, h.Repo, c) {
518 return nil, errPackRefused
519 }
520 }
521 env := workspace.GitEnvironment()
522 env["HOME"] = "/nonexistent"
523 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...)...)
524 pack := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "pack-objects", "--stdout", "-q")
525 for k, v := range env {
526 list.Env = append(list.Env, k+"="+v)
527 pack.Env = append(pack.Env, k+"="+v)
528 }
529 objects, err := list.StdoutPipe()
530 if err != nil {
531 return nil, err
532 }
533 pack.Stdin = objects
534 var out bytes.Buffer
535 pack.Stdout = &limitWriter{w: &out, n: wire.MaxTransferBytes + 1}
536 if err := list.Start(); err != nil {
537 return nil, err
538 }
539 err = pack.Run()
540 errList := list.Wait()
541 if err := errors.Join(err, errList); err != nil {
542 return nil, err
543 }
544 return out.Bytes(), nil
545}
546
547// limitWriter keeps at most n bytes and drops the rest (the caller sees
548// a pack past the bound by its length).
549type limitWriter struct {
550 w io.Writer
551 n int64
552 over bool // more was written than kept
553}
554
555func (l *limitWriter) Write(p []byte) (int, error) {
556 if int64(len(p)) > l.n {
557 l.over = true
558 }
559 if l.n <= 0 {
560 return len(p), nil
561 }
562 k := min(int64(len(p)), l.n)
563 if _, err := l.w.Write(p[:k]); err != nil {
564 return 0, err
565 }
566 l.n -= k
567 return len(p), nil
568}
569
570// relayFault, in tests, stops a publication at a named point ("indexed",
571// "pushed"), as a crash there would.
572var relayFault func(point string) bool
573
574// publishWorker publishes a worker's commit: its pack goes into a private
575// repository beside the clone, the commit must have the dispatched base
576// as its parent and a complete tree, the instance confirms the
577// publication right before the push, and forge pushes it with every check
578// it makes for the primary's own work (record, then reconcile, so a
579// repeat after a crash pushes nothing twice). Once pushed, and only
580// then, the candidate's change files and diffs on the base are measured
581// here, bound to the publication (publicationDiffs). The report echoes
582// the outcome the publish command named. done is false while it must be
583// tried again (chunks still arriving, no lease now).
584func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) {
585 rep := wire.PublishedReport{Publication: p.Publication, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, CandidateSHA: p.CandidateSHA, OutcomePhase: p.OutcomePhase}
586 fail := func(reason string) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) {
587 rep.Pushed, rep.Reason = false, reason
588 return rep, nil, true
589 }
590 if !slices.Contains(e.Owners, p.Person) || !forgekey.ValidHub(p.Repo) || !wire.ValidTaskBranch(p.Branch) || !shaPattern.MatchString(p.CandidateSHA) || !shaPattern.MatchString(p.BaseSHA) {
591 return fail("policy_rejected")
592 }
593 dir := filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt))
594 if p.state != relayIndexed {
595 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})
596 switch {
597 case errors.Is(err, ErrPackIncomplete):
598 if _, statErr := os.Stat(dir); statErr != nil {
599 return rep, nil, false
600 }
601 // Indexed before (a republish): the chunks are gone.
602 case err != nil:
603 e.log("publication pack", err)
604 return fail("candidate_unavailable")
605 default:
606 if err := e.indexWorkerPack(ctx, p, dir, pack); err != nil {
607 e.log("publication index", err)
608 return fail("candidate_unavailable")
609 }
610 }
611 if err := e.O.State.setPublication(ctx, p.Publication, relayIndexed); err != nil {
612 return rep, nil, false
613 }
614 e.log("publication chunks", e.O.State.dropChunks(ctx, p.Transfer))
615 }
616 if relayFault != nil && relayFault("indexed") {
617 return rep, nil, false
618 }
619 if err := e.verifyWorkerCommit(ctx, p, dir); err != nil {
620 e.log("publication verify", err)
621 return fail("candidate_unavailable")
622 }
623 def, err := e.publishDefault(ctx, p.Repo)
624 if err != nil {
625 // The hub is unreachable: a failed push, which Retry publishes again.
626 e.logDetail("publication default branch", err)
627 return fail("push_failed")
628 }
629 // forge reports any failed confirmation as uncertain: remember why.
630 var refused error
631 confirm := func(ctx context.Context) error {
632 if e.ConfirmPublication == nil {
633 return nil
634 }
635 refused = e.ConfirmPublication(ctx, p.StepID, p.Attempt, p.Publication)
636 return refused
637 }
638 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,
639 Remote: func(ctx context.Context) (workspace.Remote, error) { return e.Forge.Remote(ctx, p.Repo, Push) },
640 Confirm: confirm})
641 if relayFault != nil && relayFault("pushed") {
642 return rep, nil, false
643 }
644 switch {
645 case err == nil:
646 rep.Pushed = true
647 if _, proposalErr := e.Forge.Propose(ctx, Proposal{Repo: p.Repo, Branch: p.Branch}); proposalErr != nil {
648 rep.Reason = "proposal_failed"
649 }
650 var diffs []wire.ChangeDiffUpload
651 rep.ChangeFiles, rep.DiffCollection, diffs = e.publicationDiffs(ctx, p, dir)
652 return rep, diffs, true
653 case errors.Is(refused, ErrWithdrawn):
654 return fail("cancelled")
655 case refused != nil:
656 // No lease now (disconnected): try again later.
657 return rep, nil, false
658 case errors.Is(err, forge.ErrPushConflict):
659 return fail("push_conflict")
660 default:
661 // The published report has no log tail (a wire change): the log
662 // line keeps git's answer.
663 e.logPush("publication push", err)
664 return fail("push_failed")
665 }
666}
667
668// indexWorkerPack makes a private repository that sees the clone's
669// objects (the base and its history) and indexes the worker's pack.
670func (e *Engineer) indexWorkerPack(ctx context.Context, p pubRow, dir string, pack []byte) error {
671 if !e.hasCommit(ctx, p.Repo, p.BaseSHA) {
672 if err := e.fetch(ctx, p.Repo); err != nil {
673 return err
674 }
675 }
676 git := func(stdin io.Reader, args ...string) error {
677 cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...)
678 cmd.Stdin = stdin
679 for k, v := range workspace.GitEnvironment() {
680 cmd.Env = append(cmd.Env, k+"="+v)
681 }
682 cmd.Env = append(cmd.Env, "HOME=/nonexistent")
683 return cmd.Run()
684 }
685 if err := os.MkdirAll(dir, 0700); err != nil {
686 return err
687 }
688 if err := git(nil, "init", "-q", "--bare", "--template="); err != nil {
689 return err
690 }
691 alt := filepath.Join(dir, "objects", "info", "alternates")
692 if err := os.MkdirAll(filepath.Dir(alt), 0700); err != nil {
693 return err
694 }
695 if err := os.WriteFile(alt, []byte(filepath.Join(e.Clones.Path(p.Repo), "objects")+"\n"), 0600); err != nil {
696 return err
697 }
698 return git(bytes.NewReader(pack), "index-pack", "--stdin", "--fix-thin")
699}
700
701// hasCommit reports whether the project clone holds a commit.
702func (e *Engineer) hasCommit(ctx context.Context, repo, sha string) bool {
703 cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(repo), "cat-file", "-e", sha+"^{commit}")
704 for k, v := range workspace.GitEnvironment() {
705 cmd.Env = append(cmd.Env, k+"="+v)
706 }
707 return cmd.Run() == nil
708}
709
710// verifyWorkerCommit: exactly the candidate, a commit whose one parent is
711// the dispatched base, with every object of its tree present.
712func (e *Engineer) verifyWorkerCommit(ctx context.Context, p pubRow, dir string) error {
713 out := func(args ...string) (string, error) {
714 cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...)
715 for k, v := range workspace.GitEnvironment() {
716 cmd.Env = append(cmd.Env, k+"="+v)
717 }
718 cmd.Env = append(cmd.Env, "HOME=/nonexistent")
719 raw, err := cmd.Output()
720 return strings.TrimSpace(string(raw)), err
721 }
722 parents, err := out("rev-list", "--parents", "-n", "1", "--end-of-options", p.CandidateSHA)
723 if err != nil {
724 return err
725 }
726 if fields := strings.Fields(parents); len(fields) != 2 || fields[0] != p.CandidateSHA || fields[1] != p.BaseSHA {
727 return errors.New("the worker's commit is not on the dispatched base")
728 }
729 _, err = out("rev-list", "--objects", "--no-walk", "--end-of-options", p.CandidateSHA)
730 return err
731}
732
733// SweepPublications removes the private repositories of pushed
734// publications whose report the instance acked (an unpushed one keeps
735// its commit for Retry).
736func (e *Engineer) SweepPublications(ctx context.Context, s *State) {
737 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)
738 if err != nil {
739 return
740 }
741 var keep []wire.PublishCommand
742 for rows.Next() {
743 var body string
744 var p wire.PublishCommand
745 if rows.Scan(&body) == nil && json.Unmarshal([]byte(body), &p) == nil {
746 keep = append(keep, p)
747 }
748 }
749 rows.Close()
750 for _, p := range keep {
751 _ = os.RemoveAll(filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt)))
752 }
753}
754