| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/base64" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "log/slog" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | // A task is done when it lands on the default branch: Equipo's own merge |
| 23 | // step reports that itself (mergestep.go), and a person may still merge |
| 24 | // it on Amadan. The instance asks the runner to watch a task's newest pushed |
| 25 | // candidate; about once a minute the runner reads each watched |
| 26 | // repository's default branch tip (one ls-remote), and only when the tip |
| 27 | // moved does it fetch and look whether the candidate landed: an ancestor |
| 28 | // of the tip (a merge or fast-forward), or every path the task changed |
| 29 | // now as the candidate has it (a squash). |
| 30 | |
| 31 | // seen_head is the task branch's head last reported (the candidate when |
| 32 | // the watch starts); any change is reported (FrameBranch). |
| 33 | const watchSchema = `CREATE TABLE IF NOT EXISTS watches (task_id TEXT PRIMARY KEY, person TEXT NOT NULL, repo TEXT NOT NULL, branch TEXT NOT NULL, candidate_sha TEXT NOT NULL, base_sha TEXT NOT NULL DEFAULT '', seen_tip TEXT NOT NULL DEFAULT '', seen_head TEXT NOT NULL DEFAULT '');` |
| 34 | |
| 35 | // AcceptWatch records a watch_merge exactly once: a candidate replaces |
| 36 | // the task's watch, an empty one ends it. |
| 37 | func (s *State) AcceptWatch(ctx context.Context, frameID string, w wire.WatchMergeCommand) error { |
| 38 | return s.tx(ctx, func(t *sql.Tx) error { |
| 39 | fresh, err := seen(t, frameID) |
| 40 | if err != nil || !fresh { |
| 41 | return err |
| 42 | } |
| 43 | if w.CandidateSHA == "" { |
| 44 | _, err = t.Exec("DELETE FROM watches WHERE task_id=?", w.TaskID) |
| 45 | return err |
| 46 | } |
| 47 | var base string |
| 48 | _ = t.QueryRow("SELECT base_sha FROM steps WHERE task_id=? AND base_sha<>'' ORDER BY created_at LIMIT 1", w.TaskID).Scan(&base) |
| 49 | _, err = t.Exec("INSERT INTO watches(task_id, person, repo, branch, candidate_sha, base_sha, seen_head) VALUES(?,?,?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET candidate_sha=excluded.candidate_sha, branch=excluded.branch, repo=excluded.repo, seen_tip='', seen_head=excluded.candidate_sha", w.TaskID, w.Person, w.Repo, w.Branch, w.CandidateSHA, base, w.CandidateSHA) |
| 50 | return err |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | type watch struct { |
| 55 | task, person, repo, branch, candidate, base, seen, head string |
| 56 | } |
| 57 | |
| 58 | func (s *State) watches(ctx context.Context) ([]watch, error) { |
| 59 | rows, err := s.db.QueryContext(ctx, "SELECT task_id, person, repo, branch, candidate_sha, base_sha, seen_tip, seen_head FROM watches ORDER BY repo, task_id") |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | defer rows.Close() |
| 64 | var out []watch |
| 65 | for rows.Next() { |
| 66 | var w watch |
| 67 | if err := rows.Scan(&w.task, &w.person, &w.repo, &w.branch, &w.candidate, &w.base, &w.seen, &w.head); err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | out = append(out, w) |
| 71 | } |
| 72 | return out, rows.Err() |
| 73 | } |
| 74 | |
| 75 | // landed reports a merged candidate and ends its watch, in one |
| 76 | // transaction with the durable report. |
| 77 | func (s *State) landed(ctx context.Context, w watch) error { |
| 78 | return s.tx(ctx, func(t *sql.Tx) error { |
| 79 | res, err := t.Exec("DELETE FROM watches WHERE task_id=? AND candidate_sha=?", w.task, w.candidate) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if n, _ := res.RowsAffected(); n != 1 { |
| 84 | return nil |
| 85 | } |
| 86 | return s.enqueue(t, wire.FrameMerged, "", wire.MergedReport{TaskID: w.task, CandidateSHA: w.candidate}) |
| 87 | }) |
| 88 | } |
| 89 | |
| 90 | // branchSeen reports the task branch's new head and records it, in one |
| 91 | // transaction with the durable report. |
| 92 | func (s *State) branchSeen(ctx context.Context, w watch, head string) error { |
| 93 | return s.tx(ctx, func(t *sql.Tx) error { |
| 94 | res, err := t.Exec("UPDATE watches SET seen_head=? WHERE task_id=? AND candidate_sha=? AND seen_head=?", head, w.task, w.candidate, w.head) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | if n, _ := res.RowsAffected(); n != 1 { |
| 99 | return nil |
| 100 | } |
| 101 | return s.enqueue(t, wire.FrameBranch, "", wire.BranchReport{TaskID: w.task, CandidateSHA: w.candidate, Head: head}) |
| 102 | }) |
| 103 | } |
| 104 | |
| 105 | // endWatch ends a task's watch for candidate without a report: the |
| 106 | // merge step that merged it reports it. |
| 107 | func (s *State) endWatch(ctx context.Context, task, candidate string) error { |
| 108 | _, err := s.db.ExecContext(ctx, "DELETE FROM watches WHERE task_id=? AND candidate_sha=?", task, candidate) |
| 109 | return err |
| 110 | } |
| 111 | |
| 112 | func (s *State) sawTip(ctx context.Context, w watch, tip string) error { |
| 113 | _, err := s.db.ExecContext(ctx, "UPDATE watches SET seen_tip=? WHERE task_id=? AND candidate_sha=?", tip, w.task, w.candidate) |
| 114 | return err |
| 115 | } |
| 116 | |
| 117 | // MergeWatch checks the watched branches. |
| 118 | type MergeWatch struct { |
| 119 | State *State |
| 120 | Clones *Clones |
| 121 | Git string |
| 122 | Owners []string |
| 123 | Notify func() |
| 124 | Logger *slog.Logger |
| 125 | Every time.Duration |
| 126 | |
| 127 | kick chan struct{} |
| 128 | once sync.Once |
| 129 | } |
| 130 | |
| 131 | func (m *MergeWatch) kicks() chan struct{} { |
| 132 | m.once.Do(func() { m.kick = make(chan struct{}, 1) }) |
| 133 | return m.kick |
| 134 | } |
| 135 | |
| 136 | // Kick checks at once (after every sync with the instance). |
| 137 | func (m *MergeWatch) Kick() { |
| 138 | select { |
| 139 | case m.kicks() <- struct{}{}: |
| 140 | default: |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // Loop checks every Every, and when kicked, until ctx ends. |
| 145 | func (m *MergeWatch) Loop(ctx context.Context) { |
| 146 | for { |
| 147 | select { |
| 148 | case <-ctx.Done(): |
| 149 | return |
| 150 | case <-time.After(m.Every): |
| 151 | case <-m.kicks(): |
| 152 | } |
| 153 | m.Check(ctx) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // Check looks once at each repository with a watch. |
| 158 | func (m *MergeWatch) Check(ctx context.Context) { |
| 159 | ws, err := m.State.watches(ctx) |
| 160 | if err != nil || len(ws) == 0 { |
| 161 | return |
| 162 | } |
| 163 | byRepo := map[string][]watch{} |
| 164 | for _, w := range ws { |
| 165 | byRepo[w.repo] = append(byRepo[w.repo], w) |
| 166 | } |
| 167 | sent := false |
| 168 | for repo, list := range byRepo { |
| 169 | cctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| 170 | names := make([]string, 0, len(list)) |
| 171 | for _, w := range list { |
| 172 | names = append(names, w.branch) |
| 173 | } |
| 174 | branch, tip, heads, err := m.Clones.Heads(cctx, repo, names) |
| 175 | if errors.Is(err, ErrEmptyRepo) { |
| 176 | // No default branch yet: nothing can have landed. |
| 177 | cancel() |
| 178 | continue |
| 179 | } |
| 180 | if err != nil { |
| 181 | cancel() |
| 182 | m.log("merge tip", fmt.Errorf("%s: %w", repo, err)) |
| 183 | continue |
| 184 | } |
| 185 | moved := false |
| 186 | for _, w := range list { |
| 187 | moved = moved || w.seen != tip |
| 188 | } |
| 189 | landed := map[string]bool{} |
| 190 | if moved { |
| 191 | if err := m.Clones.Ensure(cctx, repo); err != nil { |
| 192 | m.log("merge fetch", err) |
| 193 | } else { |
| 194 | for _, w := range list { |
| 195 | if m.merged(cctx, repo, branch, w) { |
| 196 | m.log("merge report", m.State.landed(ctx, w)) |
| 197 | landed[w.task], sent = true, true |
| 198 | continue |
| 199 | } |
| 200 | m.log("merge seen", m.State.sawTip(ctx, w, tip)) |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | // The task branch itself: any head but the candidate takes the |
| 205 | // task out of Ready to merge on the instance. |
| 206 | for _, w := range list { |
| 207 | if head := heads[w.branch]; !landed[w.task] && head != w.head { |
| 208 | m.log("branch report", m.State.branchSeen(ctx, w, head)) |
| 209 | sent = true |
| 210 | } |
| 211 | } |
| 212 | cancel() |
| 213 | } |
| 214 | if sent && m.Notify != nil { |
| 215 | m.Notify() |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | // merged reports whether w's candidate is on the default branch: an |
| 220 | // ancestor of its tip, or (a squash) every path the task changed has the |
| 221 | // same tree entry (mode, type and object, or absence) at the tip as at |
| 222 | // the candidate. Paths are read NUL-delimited. Anything git cannot |
| 223 | // answer is unknown, and unknown is never merged. |
| 224 | func (m *MergeWatch) merged(ctx context.Context, repo, branch string, w watch) bool { |
| 225 | git := func(args ...string) ([]byte, error) { |
| 226 | cmd := exec.CommandContext(ctx, m.Git, append([]string{"--git-dir=" + m.Clones.Path(repo), "--literal-pathspecs"}, args...)...) |
| 227 | env := workspace.GitEnvironment() |
| 228 | env["HOME"] = "/nonexistent" |
| 229 | for k, v := range env { |
| 230 | cmd.Env = append(cmd.Env, k+"="+v) |
| 231 | } |
| 232 | out, clipped, err := boundedOutput(cmd, 4<<20) |
| 233 | if clipped { |
| 234 | return nil, errors.New("output too large") |
| 235 | } |
| 236 | return out, err |
| 237 | } |
| 238 | tip := "refs/heads/" + branch |
| 239 | if _, err := git("cat-file", "-e", w.candidate+"^{commit}"); err != nil { |
| 240 | return false |
| 241 | } |
| 242 | if _, err := git("merge-base", "--is-ancestor", w.candidate, tip); err == nil { |
| 243 | return true |
| 244 | } |
| 245 | if w.base == "" { |
| 246 | return false |
| 247 | } |
| 248 | changed, err := git("diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-ext-diff", "--no-textconv", w.base, w.candidate, "--") |
| 249 | if err != nil || len(changed) == 0 { |
| 250 | return false |
| 251 | } |
| 252 | // diff-tree compares whole entries: a path differs if its mode, type |
| 253 | // or object differs, or it exists on one side only. |
| 254 | differ, err := git("diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-ext-diff", "--no-textconv", w.candidate, tip, "--") |
| 255 | if err != nil { |
| 256 | return false |
| 257 | } |
| 258 | other := map[string]bool{} |
| 259 | for _, p := range bytes.Split(differ, []byte{0}) { |
| 260 | other[string(p)] = true |
| 261 | } |
| 262 | for _, p := range bytes.Split(changed, []byte{0}) { |
| 263 | if len(p) > 0 && other[string(p)] { |
| 264 | return false |
| 265 | } |
| 266 | } |
| 267 | return true |
| 268 | } |
| 269 | |
| 270 | // log says err in its own words, redacted and bounded: git's and the |
| 271 | // state's, never a provider's. |
| 272 | func (m *MergeWatch) log(msg string, err error) { |
| 273 | if m.Logger != nil && err != nil { |
| 274 | m.Logger.Warn(msg, "err", runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit)) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // unbornDefault is the default branch's name when the hub does not say: |
| 279 | // the name a repository is created with, which its first merge creates. |
| 280 | const unbornDefault = "main" |
| 281 | |
| 282 | // Heads asks the remote, in one ls-remote, for its default branch, that |
| 283 | // branch's tip and the heads of the named branches (absent: gone). |
| 284 | func (c *Clones) Heads(ctx context.Context, repo string, branches []string) (string, string, map[string]string, error) { |
| 285 | remote, err := readRemote(ctx, c.Forge, repo) |
| 286 | if err != nil { |
| 287 | return "", "", nil, err |
| 288 | } |
| 289 | env := workspace.GitEnvironment() |
| 290 | env["HOME"] = "/nonexistent" |
| 291 | protocol := "https" |
| 292 | if filepath.IsAbs(remote.URL) { |
| 293 | protocol = "file" |
| 294 | } else if remote.GitPassword != "" { |
| 295 | env["GIT_CONFIG_COUNT"] = "10" |
| 296 | env["GIT_CONFIG_KEY_9"] = "http.extraHeader" |
| 297 | env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword)) |
| 298 | } |
| 299 | // main as well: when HEAD names no default (an empty repository, or a |
| 300 | // task branch a hub rebuild pointed it at), main decides, in this one |
| 301 | // request (the hub limits an agent's git requests). |
| 302 | args := []string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "ls-remote", "--symref", "--", remote.URL, "HEAD", "refs/heads/" + unbornDefault} |
| 303 | for _, b := range branches { |
| 304 | if validBranch(b) { |
| 305 | args = append(args, "refs/heads/"+b) |
| 306 | } |
| 307 | } |
| 308 | cmd := groupCommand(ctx, c.Git, args...) |
| 309 | cmd.Dir = c.Root |
| 310 | for k, v := range env { |
| 311 | cmd.Env = append(cmd.Env, k+"="+v) |
| 312 | } |
| 313 | var stderr bytes.Buffer |
| 314 | cmd.Stderr = &limitWriter{w: &stderr, n: 2 << 10} |
| 315 | out, clipped, err := boundedOutput(cmd, 1<<20) |
| 316 | if err != nil || clipped { |
| 317 | return "", "", nil, errors.Join(err, fmt.Errorf("ls-remote: %s", strings.TrimSpace(stderr.String()))) |
| 318 | } |
| 319 | branch, tip, heads := "", "", map[string]string{} |
| 320 | for _, line := range strings.Split(string(out), "\n") { |
| 321 | if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok { |
| 322 | b, _, _ := strings.Cut(rest, "\t") |
| 323 | if validBranch(b) { |
| 324 | branch = b |
| 325 | } |
| 326 | } else if sha, ref, ok := strings.Cut(line, "\t"); ok && shaPattern.MatchString(sha) { |
| 327 | if ref == "HEAD" { |
| 328 | tip = sha |
| 329 | } else if b, ok := strings.CutPrefix(ref, "refs/heads/"); ok { |
| 330 | heads[b] = sha |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | if branch == "" || taskBranch(branch) { |
| 335 | // No default at HEAD (none, or a task branch): main is the |
| 336 | // default; absent, it is unborn (ErrEmptyRepo), named main, and |
| 337 | // the task branches' heads are as read. |
| 338 | if sha, ok := heads[unbornDefault]; ok { |
| 339 | return unbornDefault, sha, heads, nil |
| 340 | } |
| 341 | return unbornDefault, "", heads, ErrEmptyRepo |
| 342 | } |
| 343 | if tip == "" { |
| 344 | return "", "", nil, ErrNoCreate |
| 345 | } |
| 346 | return branch, tip, heads, nil |
| 347 | } |
| 348 | |