package thin import ( "bytes" "context" "database/sql" "encoding/base64" "errors" "fmt" "log/slog" "os/exec" "path/filepath" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/wire" ) // A task is done when it lands on the default branch: Equipo's own merge // step reports that itself (mergestep.go), and a person may still merge // it on Amadan. The instance asks the runner to watch a task's newest pushed // candidate; about once a minute the runner reads each watched // repository's default branch tip (one ls-remote), and only when the tip // moved does it fetch and look whether the candidate landed: an ancestor // of the tip (a merge or fast-forward), or every path the task changed // now as the candidate has it (a squash). // seen_head is the task branch's head last reported (the candidate when // the watch starts); any change is reported (FrameBranch). 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 '');` // AcceptWatch records a watch_merge exactly once: a candidate replaces // the task's watch, an empty one ends it. func (s *State) AcceptWatch(ctx context.Context, frameID string, w wire.WatchMergeCommand) error { return s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } if w.CandidateSHA == "" { _, err = t.Exec("DELETE FROM watches WHERE task_id=?", w.TaskID) return err } var base string _ = t.QueryRow("SELECT base_sha FROM steps WHERE task_id=? AND base_sha<>'' ORDER BY created_at LIMIT 1", w.TaskID).Scan(&base) _, 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) return err }) } type watch struct { task, person, repo, branch, candidate, base, seen, head string } func (s *State) watches(ctx context.Context) ([]watch, error) { 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") if err != nil { return nil, err } defer rows.Close() var out []watch for rows.Next() { var w watch if err := rows.Scan(&w.task, &w.person, &w.repo, &w.branch, &w.candidate, &w.base, &w.seen, &w.head); err != nil { return nil, err } out = append(out, w) } return out, rows.Err() } // landed reports a merged candidate and ends its watch, in one // transaction with the durable report. func (s *State) landed(ctx context.Context, w watch) error { return s.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("DELETE FROM watches WHERE task_id=? AND candidate_sha=?", w.task, w.candidate) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } return s.enqueue(t, wire.FrameMerged, "", wire.MergedReport{TaskID: w.task, CandidateSHA: w.candidate}) }) } // branchSeen reports the task branch's new head and records it, in one // transaction with the durable report. func (s *State) branchSeen(ctx context.Context, w watch, head string) error { return s.tx(ctx, func(t *sql.Tx) error { 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) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return nil } return s.enqueue(t, wire.FrameBranch, "", wire.BranchReport{TaskID: w.task, CandidateSHA: w.candidate, Head: head}) }) } // endWatch ends a task's watch for candidate without a report: the // merge step that merged it reports it. func (s *State) endWatch(ctx context.Context, task, candidate string) error { _, err := s.db.ExecContext(ctx, "DELETE FROM watches WHERE task_id=? AND candidate_sha=?", task, candidate) return err } func (s *State) sawTip(ctx context.Context, w watch, tip string) error { _, err := s.db.ExecContext(ctx, "UPDATE watches SET seen_tip=? WHERE task_id=? AND candidate_sha=?", tip, w.task, w.candidate) return err } // MergeWatch checks the watched branches. type MergeWatch struct { State *State Clones *Clones Git string Owners []string Notify func() Logger *slog.Logger Every time.Duration kick chan struct{} once sync.Once } func (m *MergeWatch) kicks() chan struct{} { m.once.Do(func() { m.kick = make(chan struct{}, 1) }) return m.kick } // Kick checks at once (after every sync with the instance). func (m *MergeWatch) Kick() { select { case m.kicks() <- struct{}{}: default: } } // Loop checks every Every, and when kicked, until ctx ends. func (m *MergeWatch) Loop(ctx context.Context) { for { select { case <-ctx.Done(): return case <-time.After(m.Every): case <-m.kicks(): } m.Check(ctx) } } // Check looks once at each repository with a watch. func (m *MergeWatch) Check(ctx context.Context) { ws, err := m.State.watches(ctx) if err != nil || len(ws) == 0 { return } byRepo := map[string][]watch{} for _, w := range ws { byRepo[w.repo] = append(byRepo[w.repo], w) } sent := false for repo, list := range byRepo { cctx, cancel := context.WithTimeout(ctx, 2*time.Minute) names := make([]string, 0, len(list)) for _, w := range list { names = append(names, w.branch) } branch, tip, heads, err := m.Clones.Heads(cctx, repo, names) if errors.Is(err, ErrEmptyRepo) { // No default branch yet: nothing can have landed. cancel() continue } if err != nil { cancel() m.log("merge tip", fmt.Errorf("%s: %w", repo, err)) continue } moved := false for _, w := range list { moved = moved || w.seen != tip } landed := map[string]bool{} if moved { if err := m.Clones.Ensure(cctx, repo); err != nil { m.log("merge fetch", err) } else { for _, w := range list { if m.merged(cctx, repo, branch, w) { m.log("merge report", m.State.landed(ctx, w)) landed[w.task], sent = true, true continue } m.log("merge seen", m.State.sawTip(ctx, w, tip)) } } } // The task branch itself: any head but the candidate takes the // task out of Ready to merge on the instance. for _, w := range list { if head := heads[w.branch]; !landed[w.task] && head != w.head { m.log("branch report", m.State.branchSeen(ctx, w, head)) sent = true } } cancel() } if sent && m.Notify != nil { m.Notify() } } // merged reports whether w's candidate is on the default branch: an // ancestor of its tip, or (a squash) every path the task changed has the // same tree entry (mode, type and object, or absence) at the tip as at // the candidate. Paths are read NUL-delimited. Anything git cannot // answer is unknown, and unknown is never merged. func (m *MergeWatch) merged(ctx context.Context, repo, branch string, w watch) bool { git := func(args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, m.Git, append([]string{"--git-dir=" + m.Clones.Path(repo), "--literal-pathspecs"}, args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } out, clipped, err := boundedOutput(cmd, 4<<20) if clipped { return nil, errors.New("output too large") } return out, err } tip := "refs/heads/" + branch if _, err := git("cat-file", "-e", w.candidate+"^{commit}"); err != nil { return false } if _, err := git("merge-base", "--is-ancestor", w.candidate, tip); err == nil { return true } if w.base == "" { return false } changed, err := git("diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-ext-diff", "--no-textconv", w.base, w.candidate, "--") if err != nil || len(changed) == 0 { return false } // diff-tree compares whole entries: a path differs if its mode, type // or object differs, or it exists on one side only. differ, err := git("diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-ext-diff", "--no-textconv", w.candidate, tip, "--") if err != nil { return false } other := map[string]bool{} for _, p := range bytes.Split(differ, []byte{0}) { other[string(p)] = true } for _, p := range bytes.Split(changed, []byte{0}) { if len(p) > 0 && other[string(p)] { return false } } return true } // log says err in its own words, redacted and bounded: git's and the // state's, never a provider's. func (m *MergeWatch) log(msg string, err error) { if m.Logger != nil && err != nil { m.Logger.Warn(msg, "err", runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit)) } } // unbornDefault is the default branch's name when the hub does not say: // the name a repository is created with, which its first merge creates. const unbornDefault = "main" // Heads asks the remote, in one ls-remote, for its default branch, that // branch's tip and the heads of the named branches (absent: gone). func (c *Clones) Heads(ctx context.Context, repo string, branches []string) (string, string, map[string]string, error) { remote, err := readRemote(ctx, c.Forge, repo) if err != nil { return "", "", nil, err } env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" protocol := "https" if filepath.IsAbs(remote.URL) { protocol = "file" } else if remote.GitPassword != "" { env["GIT_CONFIG_COUNT"] = "10" env["GIT_CONFIG_KEY_9"] = "http.extraHeader" env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(remote.Username()+":"+remote.GitPassword)) } // main as well: when HEAD names no default (an empty repository, or a // task branch a hub rebuild pointed it at), main decides, in this one // request (the hub limits an agent's git requests). args := []string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "ls-remote", "--symref", "--", remote.URL, "HEAD", "refs/heads/" + unbornDefault} for _, b := range branches { if validBranch(b) { args = append(args, "refs/heads/"+b) } } cmd := groupCommand(ctx, c.Git, args...) cmd.Dir = c.Root for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } var stderr bytes.Buffer cmd.Stderr = &limitWriter{w: &stderr, n: 2 << 10} out, clipped, err := boundedOutput(cmd, 1<<20) if err != nil || clipped { return "", "", nil, errors.Join(err, fmt.Errorf("ls-remote: %s", strings.TrimSpace(stderr.String()))) } branch, tip, heads := "", "", map[string]string{} for _, line := range strings.Split(string(out), "\n") { if rest, ok := strings.CutPrefix(line, "ref: refs/heads/"); ok { b, _, _ := strings.Cut(rest, "\t") if validBranch(b) { branch = b } } else if sha, ref, ok := strings.Cut(line, "\t"); ok && shaPattern.MatchString(sha) { if ref == "HEAD" { tip = sha } else if b, ok := strings.CutPrefix(ref, "refs/heads/"); ok { heads[b] = sha } } } if branch == "" || taskBranch(branch) { // No default at HEAD (none, or a task branch): main is the // default; absent, it is unborn (ErrEmptyRepo), named main, and // the task branches' heads are as read. if sha, ok := heads[unbornDefault]; ok { return unbornDefault, sha, heads, nil } return unbornDefault, "", heads, ErrEmptyRepo } if tip == "" { return "", "", nil, ErrNoCreate } return branch, tip, heads, nil }