package thin import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "context" "fmt" "slices" "strings" "time" "unicode/utf8" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/wire" ) // HostedCI is the hub's own CI as the primary reads it with the agent's // credential (release slice 1): whether the hub runs a repository's CI on // its machines, and its verdict on a branch's tip. type HostedCI interface { CIHosted(ctx context.Context, repo string) (bool, error) CIStatus(ctx context.Context, repo, branch, logs string) (forge.CIStatus, error) } // phaseHosted marks a checks attempt that waits for the hub's hosted CI: // it runs again after a restart instead of failing runner_restarted. const phaseHosted = "hosted" // Hosted failure logs remain diagnostic input for copy recovery. They never // certify base-run checks or select the primary checks executor. var hostedRead = 30 * time.Second var hostedWait = 60 * time.Minute func (e *Engineer) hostedChecks(ctx context.Context, r stepRow, rep wire.StepReport) wire.StepReport { if e.CI == nil { rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, wire.ChecksCannotRun, "checks_unavailable" return rep } cctx, cancel := context.WithTimeout(ctx, hostedRead) st, err := e.CI.CIStatus(cctx, r.Repo, r.Branch, forge.CILogsNone) cancel() if ctx.Err() != nil { rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true return rep } if err == nil && st.SHA == r.CandidateSHA && st.UpdatedAt > 0 { if out, ok := e.hostedVerdict(ctx, r, rep, st); ok { return out } } if since := e.O.State.deferredSince(context.WithoutCancel(ctx), r); !since.IsZero() && time.Since(since) >= hostedWait { rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, wire.ChecksCannotRun, "checks_timeout" rep.LogTail = fmt.Sprintf("Hosted CI gave no verdict on %s within %d minutes.", shortSHA(r.CandidateSHA), int(hostedWait/time.Minute)) return rep } rep.State = stepDeferred return rep } // hostedVerdict is the report for a verdict the hub gave on the // candidate, from that one snapshot (its failing logs only from a second // read of the very same run). ok is false while there is no verdict. func (e *Engineer) hostedVerdict(ctx context.Context, r stepRow, rep wire.StepReport, st forge.CIStatus) (wire.StepReport, bool) { done := func(outcome, reason string) (wire.StepReport, bool) { rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, outcome, reason rep.Hosted = &wire.HostedResult{Repo: r.Repo, Branch: r.Branch, SHA: st.SHA, State: st.State, ReportedAt: st.UpdatedAt, Failed: failedUnits(st.Steps)} return rep, true } where := "Hosted CI on " + forgekey.Display(r.Repo) + " at " + shortSHA(st.SHA) switch st.State { case wire.HostedSuccess: code := 0 rep.Gate, rep.ExitCode, rep.Output = wire.GateHosted, &code, where+": passed." rep.LogTail = rep.Output return done(wire.ChecksPassed, "") case wire.HostedFailure: code := 1 var logs []wire.CIUnit cctx, cancel := context.WithTimeout(ctx, hostedRead) full, err := e.CI.CIStatus(cctx, r.Repo, r.Branch, forge.CILogsFailed) cancel() if err == nil && full.SHA == st.SHA && full.State == st.State && full.UpdatedAt == st.UpdatedAt { logs = failedLogs(full.Steps) } head := where + ": failed.\n" if names := failedUnits(st.Steps); len(names) > 0 { head += "Failed: " + strings.Join(names, "; ") + "\n" } if s := strings.TrimSpace(st.Summary); s != "" { head += s + "\n" } // Every failing unit's share of the output, its failing lines // first: the fix round reads them all. rep.Gate, rep.ExitCode, rep.Output = wire.GateHosted, &code, head+wire.JoinCIUnits(logs, wire.MaxChecksOutput-len(head)) rep.LogTail = lastLines(rep.Output, stepTailLines, wire.MaxLogTail) return done(wire.ChecksFailed, "") case "skipped": rep.LogTail = where + ": no CI script." return done(wire.ChecksNone, "") case "lost", "stale": rep.LogTail = where + ": the run did not finish (" + st.State + ")." return done(wire.ChecksCannotRun, "checks_unavailable") } return rep, false } // failedUnits names what failed, finest first: a sharded step's failing // shards, else the step. At most wire.MaxHostedFailed names of // wire.MaxHostedName bytes. func failedUnits(steps []forge.CIStep) []string { out := []string{} add := func(name string) { if len(out) < wire.MaxHostedFailed { out = append(out, unitName(name)) } } for _, s := range steps { if s.State != wire.HostedFailure { continue } shards := slices.IndexFunc(s.Shards, func(sh forge.CIShard) bool { return sh.State == wire.HostedFailure }) >= 0 if !shards { add(s.Name) continue } for _, sh := range s.Shards { if sh.State == wire.HostedFailure { add(s.Name + " " + sh.Name) } } } return out } // failedLogs are the logs of the failing units the hub sent, each named // as failedUnits names a unit. func failedLogs(steps []forge.CIStep) []wire.CIUnit { var out []wire.CIUnit for _, s := range steps { if s.Log != "" { out = append(out, wire.CIUnit{Name: unitName(s.Name), Log: s.Log}) } for _, sh := range s.Shards { if sh.Log != "" { out = append(out, wire.CIUnit{Name: unitName(s.Name + " " + sh.Name), Log: sh.Log}) } } } return out } // unitName is a unit's name as the binding records it: one line, bounded. func unitName(name string) string { return clipName(strings.Join(strings.Fields(name), " ")) } func clipName(s string) string { for len(s) > wire.MaxHostedName { _, n := utf8.DecodeLastRuneInString(s) s = s[:len(s)-n] } return s } // tailBytes is the end of s within limit bytes, starting on a line. func tailBytes(s string, limit int) string { if limit <= 0 { return "" } if len(s) <= limit { return s } s = s[len(s)-limit:] if i := strings.IndexByte(s, '\n'); i >= 0 { s = s[i+1:] } return strings.ToValidUTF8(s, "") } func shortSHA(sha string) string { return sha[:min(len(sha), 7)] }