package pickupclient
import (
"context"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"craftdesign.group/quarry/internal/nextstep"
)
// quarry land --stack: land a stack that is already open, from the top
// rung down, as one act of the forge's (landing.land). It pushes and
// opens nothing. The forge answers for the walk as a whole (what landed,
// the rung it stopped at and why, whether it armed the top to land the
// stack when every rung is green); the per-rung reading below is that
// answer laid over the rungs landing.get names.
// landRung is one rung of a stack as quarry land names it.
type landRung struct {
Number int `json:"number"`
Branch string `json:"branch"`
}
// landStrata is landing.get's `stack`: the chain the landing belongs to,
// bottom-up.
type landStrata struct {
Segments []landSeg `json:"segments"`
}
type landSeg struct {
ID string `json:"id"`
Number int `json:"number"`
Branch string `json:"branch"`
Target string `json:"target"`
State string `json:"state"`
Position int `json:"position"`
CI string `json:"ci"`
Author string `json:"author"`
}
func (s landStrata) rungs() []landRung {
out := make([]landRung, 0, len(s.Segments))
for _, g := range s.Segments {
out = append(out, landRung{Number: g.Number, Branch: g.Branch})
}
return out
}
// finalTarget is the branch the landing's stack lands on: where its
// bottom rung's target has already landed, else that target.
func (g landingState) finalTarget() string {
switch {
case g.LandsOn != "":
return g.LandsOn
case len(g.Stack.Segments) > 0:
return g.Stack.Segments[0].Target
}
return g.Landing.Target
}
func rungName(r landRung) string {
if r.Number > 0 {
return "!" + strconv.Itoa(r.Number)
}
return r.Branch
}
// stackLine names a stack bottom-up to the branch it lands on.
func stackLine(rungs []landRung, final string) string {
names := make([]string, 0, len(rungs)+1)
for _, r := range rungs {
names = append(names, rungName(r))
}
return strings.Join(append(names, final), " -> ")
}
type stackCtx struct {
a landArgs
v voice
base *url.URL
token string
repo string
address string
root string
asJSON bool
fail func(error) int
}
type stackRungOut struct {
Number int `json:"number"`
ID string `json:"id"`
Branch string `json:"branch"`
Author string `json:"author,omitempty"`
// State is landed, armed (lands with the stack once every rung is
// green), stopped, held (nothing lands while another rung is
// refused) or not_reached.
State string `json:"state"`
Reason string `json:"reason,omitempty"`
Next *nextstep.Next `json:"next,omitempty"`
}
type landStackJSON struct {
OK bool `json:"ok"`
Code string `json:"code,omitempty"`
Error string `json:"error,omitempty"`
Host string `json:"host"`
Repo string `json:"repo"`
Address string `json:"address"`
Top int `json:"top"`
ID string `json:"id"`
FinalTarget string `json:"finalTarget"`
Rungs []stackRungOut `json:"rungs"`
Armed bool `json:"armed"`
// Outcome is landed, armed or stopped for the forge's answer, and
// with --wait landed, failed, stopped, unarmed or timeout.
Outcome string `json:"outcome"`
StoppedAt int `json:"stoppedAt,omitempty"`
Reason string `json:"reason,omitempty"`
Next *nextstep.Next `json:"next"`
}
// stackRungOutcome is one rung's verdict while waiting for a stack to
// land: "landed", "failed", "stopped" (a run was cancelled and none is
// going), "unarmed" (the top, which carries the arm, lost it) or "" (still
// going). A rung's tip is not known here, so its verdict stands for it.
func stackRungOutcome(g landingState, top bool) string {
switch {
case g.Landing.State == "accepted":
return "landed"
case g.Landing.State != "" && g.Landing.State != "open":
return "failed"
case g.Landing.CI == "ci-fail" && !g.Stale && !g.Untested:
return "failed"
case g.Landing.CI != "ci-pass" && !g.Stale && g.stoppedOn(""):
return "stopped"
case top && g.Landing.AutoBy == "":
return "unarmed"
}
return ""
}
func (e *Env) landStackNow(ctx, short context.Context, c stackCtx) int {
a, v, base, repo := c.a, c.v, c.base, c.repo
rt := "/r/" + repo + "/landing/"
topID := strings.TrimPrefix(a.top, "!")
if topID == "" {
// The stack this checkout's branch is the top of.
tout, terr := e.Run(ctx, c.root, nil, []string{"timeline", "-n", "1", "-F", "oneline", "-c"})
last, found := parseCheckinLine(tout)
if terr != nil || !found {
return v.refuse(1, "no_branch", "this checkout's branch could not be read", false,
&nextstep.Next{Say: "Name the top rung: quarry land --stack !N.", Cmd: "quarry status"})
}
me, err := e.readMe(short, base, c.token)
if err != nil {
return c.fail(err)
}
var list struct {
Landings []struct {
ID string `json:"id"`
Branch string `json:"branch"`
Author string `json:"author"`
SupersededBy string `json:"superseded_by"`
} `json:"landings"`
}
if err := e.getJSON(short, base, c.token, "/r/"+repo+"/landing", url.Values{"state": {"open"}, "limit": {"200"}}, &list); err != nil {
var se statusError
if errors.As(err, &se) && se == 404 {
err = errNoSuchRepo
}
return c.fail(err)
}
for _, l := range list.Landings {
if l.Branch == last.Branch && l.SupersededBy == "" && strings.EqualFold(l.Author, me.Name) {
topID = l.ID
break
}
}
if topID == "" {
return v.refuse(1, "no_landing", "you have no open landing on "+show(last.Branch), false,
&nextstep.Next{Say: "Open it first, or name the top rung.", Cmd: "quarry land"})
}
}
before, err := e.readLanding(short, base, c.token, repo, topID)
if err != nil {
var se statusError
if errors.As(err, &se) && se == 404 {
return v.refuse(1, "no_landing", "no landing "+show(a.top)+" in "+repo, false,
&nextstep.Next{Say: "List yours.", Cmd: "quarry status"})
}
return c.fail(err)
}
top := landSeg{ID: before.Landing.ID, Number: before.Landing.Number, Branch: before.Landing.Branch, Target: before.Landing.Target, Author: before.Landing.Author}
// landing.land arms the top as the caller, so the top must be the
// caller's own, as plain land holds. Lower rungs by others land with
// the stack (the forge's stack semantics) and are listed below.
me, err := e.readMe(short, base, c.token)
if err != nil {
return c.fail(err)
}
if !strings.EqualFold(top.Author, me.Name) {
return v.refuse(1, "not_yours", "!"+strconv.Itoa(top.Number)+" on "+show(top.Branch)+" is "+show(top.Author)+"'s landing, not yours; landing it would be acting on their work", false,
&nextstep.Next{Say: "Land a stack whose top is your own, or ask " + top.Author + " to land theirs.", Cmd: "quarry status"})
}
// The rungs this land is for: the stack up to and including the top.
rungs := []landSeg{top}
for _, g := range before.Stack.Segments {
if g.ID == top.ID {
rungs = nil
for _, h := range before.Stack.Segments {
if h.Position <= g.Position {
rungs = append(rungs, h)
}
}
break
}
}
final := before.finalTarget()
line := make([]landRung, 0, len(rungs))
for _, r := range rungs {
line = append(line, landRung{Number: r.Number, Branch: r.Branch})
}
res := landStackJSON{Host: base.Host, Repo: repo, Address: c.address, Top: top.Number, ID: top.ID, FinalTarget: final}
say := func(f string, x ...any) {
if !c.asJSON {
fmt.Fprintf(e.Stdout, f, x...)
}
}
say("stack %s\n", show(stackLine(line, final)))
for _, r := range rungs {
say(" %s by %s\n", show(rungName(landRung{r.Number, r.Branch})), show(r.Author))
}
step, stopStep := context.WithTimeout(ctx, 60*time.Second)
defer stopStep()
var landed struct {
Landed []string `json:"landed"`
Stopped string `json:"stopped"`
Reason string `json:"reason"`
Armed []string `json:"armed"`
Settled string `json:"settled"`
}
if err := e.postJSON(step, base, c.token, rt+url.PathEscape(topID)+"/land", map[string]any{}, &landed); err != nil {
return c.fail(err)
}
isLanded := map[string]bool{}
for _, id := range landed.Landed {
isLanded[id] = true
}
armed := len(landed.Armed) > 0
res.Armed = armed
reached := false // past the rung the walk stopped at
for _, r := range rungs {
o := stackRungOut{Number: r.Number, ID: r.ID, Branch: r.Branch, Author: r.Author}
switch {
case isLanded[r.ID] || landed.Settled == "accepted":
o.State = "landed"
case landed.Settled != "":
o.State, o.Reason = "stopped", "it is "+landed.Settled
reached = true
case landed.Stopped == r.ID:
o.State, o.Reason = "stopped", landed.Reason
if armed {
o.State = "armed"
}
reached = true
if g, gerr := e.readLanding(step, base, c.token, repo, r.ID); gerr == nil {
o.Next = g.Waiting.Next
}
case armed:
o.State = "armed"
case reached:
o.State = "not_reached"
case landed.Stopped != "":
o.State = "held"
default:
o.State, o.Reason = "stopped", "the forge did not say why"
}
res.Rungs = append(res.Rungs, o)
}
// Rungs the forge landed that the earlier read did not list (the
// stack changed in between, or a base whose target landed): they are
// below what was read, so they go first. Their number is unknown.
inRead := map[string]bool{}
for _, r := range rungs {
inRead[r.ID] = true
}
var extra []stackRungOut
for _, id := range landed.Landed {
if !inRead[id] {
extra = append(extra, stackRungOut{ID: id, State: "landed"})
}
}
res.Rungs = append(extra, res.Rungs...)
res.Outcome = "landed"
for _, o := range res.Rungs {
switch {
case o.State == "stopped" || o.State == "held" || o.State == "not_reached":
res.Outcome = "stopped"
case o.State == "armed" && res.Outcome == "landed":
res.Outcome = "armed"
}
if o.State == "stopped" && res.StoppedAt == 0 {
res.StoppedAt, res.Reason, res.Next = o.Number, o.Reason, o.Next
}
}
// The forge's own account of where the walk stopped stands even when
// that rung was not in the earlier read.
if landed.Stopped != "" {
if !armed {
res.Outcome = "stopped"
}
if res.StoppedAt == 0 {
if g, gerr := e.readLanding(step, base, c.token, repo, landed.Stopped); gerr == nil {
res.StoppedAt = g.Landing.Number
}
}
if res.Reason == "" {
res.Reason = landed.Reason
}
}
reasonShown := false
for _, o := range res.Rungs {
name := rungName(landRung{o.Number, o.Branch})
if o.Number == 0 && o.Branch == "" {
name = o.ID
}
switch o.State {
case "landed":
say(" %s landed\n", show(name))
case "armed":
say(" %s armed, waiting: it lands with the stack once every rung is green\n", show(name))
case "stopped":
say(" %s stopped\n", show(name))
case "held":
say(" %s held: nothing lands while %s is refused\n", show(name), show(landed.Stopped))
default:
say(" %s not reached\n", show(name))
}
if o.Reason != "" {
say(" %s\n", show(o.Reason))
reasonShown = reasonShown || o.Reason == res.Reason
}
if n := o.Next; n != nil {
say(" next %s\n", show(n.Say))
if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
say(" run %s\n", show(n.Cmd))
}
}
}
if res.Reason != "" && !reasonShown {
say(" %s\n", show(res.Reason))
}
code := 0
if res.Outcome == "stopped" {
code = 1
if res.Code = "stopped"; res.Reason != "" {
res.Error = show(res.Reason)
}
}
if a.wait && res.Outcome == "armed" {
code = e.waitStack(ctx, c, &res, rungs, say)
}
res.OK = code == 0
if c.asJSON {
v.print(res)
}
return code
}
// waitStack follows an armed stack until every rung has landed, one
// fails, is cancelled or loses the top's arm, or the --wait limit passes.
func (e *Env) waitStack(ctx context.Context, c stackCtx, res *landStackJSON, rungs []landSeg, say func(string, ...any)) int {
base, repo := c.base, c.repo
limit := e.WaitMax
if limit <= 0 {
limit = apiWaitLimit
}
wctx, wstop := context.WithTimeout(ctx, limit)
defer wstop()
topName := "!" + strconv.Itoa(res.Top)
lastSay := ""
var bad landingState
var badRung landSeg
for {
all, failed := true, ""
for i, r := range rungs {
rctx, rstop := context.WithTimeout(wctx, 30*time.Second)
g, err := e.readLanding(rctx, base, c.token, repo, r.ID)
rstop()
if err != nil {
if wctx.Err() != nil {
res.Outcome = "timeout"
break
}
return c.fail(err)
}
if g.Waiting.Say != "" && g.Waiting.Say != lastSay && i == len(rungs)-1 {
lastSay = g.Waiting.Say
say(" %s\n", show(lastSay))
}
if o := stackRungOutcome(g, i == len(rungs)-1); o != "landed" {
all = false
if o != "" && failed == "" {
failed, bad, badRung = o, g, r
}
}
}
switch {
case res.Outcome == "timeout":
case all:
res.Outcome = "landed"
case failed != "":
res.Outcome = failed
}
if res.Outcome == "landed" || failed != "" || res.Outcome == "timeout" {
break
}
sctx, sstop := context.WithTimeout(wctx, landSlice)
werr := e.apiWaitEvent(sctx, base, c.token, "/r/"+repo+"/events/stream")
sstop()
if wctx.Err() != nil {
res.Outcome = "timeout"
break
}
if werr != nil && sctx.Err() == nil && e.Sleep(wctx, 3*time.Second) != nil {
res.Outcome = "timeout"
break
}
}
for i := range res.Rungs {
if res.Outcome == "landed" {
res.Rungs[i].State = "landed"
}
}
name := rungName(landRung{badRung.Number, badRung.Branch})
switch res.Outcome {
case "landed":
say("Landed the whole stack, up to %s.\n", show(topName))
return 0
case "failed":
res.StoppedAt = badRung.Number
res.Reason, res.Next = failWord(bad), bad.Waiting.Next
say("Not landing the stack: %s: %s.\n", show(name), show(res.Reason))
case "stopped":
res.StoppedAt = badRung.Number
res.Reason = "a check run was cancelled, so no answer is coming"
res.Next = &nextstep.Next{Say: "Re-run it from the landing page, or push again; the stack stays armed."}
say("Not landing the stack: %s: %s.\n", show(name), res.Reason)
case "unarmed":
why := bad.AutoLapsed
if why == "" {
why = bad.Waiting.Say
}
res.StoppedAt, res.Reason, res.Next = badRung.Number, show(why), bad.Waiting.Next
say("Not landing the stack: %s is no longer armed. %s\n", show(topName), show(why))
case "timeout":
res.Next = &nextstep.Next{Say: "Still armed; look again.", Cmd: "quarry status " + topName}
say("Still waiting after %s; the stack is armed.\n", limit)
say(" next quarry status %s\n", topName)
return 3
}
if n := res.Next; n != nil && res.Outcome != "stopped" {
say(" next %s\n", show(n.Say))
if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
say(" run %s\n", show(n.Cmd))
}
}
res.Code = res.Outcome
return 1
}