|
| 1 | +package cmdutil |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "regexp" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// JSONErrorIssue mirrors the issue shape used by auth check, sql, and import |
| 13 | +// d1 responses: a stable machine-readable code plus the human message. |
| 14 | +type JSONErrorIssue struct { |
| 15 | + Code string `json:"code"` |
| 16 | + Message string `json:"message"` |
| 17 | +} |
| 18 | + |
| 19 | +// JSONErrorResponse is the fallback JSON envelope for unhandled command |
| 20 | +// errors. It follows the same schema as command-specific error responses: |
| 21 | +// status, error, issues (code + message), next_steps. |
| 22 | +type JSONErrorResponse struct { |
| 23 | + Status string `json:"status"` |
| 24 | + Error string `json:"error"` |
| 25 | + Issues []JSONErrorIssue `json:"issues"` |
| 26 | + NextSteps []string `json:"next_steps"` |
| 27 | +} |
| 28 | + |
| 29 | +// Code returns the classification code of the first issue. |
| 30 | +func (r JSONErrorResponse) Code() string { |
| 31 | + if len(r.Issues) == 0 { |
| 32 | + return "" |
| 33 | + } |
| 34 | + return r.Issues[0].Code |
| 35 | +} |
| 36 | + |
| 37 | +// ansiEscape matches CSI color/style sequences. Error messages built for |
| 38 | +// human output may embed them (e.g. via printer.BoldBlue); they must never |
| 39 | +// reach a JSON payload. |
| 40 | +var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*m`) |
| 41 | + |
| 42 | +// GlobalJSONError classifies an error for the global JSON envelope. |
| 43 | +// |
| 44 | +// Classification is by message text because this is the top-level fallback: |
| 45 | +// command-specific handlers with typed errors have already had their chance. |
| 46 | +// next_steps must earn their place: each case lists only the commands that |
| 47 | +// actually address the failure, not generic bootstrap commands. |
| 48 | +func GlobalJSONError(err error) JSONErrorResponse { |
| 49 | + msg := err.Error() |
| 50 | + status := "error" |
| 51 | + code := "COMMAND_FAILED" |
| 52 | + |
| 53 | + if cmdErr, ok := errors.AsType[*Error](err); ok { |
| 54 | + if cmdErr.Msg != "" { |
| 55 | + msg = cmdErr.Msg |
| 56 | + } |
| 57 | + if cmdErr.ExitCode == ActionRequestedExitCode { |
| 58 | + status = "action_required" |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + msg = ansiEscape.ReplaceAllString(msg, "") |
| 63 | + |
| 64 | + var nextSteps []string |
| 65 | + lower := strings.ToLower(msg) |
| 66 | + |
| 67 | + switch { |
| 68 | + // Auth problems: the fix is logging in (or fixing credentials), then verifying. |
| 69 | + case strings.Contains(msg, WarnAuthMessage) || |
| 70 | + strings.Contains(lower, "not authenticated") || |
| 71 | + strings.Contains(msg, "access token has expired"): |
| 72 | + status = "action_required" |
| 73 | + code = "NO_AUTH" |
| 74 | + nextSteps = []string{AgentAuthLoginCmd(), AgentAuthCheckCmd()} |
| 75 | + |
| 76 | + case strings.Contains(msg, "Authentication failed") && strings.Contains(msg, "service token"): |
| 77 | + status = "action_required" |
| 78 | + code = "SERVICE_TOKEN_INVALID" |
| 79 | + nextSteps = []string{ |
| 80 | + "Verify --service-token-id and --service-token values (or PLANETSCALE_SERVICE_TOKEN_ID / PLANETSCALE_SERVICE_TOKEN)", |
| 81 | + AgentAuthCheckCmd(), |
| 82 | + } |
| 83 | + |
| 84 | + // --org on pscale root: show the corrected shape, not a re-auth loop. |
| 85 | + case strings.Contains(msg, "unknown flag: --org"): |
| 86 | + code = "INVALID_FLAG_PLACEMENT" |
| 87 | + nextSteps = []string{ |
| 88 | + "Move --org onto the resource subcommand", |
| 89 | + AgentDatabaseListCmd(""), |
| 90 | + } |
| 91 | + |
| 92 | + // Wrong invocation: cobra's message already names the missing piece and |
| 93 | + // includes usage. Point at the guide for command shapes; auth is not the issue. |
| 94 | + case strings.Contains(msg, "missing argument") || |
| 95 | + strings.Contains(msg, "missing arguments") || |
| 96 | + strings.Contains(msg, "missing required flags") || |
| 97 | + strings.Contains(msg, "required flag"): |
| 98 | + status = "action_required" |
| 99 | + code = "INVALID_USAGE" |
| 100 | + nextSteps = []string{ |
| 101 | + "Re-run with the missing arguments or flags named in the error message", |
| 102 | + AgentGuideCmd(), |
| 103 | + } |
| 104 | + |
| 105 | + case strings.Contains(msg, "unknown command"): |
| 106 | + code = "UNKNOWN_COMMAND" |
| 107 | + nextSteps = []string{ |
| 108 | + "Run `pscale --help` to list valid commands", |
| 109 | + AgentGuideCmd(), |
| 110 | + } |
| 111 | + |
| 112 | + case strings.Contains(msg, "unknown flag") || strings.Contains(msg, "unknown shorthand flag"): |
| 113 | + code = "UNKNOWN_FLAG" |
| 114 | + nextSteps = []string{ |
| 115 | + "Run the same command with --help to list valid flags", |
| 116 | + AgentGuideCmd(), |
| 117 | + } |
| 118 | + |
| 119 | + // TTY-gated commands: messages vary ("interactive shell", "interactive |
| 120 | + // terminal"), so match the shared prefix. Only login has a JSON-mode |
| 121 | + // alternative worth suggesting. |
| 122 | + case strings.Contains(msg, "requires an interactive"): |
| 123 | + status = "action_required" |
| 124 | + code = "TTY_REQUIRED" |
| 125 | + if strings.Contains(lower, "login") { |
| 126 | + nextSteps = []string{AgentAuthLoginCmd()} |
| 127 | + } else { |
| 128 | + nextSteps = []string{"Re-run this command in an interactive terminal"} |
| 129 | + } |
| 130 | + |
| 131 | + // Confirmation-gated commands: the fix is user approval, then --force. |
| 132 | + case strings.Contains(msg, "run with --force"): |
| 133 | + status = "action_required" |
| 134 | + code = "CONFIRMATION_REQUIRED" |
| 135 | + nextSteps = []string{ |
| 136 | + "Ask the user to approve this action", |
| 137 | + "Re-run the same command with --force after approval", |
| 138 | + } |
| 139 | + |
| 140 | + // Resource lookups that failed: discovery commands are the way forward. |
| 141 | + case strings.Contains(msg, "does not exist"): |
| 142 | + code = "NOT_FOUND" |
| 143 | + nextSteps = []string{ |
| 144 | + AgentOrgListCmd(), |
| 145 | + AgentDatabaseListCmd(""), |
| 146 | + } |
| 147 | + |
| 148 | + // Connectivity: nothing an agent can self-serve beyond retry and status. |
| 149 | + // Match transport-level failures only — a bare "timeout" substring would |
| 150 | + // swallow operation or deadline timeouts that deserve command-specific |
| 151 | + // handling. |
| 152 | + case strings.Contains(lower, "connection refused") || |
| 153 | + strings.Contains(lower, "connection reset by peer") || |
| 154 | + strings.Contains(lower, "no such host") || |
| 155 | + strings.Contains(lower, "i/o timeout") || |
| 156 | + strings.Contains(lower, "tls handshake timeout") || |
| 157 | + strings.Contains(lower, "temporary failure in name resolution"): |
| 158 | + code = "NETWORK_ERROR" |
| 159 | + nextSteps = []string{ |
| 160 | + "Check network connectivity and --api-url, then retry", |
| 161 | + AgentAuthCheckCmd(), |
| 162 | + } |
| 163 | + |
| 164 | + // Unclassified: auth state is the one thing worth ruling out first. |
| 165 | + default: |
| 166 | + nextSteps = []string{ |
| 167 | + AgentAuthCheckCmd(), |
| 168 | + AgentGuideCmd(), |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + return JSONErrorResponse{ |
| 173 | + Status: status, |
| 174 | + Error: msg, |
| 175 | + Issues: []JSONErrorIssue{{Code: code, Message: msg}}, |
| 176 | + NextSteps: nextSteps, |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +// ReportGlobalJSONError writes the classified envelope for err to w and |
| 181 | +// returns the process exit code. On encoding failure it falls back to a |
| 182 | +// plain error line on errW. |
| 183 | +func ReportGlobalJSONError(w, errW io.Writer, err error) int { |
| 184 | + resp := GlobalJSONError(err) |
| 185 | + if writeErr := WriteJSONError(w, resp); writeErr != nil { |
| 186 | + fmt.Fprintf(errW, "Error: %s\n", err) |
| 187 | + } |
| 188 | + |
| 189 | + if resp.Status == "action_required" { |
| 190 | + return ActionRequestedExitCode |
| 191 | + } |
| 192 | + if cmdErr, ok := errors.AsType[*Error](err); ok && cmdErr.ExitCode != 0 { |
| 193 | + return cmdErr.ExitCode |
| 194 | + } |
| 195 | + return FatalErrExitCode |
| 196 | +} |
| 197 | + |
| 198 | +// WriteJSONError writes a JSON error envelope to w. |
| 199 | +func WriteJSONError(w io.Writer, resp JSONErrorResponse) error { |
| 200 | + enc := json.NewEncoder(w) |
| 201 | + enc.SetEscapeHTML(false) |
| 202 | + enc.SetIndent("", " ") |
| 203 | + return enc.Encode(resp) |
| 204 | +} |
0 commit comments