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 "context"
5 "encoding/json"
6 "log/slog"
7 "net"
8 "net/http"
9 "os"
10 "path/filepath"
11 "strings"
12 "sync/atomic"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runner"
17 "amadan.net/oficina/equipo/internal/runner/mac"
18 "amadan.net/oficina/equipo/internal/runnerproto"
19 "amadan.net/oficina/equipo/internal/wire"
20 "github.com/coder/websocket"
21)
22
23// A Mac worker's start logs each phase at info, in order, through its
24// hello and the welcome: a hang shows as a phase that started and never
25// ended. The instance's first refusal is logged with its error and the
26// wait before the next try, and no line holds the bearer.
27func TestWorkerStartupLogs(t *testing.T) {
28 root := t.TempDir()
29 c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "equipo-runner")}
30 if err := os.Mkdir(c.StateDir, 0700); err != nil {
31 t.Fatal(err)
32 }
33 const bearer = "bearer-5f2c9a71d04e-never-logged"
34 credential, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: bearer, Role: wire.RoleWorker}})
35 if err := os.WriteFile(filepath.Join(c.StateDir, "credentials.json"), credential, 0600); err != nil {
36 t.Fatal(err)
37 }
38 // The Mac's tools, as scripts that print a version; xcodebuild and
39 // swift (fixed /usr/bin paths) are missing here, so they fail.
40 bin := filepath.Join(root, "bin")
41 if err := os.Mkdir(bin, 0700); err != nil {
42 t.Fatal(err)
43 }
44 env := map[string]string{}
45 for name, version := range map[string]string{"node": "v22.12.0", "srt": "0.0.81", "rg": "14.1.1", "claude": "2.1.312", "codex": "0.1.0"} {
46 p := filepath.Join(bin, name)
47 if err := os.WriteFile(p, []byte("#!/bin/sh\necho "+version+"\n"), 0700); err != nil {
48 t.Fatal(err)
49 }
50 env["EQUIPO_"+strings.ToUpper(name)+"_PATH"] = p
51 }
52 was := macUsers
53 macUsers = filepath.Join(root, "Users")
54 defer func() { macUsers = was }()
55
56 var dials atomic.Int32
57 conns := make(chan *websocket.Conn, 2)
58 l, err := net.Listen("tcp", "127.0.0.1:0")
59 if err != nil {
60 t.Fatal(err)
61 }
62 srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
63 if dials.Add(1) == 1 {
64 http.Error(w, "starting", http.StatusServiceUnavailable)
65 return
66 }
67 if r.URL.Path != wire.StreamPath || r.Header.Get("Authorization") != "Bearer "+bearer {
68 http.Error(w, "forbidden", http.StatusForbidden)
69 return
70 }
71 ws, err := websocket.Accept(w, r, nil)
72 if err != nil {
73 return
74 }
75 conns <- ws
76 <-r.Context().Done()
77 })}
78 go srv.Serve(l)
79 defer srv.Close()
80 c.Origin = "http://" + l.Addr().String()
81
82 logs := &syncBuffer{}
83 o := OptionsFromEnv(func(k string) string { return env[k] })
84 o.Version, o.Logger = "v-test", slog.New(slog.NewTextHandler(logs, nil))
85 h, err := newMacHost(c, o)
86 if err != nil {
87 t.Fatal(err)
88 }
89 // The probes' verdicts, without running the Mac's probes here.
90 h.probes.run = func(context.Context) mac.Report {
91 return mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: time.Now(), Probes: probesAll(wire.ProbeDenied)}
92 }
93 ctx, cancel := context.WithCancel(context.Background())
94 defer cancel()
95 done := make(chan error, 1)
96 go func() { done <- serveMac(ctx, c, o, h) }()
97
98 var ws *websocket.Conn
99 select {
100 case ws = <-conns:
101 case <-time.After(15 * time.Second):
102 t.Fatalf("never connected:\n%s", logs)
103 }
104 rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second)
105 _, raw, err := ws.Read(rctx)
106 rcancel()
107 if f, _, perr := wire.ParseFrame(raw); err != nil || perr != nil || f.Type != wire.FrameHello {
108 t.Fatalf("no hello: %v %s", err, raw)
109 }
110 welcome, _ := wire.NewFrame("i-welcome-1", wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: "R1", Protocol: wire.Protocol2, Role: wire.RoleWorker})
111 raw, _ = json.Marshal(welcome)
112 write(t, ws, raw)
113 // Answer the runner's goodbye at once.
114 ws.CloseRead(context.Background())
115 for deadline := time.Now().Add(10 * time.Second); !strings.Contains(logs.String(), "msg=welcome") || !strings.Contains(logs.String(), `msg="probes finished"`); {
116 if time.Now().After(deadline) {
117 t.Fatalf("no welcome or probes line:\n%s", logs)
118 }
119 time.Sleep(20 * time.Millisecond)
120 }
121 cancel()
122 if err := <-done; err != nil {
123 t.Fatalf("worker ended: %v", err)
124 }
125 out := logs.String()
126 t.Logf("a Mac worker's start:\n%s", out)
127
128 host := l.Addr().String()
129 order := []string{
130 `level=INFO msg="startup phase" phase=mac_host`,
131 `level=INFO msg=command cmd=/usr/bin/xcode-select args=-p took=`,
132 `level=INFO msg="startup phase done" phase=mac_host took=`,
133 `level=INFO msg="startup phase" phase=state_lock`,
134 `level=INFO msg="startup phase done" phase=state_lock took=`,
135 `level=INFO msg="startup phase" phase=claim_roots`,
136 `level=INFO msg="startup phase done" phase=claim_roots took=`,
137 `level=INFO msg="startup phase" phase=sweep`,
138 `level=INFO msg="startup phase done" phase=sweep took=`,
139 `level=INFO msg="startup phase" phase=credentials`,
140 `level=INFO msg="startup phase done" phase=credentials took=`,
141 `level=INFO msg="startup phase" phase=open_state`,
142 `level=INFO msg="startup phase done" phase=open_state took=`,
143 `level=INFO msg=connecting host=` + host + ` protocol=` + itoa(int64(wire.ProtocolCurrent)),
144 `level=WARN msg="runner stream" err=`,
145 `level=INFO msg=connecting host=` + host,
146 `level=INFO msg=connected host=` + host + ` took=`,
147 `level=INFO msg="capabilities gathering"`,
148 `level=INFO msg=command cmd=/usr/bin/xcodebuild args=-version took=`,
149 `level=INFO msg=command cmd=` + env["EQUIPO_NODE_PATH"] + ` args=--version took=`,
150 `level=INFO msg="capabilities gathered" took=`,
151 `level=INFO msg="hello sent" protocol=`,
152 `level=INFO msg=welcome protocol=2 role=worker generation=1`,
153 }
154 if n := strings.Count(out, `level=INFO msg="probes started"`); n != 1 {
155 t.Fatalf("probes started at info %d times: a run asked for again, verdicts the same, is debug:\n%s", n, out)
156 }
157 lines, at := strings.Split(out, "\n"), 0
158 for _, want := range order {
159 for at < len(lines) && !strings.Contains(lines[at], want) {
160 at++
161 }
162 if at == len(lines) {
163 t.Fatalf("missing or out of order: %s\n%s", want, out)
164 }
165 at++
166 }
167 // The claude planted at EQUIPO_CLAUDE_PATH is never run (spec §8.2).
168 if strings.Contains(out, env["EQUIPO_CLAUDE_PATH"]) {
169 t.Fatalf("an unpinned claude ran:\n%s", out)
170 }
171 // The dial failure: the error and the wait before the next try.
172 if !strings.Contains(out, "503") || !strings.Contains(out, "retry_in=") {
173 t.Fatalf("the dial failure says neither why nor when:\n%s", out)
174 }
175 // A failed command says how; the probes say names and verdicts only.
176 if !strings.Contains(out, `cmd=/usr/bin/xcodebuild args=-version`) || !strings.Contains(out, `msg="probes started"`) || !strings.Contains(out, `verdicts="P1=passed P2=denied`) {
177 t.Fatalf("command or probes lines:\n%s", out)
178 }
179 if strings.Contains(out, bearer) {
180 t.Fatalf("a line holds the bearer:\n%s", out)
181 }
182}
183
184// A command still running after slowCommand is logged while it runs,
185// with its arguments (a password's value withheld), and again when it
186// ends with how long it took.
187func TestMacSlowCommandLogged(t *testing.T) {
188 was := slowCommand
189 slowCommand = 50 * time.Millisecond
190 defer func() { slowCommand = was }()
191 logs := &syncBuffer{}
192 h := &macHost{log: slog.New(slog.NewTextHandler(logs, nil))}
193 if _, err := h.run(context.Background(), "/bin/sh", "-c", "sleep 0.3", "sh", "-w", "hunter2"); err != nil {
194 t.Fatal(err)
195 }
196 out := logs.String()
197 still, finished := strings.Index(out, `level=WARN msg="command still running" cmd=/bin/sh`), strings.Index(out, `level=WARN msg="slow command finished" cmd=/bin/sh`)
198 if still < 0 || finished < still || !strings.Contains(out, `args="-c sleep 0.3 sh -w [withheld]"`) || strings.Contains(out, "hunter2") {
199 t.Fatalf("slow command lines:\n%s", out)
200 }
201 // A quick command says nothing.
202 quiet := &syncBuffer{}
203 h.log = slog.New(slog.NewTextHandler(quiet, nil))
204 if _, err := h.run(context.Background(), "/bin/sh", "-c", "true"); err != nil || quiet.String() != "" {
205 t.Fatalf("a quick command logged: %v %q", err, quiet.String())
206 }
207}
208
209// Why P2's srt run failed reaches runner.log at WARN through the probes'
210// host; a host without a log says nothing and does not fail.
211func TestMacP2FailureLogged(t *testing.T) {
212 logs := &syncBuffer{}
213 h := &macHost{log: slog.New(slog.NewTextHandler(logs, nil))}
214 h.probeHost("v1", nil).Warn("p2 srt run failed", "phase", "test build", "exit", 65)
215 if out := logs.String(); !strings.Contains(out, `level=WARN msg="p2 srt run failed" phase="test build" exit=65`) {
216 t.Fatalf("runner.log:\n%s", out)
217 }
218 (&macHost{}).probeHost("v1", nil).Warn("p2 srt run failed")
219}
220