cli: link create stops on permanent answers, bounded wait
Fix round 1 of Task 9 (Astra). homeLinkStatus keeps getJSON's status beside an error, so a console-moved redirect, another 4xx or an undecodable answer ends link create with the console's message; only no answer, 5xx, 429 or a cut-short body are retried. The wait stops after 12 minutes (CLIAuthTTL plus a margin) with a draft pointing at carlos link status. LD-C56 without its home name is now its own draft constant.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+116
−9
apimode.go+13 −5link_cli.go+31 −2link_cli_test.go+72 −2
diff --git a/apimode.go b/apimode.go| index 55206afbd..25eaf8a43 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -5984,10 +5984,17 @@ type apiLinkViewApp struct { |
| URL string `json:"url"` |
| } |
| +// linkDecodeError is a complete 2xx answer this CLI could not decode: a |
| +// console speaking another shape, which waiting will not change. |
| +type linkDecodeError struct{ err error } |
| + |
| +func (e *linkDecodeError) Error() string { return copyLinkUnreadable + ": " + e.err.Error() } |
| +func (e *linkDecodeError) Unwrap() error { return e.err } |
| + |
| // decodeLinkAnswer reads a 2xx answer into out. |
| func decodeLinkAnswer(body []byte, out any) error { |
| if err := json.Unmarshal(body, out); err != nil { |
| - return fmt.Errorf("%s: %w", copyLinkUnreadable, err) |
| + return &linkDecodeError{err} |
| } |
| return nil |
| } |
| @@ -6005,14 +6012,15 @@ func (s *apiSession) homeLinkStart(ctx context.Context, to, name string) (apiLin |
| return out, decodeLinkAnswer(body, &out) |
| } |
| -// homeLinkStatus is GET /api/cli/link. It hands back the status too (0 |
| -// when there was no answer), so the create's wait can tell a hiccup from a |
| -// refusal. |
| +// homeLinkStatus is GET /api/cli/link. It hands back the status as |
| +// getJSON gave it (0 when there was no answer; set beside an error for a |
| +// console-moved redirect or a body that could not be read), so the |
| +// create's wait can tell a hiccup from a refusal. |
| func (s *apiSession) homeLinkStatus(ctx context.Context) (apiHomeLink, int, error) { |
| var out apiHomeLink |
| status, body, err := s.getJSON(ctx, "/api/cli/link") |
| if err != nil { |
| - return out, 0, err |
| + return out, status, err |
| } |
| if status != http.StatusOK { |
| return out, status, apiErrorFromBody(status, body) |
diff --git a/link_cli.go b/link_cli.go| index 1e4202d2c..7661d6d59 100644 |
| --- a/link_cli.go |
| +++ b/link_cli.go |
| @@ -78,6 +78,11 @@ const ( |
| // create: the home console no longer reports the request it started |
| // (it restarted while waiting). |
| copyLinkCreateLost = "the console no longer has this link request. run carlos link create again" |
| + // status: LD-C56 without its home name, when the serving console could |
| + // not be asked for it. |
| + copyLinkStatusNoHome = "linked to {account} on {console}" |
| + // create: stopped waiting after the approval code's lifetime. |
| + copyLinkCreateTimedOut = "stopped waiting for approval. run carlos link status to see whether the link was made" |
| // status, not linked: a request is waiting for approval. |
| copyLinkStatusRequestPending = "a link request is waiting for approval" |
| // status: a remove got 202 and the serving console has not cut the |
| @@ -123,6 +128,26 @@ func linkRefused(err error) { |
| // console whether the link was saved. Tests shorten it. |
| var linkCreatePollEvery = 2 * time.Second |
| +// linkCreateWaitFor bounds that wait: the approval code's lifetime on the |
| +// serving console (CLIAuthTTL, 10 minutes) plus a margin for the home |
| +// console's own last poll. Tests shorten it. |
| +var linkCreateWaitFor = 12 * time.Minute |
| + |
| +// linkWaitTemporary reports whether a failed GET /api/cli/link is worth |
| +// asking again: no answer, an answer cut short, a 5xx or a 429. Anything |
| +// else (a console-moved redirect, any other refusal, an answer in a shape |
| +// this CLI cannot read) will not change by waiting. |
| +func linkWaitTemporary(status int, err error) bool { |
| + var decode *linkDecodeError |
| + switch { |
| + case status == 0, status >= http.StatusInternalServerError, status == http.StatusTooManyRequests: |
| + return true |
| + case status >= 200 && status < 300: |
| + return !errors.As(err, &decode) // a body that could not be read |
| + } |
| + return false |
| +} |
| + |
| // RunLink runs `carlos link` from its subtree; tests call it directly. |
| func RunLink(args []string) { |
| clireg.Dispatch(linkCommand(), args) |
| @@ -238,7 +263,11 @@ func linkCreate(ctx context.Context, sess *apiSession, to, name string, out io.W |
| fmt.Fprintln(out, fillLinkCopy(copyLD52, "verification_uri", started.VerificationURI)) |
| fmt.Fprintln(out, fillLinkCopy(copyLD53, "user_code", started.UserCode)) |
| fmt.Fprintln(out, copyLD54) |
| + deadline := time.Now().Add(linkCreateWaitFor) |
| for { |
| + if !time.Now().Before(deadline) { |
| + return errors.New(copyLinkCreateTimedOut) |
| + } |
| select { |
| case <-ctx.Done(): |
| return ctx.Err() |
| @@ -246,7 +275,7 @@ func linkCreate(ctx context.Context, sess *apiSession, to, name string, out io.W |
| } |
| l, status, err := sess.homeLinkStatus(ctx) |
| switch { |
| - case err != nil && (status == 0 || status >= http.StatusInternalServerError): |
| + case err != nil && linkWaitTemporary(status, err): |
| // A hiccup is not a failed link: the person may be |
| // approving right now. |
| continue |
| @@ -302,7 +331,7 @@ func linkStatus(ctx context.Context, sess *apiSession, out io.Writer) error { |
| if l.Name == "" { |
| // The serving console could not be asked for the home's name: |
| // the line without it, never an empty name. |
| - line = strings.TrimSuffix(copyLD56, " as {home}") |
| + line = copyLinkStatusNoHome |
| } |
| fmt.Fprintln(out, fillLinkCopy(line, "account", l.Account, "console", l.Console, "home", l.Name)) |
| if l.ServingError != "" { |
diff --git a/link_cli_test.go b/link_cli_test.go| index f2b39bfdf..15691fb44 100644 |
| --- a/link_cli_test.go |
| +++ b/link_cli_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "bytes" |
| "context" |
| "encoding/json" |
| + "errors" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -135,6 +136,7 @@ func TestLinkCreatePrintsApprovalAndWaits(t *testing.T) { |
| pending, |
| // A hiccup while the person approves is not a failed link. |
| jsonAnswer(http.StatusServiceUnavailable, map[string]string{"error": "the link could not be read just now. try again"}), |
| + jsonAnswer(http.StatusTooManyRequests, map[string]string{"error": "too many requests"}), |
| pending, |
| jsonAnswer(http.StatusOK, map[string]any{"linked": true, "console": testServing, "account": "shop", |
| "name": "pi", "box": "", "state": "", "apps": []any{}}), |
| @@ -153,8 +155,8 @@ func TestLinkCreatePrintsApprovalAndWaits(t *testing.T) { |
| if b := fc.body("POST /api/cli/link/start"); b["to"] != testServing || b["name"] != "pi" { |
| t.Fatalf("start body = %v", b) |
| } |
| - if n := fc.polls.Load(); n != 4 { |
| - t.Fatalf("polled %d times, want 4", n) |
| + if n := fc.polls.Load(); n != 5 { |
| + t.Fatalf("polled %d times, want 5", n) |
| } |
| } |
| @@ -189,6 +191,74 @@ func TestLinkCreateReportsHowTheRequestEnded(t *testing.T) { |
| } |
| } |
| +// TestLinkCreateStopsOnPermanentAnswers: a status answer that waiting |
| +// will not change ends the wait at once with what the console said. A |
| +// console-moved redirect is the case getJSON answers with a status and an |
| +// error together. |
| +func TestLinkCreateStopsOnPermanentAnswers(t *testing.T) { |
| + fastLinkPolls(t) |
| + for _, tc := range []struct { |
| + name string |
| + status func(http.ResponseWriter) |
| + check func(t *testing.T, err error) |
| + }{ |
| + {"console moved", func(w http.ResponseWriter) { |
| + w.Header().Set("Location", "https://new.example.com/api/cli/link") |
| + w.WriteHeader(http.StatusPermanentRedirect) |
| + }, func(t *testing.T, err error) { |
| + var moved *consoleMovedError |
| + if !errors.As(err, &moved) || moved.To != "https://new.example.com" || |
| + !strings.Contains(err.Error(), "carlos auth login --console https://new.example.com") { |
| + t.Fatalf("err = %v, want the console-moved message", err) |
| + } |
| + }}, |
| + {"refused", jsonAnswer(http.StatusForbidden, map[string]string{"error": "not yours"}), func(t *testing.T, err error) { |
| + if err == nil || err.Error() != "not yours" { |
| + t.Fatalf("err = %v, want the console's refusal", err) |
| + } |
| + }}, |
| + {"unreadable", func(w http.ResponseWriter) { w.Write([]byte("<html>")) }, func(t *testing.T, err error) { |
| + if err == nil || !strings.HasPrefix(err.Error(), copyLinkUnreadable) { |
| + t.Fatalf("err = %v, want %q", err, copyLinkUnreadable) |
| + } |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fc := newFakeLinkConsole(t) |
| + fc.on("POST /api/cli/link/start", http.StatusOK, map[string]string{ |
| + "verification_uri": testApprove, "user_code": "ABCD-1234"}) |
| + fc.statuses = []func(http.ResponseWriter){tc.status} |
| + err := linkCreate(context.Background(), fc.session(), testServing, "", io.Discard) |
| + tc.check(t, err) |
| + if n := fc.polls.Load(); n != 1 { |
| + t.Fatalf("polled %d times, want 1: a permanent answer is not retried", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestLinkCreateGivesUpAfterTheCodesLifetime: temporary failures are |
| +// tolerated only until the approval code could have expired. |
| +func TestLinkCreateGivesUpAfterTheCodesLifetime(t *testing.T) { |
| + fastLinkPolls(t) |
| + orig := linkCreateWaitFor |
| + linkCreateWaitFor = 30 * time.Millisecond |
| + t.Cleanup(func() { linkCreateWaitFor = orig }) |
| + fc := newFakeLinkConsole(t) |
| + fc.on("POST /api/cli/link/start", http.StatusOK, map[string]string{ |
| + "verification_uri": testApprove, "user_code": "ABCD-1234"}) |
| + fc.statuses = []func(http.ResponseWriter){ |
| + jsonAnswer(http.StatusServiceUnavailable, map[string]string{"error": "the link could not be read just now. try again"}), |
| + } |
| + err := linkCreate(context.Background(), fc.session(), testServing, "", io.Discard) |
| + if err == nil || err.Error() != copyLinkCreateTimedOut { |
| + t.Fatalf("err = %v, want %q", err, copyLinkCreateTimedOut) |
| + } |
| + if n := fc.polls.Load(); n < 2 { |
| + t.Fatalf("polled %d times: the 503s should have been retried until the deadline", n) |
| + } |
| +} |
| + |
| func TestLinkCreateStartRefused(t *testing.T) { |
| fc := newFakeLinkConsole(t) |
| refusal := "this deployment is already linked to shop on " + testServing + ". run carlos link remove first to link it somewhere else" |