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 "bytes"
5 "context"
6 "database/sql"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "slices"
15 "strings"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner"
19 "amadan.net/oficina/equipo/internal/runner/mac"
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runner/workspace"
22 "amadan.net/oficina/equipo/internal/sealbox"
23 "amadan.net/oficina/equipo/internal/wire"
24 "amadan.net/oficina/equipo/internal/wire/forgekey"
25)
26
27// A worker's store for Engineering (Mac runners spec §8.4): one bare
28// repository per hub repository, holding the commits the primary relays
29// (each a shallow boundary: their parents never come) and the candidates
30// the worker made, each pinned by its ref until its task is forgotten.
31
32// candidatesSchema records each pinned candidate and, once its task is
33// forgotten, until when it stays (a stamp; ” while the task is open).
34const candidatesSchema = `
35CREATE TABLE IF NOT EXISTS candidates (ref TEXT NOT NULL, repo TEXT NOT NULL, task_id TEXT NOT NULL, person TEXT NOT NULL, expires_at TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, PRIMARY KEY (repo, ref));
36CREATE INDEX IF NOT EXISTS candidates_task ON candidates(task_id, person);
37`
38
39// objectFormat names the object format of a full object id.
40func objectFormat(sha string) string {
41 if len(sha) == 64 {
42 return "sha256"
43 }
44 return "sha1"
45}
46
47// initStore makes the repository's store if it is missing.
48func (w *Worker) initStore(ctx context.Context, store, sha string) error {
49 if _, err := os.Stat(store); err == nil {
50 return nil
51 }
52 if err := os.MkdirAll(store, 0700); err != nil {
53 return err
54 }
55 _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(sha), store)
56 return err
57}
58
59// indexEngineering checks an Engineering pack's own inventory, alone in
60// a repository of its own (scratch/inventory.git): exactly the commits
61// the header names, each with its whole tree, and nothing else. Only then
62// does it go into the store, its commits marked shallow there.
63func (w *Worker) indexEngineering(ctx context.Context, store, scratch string, pack []byte, h wire.TransferHeader) error {
64 commits := h.Commits()
65 look := filepath.Join(scratch, "inventory.git")
66 if err := os.RemoveAll(look); err != nil {
67 return err
68 }
69 if err := os.MkdirAll(look, 0700); err != nil {
70 return err
71 }
72 defer os.RemoveAll(look)
73 if _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(h.BaseSHA), look); err != nil {
74 return err
75 }
76 out, err := w.git(ctx, bytes.NewReader(pack), "--git-dir="+look, "index-pack", "--stdin")
77 if err != nil {
78 return err
79 }
80 fields := strings.Fields(out)
81 if len(fields) == 0 || !wire.ValidCommitSHA(fields[len(fields)-1]) {
82 return errPackRefused
83 }
84 listed, err := w.git(ctx, nil, "verify-pack", "-v", filepath.Join(look, "objects", "pack", "pack-"+fields[len(fields)-1]+".idx"))
85 if err != nil {
86 return err
87 }
88 inPack, packed := map[string]bool{}, []string{}
89 for _, line := range strings.Split(listed, "\n") {
90 f := strings.Fields(line)
91 if len(f) < 3 || !wire.ValidCommitSHA(f[0]) {
92 continue
93 }
94 inPack[f[0]] = true
95 if f[1] == "commit" {
96 packed = append(packed, f[0])
97 }
98 }
99 walk, err := w.git(ctx, nil, append([]string{"--git-dir=" + look, "rev-list", "--objects", "--no-walk", "--end-of-options"}, commits...)...)
100 if err != nil {
101 return err
102 }
103 whole := map[string]bool{}
104 for _, line := range strings.Split(walk, "\n") {
105 if f := strings.Fields(line); len(f) > 0 {
106 whole[f[0]] = true
107 }
108 }
109 // The walk ran where only the pack's objects are, so every object it
110 // listed is in the pack: equal counts are equal sets.
111 slices.Sort(packed)
112 named := slices.Sorted(slices.Values(commits))
113 if !slices.Equal(packed, named) || len(whole) != len(inPack) {
114 return errPackRefused
115 }
116 if err := w.initStore(ctx, store, h.BaseSHA); err != nil {
117 return err
118 }
119 if _, err := w.git(ctx, bytes.NewReader(pack), "--git-dir="+store, "index-pack", "--stdin"); err != nil {
120 return err
121 }
122 return markShallow(store, commits)
123}
124
125// markShallow adds commits to the store's shallow file (merged with what
126// is there, sorted), so log and rev-list stop at them.
127func markShallow(store string, commits []string) error {
128 path := filepath.Join(store, "shallow")
129 raw, err := os.ReadFile(path)
130 if err != nil && !errors.Is(err, fs.ErrNotExist) {
131 return err
132 }
133 all := slices.Clone(commits)
134 for _, line := range strings.Split(string(raw), "\n") {
135 if line = strings.TrimSpace(line); line != "" {
136 all = append(all, line)
137 }
138 }
139 slices.Sort(all)
140 all = slices.Compact(all)
141 tmp := path + ".new"
142 if err := os.WriteFile(tmp, []byte(strings.Join(all, "\n")+"\n"), 0600); err != nil {
143 return err
144 }
145 return os.Rename(tmp, path)
146}
147
148// retain copies the candidate's new objects from the task tree's private
149// repository into the store and pins it with its ref, recorded with its
150// task so a forget_task releases it.
151func (w *Worker) retain(ctx context.Context, tree workspace.TaskTree, store, dir string, r stepRow, base, sha string) error {
152 file := filepath.Join(dir, "candidate.pack")
153 f, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
154 if err != nil {
155 return err
156 }
157 defer os.Remove(file)
158 cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+tree.GitDir, "pack-objects", "--revs", "--stdout", "-q")
159 cmd.Stdin, cmd.Stdout, cmd.Env = strings.NewReader(sha+"\n^"+base+"\n"), f, w.gitEnv()
160 err = mac.StartOwn(cmd)
161 if err == nil {
162 err = cmd.Wait()
163 }
164 if cerr := f.Close(); err == nil {
165 err = cerr
166 }
167 if err != nil {
168 return err
169 }
170 in, err := os.Open(file)
171 if err != nil {
172 return err
173 }
174 defer in.Close()
175 if _, err := w.git(ctx, in, "--git-dir="+store, "index-pack", "--stdin"); err != nil {
176 return err
177 }
178 ref := candidateRef(r)
179 if _, err := w.git(ctx, nil, "--git-dir="+store, "update-ref", ref, sha); err != nil {
180 return err
181 }
182 _, err = w.State.db.ExecContext(ctx, "INSERT INTO candidates(ref, repo, task_id, person, created_at) VALUES(?,?,?,?,?) ON CONFLICT DO NOTHING", ref, r.Repo, r.TaskID, r.Person, now())
183 return err
184}
185
186// dropCandidate removes a candidate's ref and its record.
187func (w *Worker) dropCandidate(ctx context.Context, repo, ref string) error {
188 if _, err := os.Stat(w.objects(repo)); err == nil {
189 if _, err := w.git(ctx, nil, "--git-dir="+w.objects(repo), "update-ref", "-d", ref); err != nil {
190 return err
191 }
192 }
193 _, err := w.State.db.ExecContext(ctx, "DELETE FROM candidates WHERE repo=? AND ref=?", repo, ref)
194 return err
195}
196
197// gitEnv is the environment of the worker's own git: no config, no
198// home, the attempt's marker.
199func (w *Worker) gitEnv() []string {
200 var env []string
201 for k, v := range workspace.GitEnvironment() {
202 env = append(env, k+"="+v)
203 }
204 return append(env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker)
205}
206
207// candidatePack is the thin pack (against the base) of a committed
208// attempt's candidate, for an outbound transfer: the attempt must be on
209// record committed with exactly this base and candidate, which only a
210// passed scan records, and its ref must pin the candidate. It is answered
211// as often as the instance asks (a Retry after the primary was replaced
212// sends a second send_pack), from the store alone. errPackRefused: never.
213func (w *Worker) candidatePack(ctx context.Context, h wire.TransferHeader) ([]byte, error) {
214 if h.Direction != wire.TransferOutbound || h.Kind != "" || !forgekey.ValidHub(h.Repo) || !h.Valid() || !wire.ValidCommitSHA(h.BaseSHA) || !wire.ValidCommitSHA(h.CandidateSHA) || !refName.MatchString(h.TaskID) || !refName.MatchString(h.StepID) || h.Attempt < 1 {
215 return nil, errPackRefused
216 }
217 var task, phase, base, cand string
218 err := w.State.db.QueryRowContext(ctx, "SELECT task_id, phase, base_sha, candidate_sha FROM steps WHERE step_id=? AND attempt=?", h.StepID, h.Attempt).Scan(&task, &phase, &base, &cand)
219 if errors.Is(err, sql.ErrNoRows) {
220 return nil, errPackRefused
221 }
222 if err != nil {
223 return nil, err
224 }
225 if task != h.TaskID || !committed(phase) || base != h.BaseSHA || cand != h.CandidateSHA {
226 return nil, errPackRefused
227 }
228 store := w.objects(h.Repo)
229 ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt}})
230 // Retained, and not past its keep: a forgotten candidate never goes,
231 // whether or not its ref is gone yet.
232 var expires string
233 err = w.State.db.QueryRowContext(ctx, "SELECT expires_at FROM candidates WHERE repo=? AND ref=?", h.Repo, ref).Scan(&expires)
234 if errors.Is(err, sql.ErrNoRows) {
235 return nil, errPackRefused
236 }
237 if err != nil {
238 return nil, err
239 }
240 if expires != "" && expires <= stamp(time.Now()) {
241 return nil, errPackRefused
242 }
243 if got, err := w.git(ctx, nil, "--git-dir="+store, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}"); err != nil || got != cand {
244 return nil, errPackRefused
245 }
246 var out bytes.Buffer
247 if err := w.thinPack(ctx, store, base, cand, &limitWriter{w: &out, n: wire.MaxTransferBytes + 1}); err != nil {
248 return nil, err
249 }
250 return out.Bytes(), nil
251}
252
253// thinPack writes the thin pack of cand against base from store to out:
254// what an outbound transfer carries.
255func (w *Worker) thinPack(ctx context.Context, store, base, cand string, out io.Writer) error {
256 cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+store, "pack-objects", "--revs", "--thin", "--stdout", "-q")
257 cmd.Stdin, cmd.Stdout, cmd.Env = strings.NewReader(cand+"\n^"+base+"\n"), out, w.gitEnv()
258 if err := mac.StartOwn(cmd); err != nil {
259 return err
260 }
261 return cmd.Wait()
262}
263
264// packSize is the size of the thin pack an outbound transfer of cand
265// would carry.
266func (w *Worker) packSize(ctx context.Context, store, base, cand string) (int64, error) {
267 var n counter
268 err := w.thinPack(ctx, store, base, cand, &n)
269 return int64(n), err
270}
271
272// counter counts what is written to it.
273type counter int64
274
275func (c *counter) Write(p []byte) (int, error) { *c += counter(len(p)); return len(p), nil }
276
277// forget is the worker's forget_task: the kept sessions it released go,
278// and so do the task's candidates whose keep (none, or passed) is over;
279// the next keep's end is swept when it comes.
280func (w *Worker) forget(ctx context.Context, dirs []string) {
281 w.Engine.RemoveKept(dirs)
282 w.sweep(ctx)
283}
284
285// sweep removes what finished attempts left (their trees and their step
286// logs, once the instance acked their final report), kept sessions past
287// their keep or retention, and the refs of candidates whose task was
288// forgotten and whose keep has passed; then it sets itself to run again
289// at the next candidate's keep.
290func (w *Worker) sweep(ctx context.Context) {
291 if keys, err := w.State.finishedSteps(ctx); err == nil {
292 for _, r := range keys {
293 _ = os.RemoveAll(filepath.Join(w.stepsDir(), stepKey(r)))
294 _ = os.RemoveAll(filepath.Join(w.Engine.root(), stepKey(r)))
295 }
296 }
297 w.Engine.sweepKept(ctx, w.State)
298 defer w.sweepAtNextKeep(ctx)
299 rows, err := w.State.db.QueryContext(ctx, "SELECT repo, ref FROM candidates WHERE expires_at<>'' AND expires_at<=?", stamp(time.Now()))
300 if err != nil {
301 w.Engine.log("worker candidates", err)
302 return
303 }
304 var gone [][2]string
305 for rows.Next() {
306 var repo, ref string
307 if rows.Scan(&repo, &ref) == nil {
308 gone = append(gone, [2]string{repo, ref})
309 }
310 }
311 rows.Close()
312 for _, g := range gone {
313 w.Engine.log("worker candidates", w.dropCandidate(ctx, g[0], g[1]))
314 }
315}
316
317// workerSecrets are a Mac worker's known secrets: its runner credential,
318// every Claude token connection's token, and its enrolment key (whose
319// seed the seal key is made from) with the seal key's private half. A
320// token or key that is not there is skipped; any other failure to read
321// one is an error (nothing is scanned against a list with a hole).
322func workerSecrets(c runner.Config, bearer string) ([]string, error) {
323 out := []string{bearer}
324 bindings, err := runner.LoadBindings(c.AccountBindingsPath)
325 if err != nil && !errors.Is(err, fs.ErrNotExist) {
326 return nil, err
327 }
328 for _, b := range bindings {
329 if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken {
330 continue
331 }
332 raw, err := provider.ReadToken(b.ProviderHome)
333 if errors.Is(err, fs.ErrNotExist) {
334 continue
335 }
336 if err != nil {
337 return nil, err
338 }
339 out = append(out, string(raw))
340 clear(raw)
341 }
342 key, err := runner.ReadMachineKey(c.StateDir)
343 switch {
344 case errors.Is(err, fs.ErrNotExist):
345 case err != nil:
346 return nil, err
347 default:
348 out = append(out, string(key), string(key.Seed()))
349 if keys, err := sealbox.FromEd25519(key); err == nil {
350 out = append(out, string(keys.PrivateHalf()))
351 }
352 clear(key)
353 }
354 return out, nil
355}
356
357// sweepAtNextKeep runs the sweep when the soonest candidate keep ends.
358func (w *Worker) sweepAtNextKeep(ctx context.Context) {
359 var next sql.NullString
360 if err := w.State.db.QueryRowContext(ctx, "SELECT MIN(expires_at) FROM candidates WHERE expires_at>?", stamp(time.Now())).Scan(&next); err != nil || !next.Valid {
361 return
362 }
363 var ms int64
364 if _, err := fmt.Sscanf(next.String, "%d", &ms); err != nil {
365 return
366 }
367 w.sweepMu.Lock()
368 defer w.sweepMu.Unlock()
369 if w.sweepTimer != nil {
370 w.sweepTimer.Stop()
371 }
372 w.sweepTimer = time.AfterFunc(time.Until(time.UnixMilli(ms))+10*time.Millisecond, func() { w.sweep(ctx) })
373}
374