diff --git a/AGENTS.md b/AGENTS.md index 1574ac9..a2066bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ Go CLI for Hacker News via the Algolia API. No auth required. - `cmd/hn/main.go` -- thin entrypoint, version embedding via ldflags - `internal/cmd/root.go` -- all CLI commands (cobra) -- `internal/api/client.go` -- HN Algolia API client +- `internal/api/client.go` -- HN Algolia and Firebase API client - `internal/output/format.go` -- compact plaintext and JSON formatters - `skills/hn/SKILL.md` -- agent skill definition @@ -28,4 +28,5 @@ Go CLI for Hacker News via the Algolia API. No auth required. ## API -HN Algolia API at `https://hn.algolia.com/api/v1/`. Free, no auth, no rate limits. +HN Algolia API at `https://hn.algolia.com/api/v1/`, and the official Firebase API +at `https://hacker-news.firebaseio.com/v0/` for what Algolia lacks. Free, no auth. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e2b8d5..3a5158f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- Exit codes now match the docs. Network failures, rate limits and server + errors exit 8, missing items and users exit 5, and an empty `hn front` exits 3. +- `hn status --json` exits 8 when the API is down. +- `hn user` looks profiles up through the Firebase API, because Algolia answers + 500 for unknown users. + ## [0.2.1] — 2026-08-08 ### Fixed diff --git a/README.md b/README.md index e07e4dc..cf122f9 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Agent-friendly CLI for [Hacker News](https://news.ycombinator.com) via the [Algo - **Fast** — direct Algolia API, no scraping or HTML parsing - **Agent-friendly** — `--json` on every command, structured exit codes, stderr-only progress -- **Zero config** — no API keys, no auth, no rate limits +- **Zero config** — no API keys, no auth - **Single binary** — install via Homebrew, Scoop, or `go install`

@@ -113,7 +113,7 @@ npx skills add -g voska/hn-cli ## API -Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) -- free, public, no authentication or API keys required. +Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) for search and threads, and the [official Firebase API](https://github.com/HackerNews/API) for user profiles. Both are free and public, with no authentication or API keys required. ## Output Modes @@ -143,7 +143,7 @@ All commands support `--json`. | 1 | error | General error | | 3 | empty | No results found | | 5 | not_found | Invalid ID or username | -| 8 | retryable | Transient error, safe to retry | +| 8 | retryable | Network failure, rate limit or server error, safe to retry | ## Development diff --git a/internal/api/client.go b/internal/api/client.go index 5dc1595..4418851 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "errors" "fmt" "html" "net/http" @@ -11,28 +12,64 @@ import ( "time" ) -// BaseURL is the default HN Algolia API endpoint. -const BaseURL = "https://hn.algolia.com/api/v1" +const ( + // BaseURL is the default HN Algolia API endpoint. + BaseURL = "https://hn.algolia.com/api/v1" + // FirebaseURL is the default official HN API endpoint. + FirebaseURL = "https://hacker-news.firebaseio.com/v0" +) + +var ( + // ErrNotFound means the requested item or user does not exist. + ErrNotFound = errors.New("not found") + // ErrRetryable means a network failure, rate limit or server error. + ErrRetryable = errors.New("temporary failure") +) -// Client wraps an HTTP client and base URL for the HN Algolia API. +// Client wraps an HTTP client and base URLs for the HN APIs. type Client struct { - baseURL string - httpClient *http.Client + baseURL string + firebaseURL string + httpClient *http.Client } // NewClient returns a Client configured with the given base URL and HTTP client. func NewClient(baseURL string, httpClient *http.Client) *Client { return &Client{ - baseURL: baseURL, - httpClient: httpClient, + baseURL: baseURL, + firebaseURL: FirebaseURL, + httpClient: httpClient, } } -// DefaultClient returns a Client using the production API and a 15s timeout. +// DefaultClient returns a Client using the production APIs and a 15s timeout. func DefaultClient() *Client { return NewClient(BaseURL, &http.Client{Timeout: 15 * time.Second}) } +// getJSON fetches reqURL and decodes the response into v. +func (c *Client) getJSON(reqURL string, v any) error { + resp, err := c.httpClient.Get(reqURL) + if err != nil { + return fmt.Errorf("%w: %v", ErrRetryable, err) + } + defer resp.Body.Close() + + switch { + case resp.StatusCode == http.StatusNotFound: + return ErrNotFound + case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500: + return fmt.Errorf("%w: api returned %d", ErrRetryable, resp.StatusCode) + case resp.StatusCode != http.StatusOK: + return fmt.Errorf("api returned %d", resp.StatusCode) + } + + if err := json.NewDecoder(resp.Body).Decode(v); err != nil { + return fmt.Errorf("decode failed: %w", err) + } + return nil +} + // SearchResult represents the Algolia search response. type SearchResult struct { Hits []Hit `json:"hits"` @@ -126,68 +163,38 @@ func (c *Client) BuildURL(opts SearchOptions) string { // Search queries the HN Algolia search API. func (c *Client) Search(opts SearchOptions) (*SearchResult, error) { - reqURL := c.BuildURL(opts) - resp, err := c.httpClient.Get(reqURL) - if err != nil { - return nil, fmt.Errorf("request failed: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("api returned %d", resp.StatusCode) - } - var result SearchResult - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return nil, fmt.Errorf("decode failed: %w", err) + if err := c.getJSON(c.BuildURL(opts), &result); err != nil { + return nil, err } return &result, nil } // GetItem fetches a single item (story/comment) with its children. func (c *Client) GetItem(id string) (*Item, error) { - reqURL := fmt.Sprintf("%s/items/%s", c.baseURL, id) - resp, err := c.httpClient.Get(reqURL) - if err != nil { - return nil, fmt.Errorf("request failed: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotFound { - return nil, fmt.Errorf("item %s not found", id) - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("api returned %d", resp.StatusCode) - } - var item Item - if err := json.NewDecoder(resp.Body).Decode(&item); err != nil { - return nil, fmt.Errorf("decode failed: %w", err) + if err := c.getJSON(fmt.Sprintf("%s/items/%s", c.baseURL, url.PathEscape(id)), &item); err != nil { + return nil, fmt.Errorf("item %s: %w", id, err) } return &item, nil } -// GetUser fetches a user profile. +// GetUser fetches a user profile. It uses the Firebase API because Algolia +// answers 500 for unknown users, which looks like an outage. func (c *Client) GetUser(username string) (*User, error) { - reqURL := fmt.Sprintf("%s/users/%s", c.baseURL, url.PathEscape(username)) - resp, err := c.httpClient.Get(reqURL) - if err != nil { - return nil, fmt.Errorf("request failed: %w", err) + var profile *struct { + ID string `json:"id"` + About string `json:"about"` + Karma int `json:"karma"` } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotFound { - return nil, fmt.Errorf("user %q not found", username) - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("api returned %d", resp.StatusCode) + reqURL := fmt.Sprintf("%s/user/%s.json", c.firebaseURL, url.PathEscape(username)) + if err := c.getJSON(reqURL, &profile); err != nil { + return nil, fmt.Errorf("user %s: %w", username, err) } - - var user User - if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { - return nil, fmt.Errorf("decode failed: %w", err) + if profile == nil { + return nil, fmt.Errorf("user %s: %w", username, ErrNotFound) } - return &user, nil + return &User{Username: profile.ID, About: profile.About, Karma: profile.Karma}, nil } // HealthCheck pings the API and returns latency. @@ -195,13 +202,13 @@ func (c *Client) HealthCheck() (time.Duration, error) { start := time.Now() resp, err := c.httpClient.Get(c.baseURL + "/search?query=test&hitsPerPage=0") if err != nil { - return 0, fmt.Errorf("api unreachable: %w", err) + return 0, fmt.Errorf("%w: %v", ErrRetryable, err) } defer resp.Body.Close() elapsed := time.Since(start) if resp.StatusCode != http.StatusOK { - return elapsed, fmt.Errorf("api returned %d", resp.StatusCode) + return elapsed, fmt.Errorf("%w: api returned %d", ErrRetryable, resp.StatusCode) } return elapsed, nil } diff --git a/internal/api/client_test.go b/internal/api/client_test.go index 9f3fc5d..f6f0e75 100644 --- a/internal/api/client_test.go +++ b/internal/api/client_test.go @@ -2,12 +2,20 @@ package api import ( "encoding/json" + "errors" "net/http" "net/http/httptest" "testing" "time" ) +// testClient points both APIs at srv. +func testClient(srv *httptest.Server) *Client { + c := NewClient(srv.URL, srv.Client()) + c.firebaseURL = srv.URL + return c +} + func TestBuildURL(t *testing.T) { c := NewClient("https://example.com/api/v1", http.DefaultClient) @@ -70,7 +78,7 @@ func TestSearch(t *testing.T) { })) defer srv.Close() - c := NewClient(srv.URL, srv.Client()) + c := testClient(srv) result, err := c.Search(SearchOptions{Query: "test"}) if err != nil { t.Fatalf("Search() error: %v", err) @@ -93,7 +101,7 @@ func TestGetItem(t *testing.T) { })) defer srv.Close() - c := NewClient(srv.URL, srv.Client()) + c := testClient(srv) item, err := c.GetItem("123") if err != nil { @@ -111,27 +119,80 @@ func TestGetItem(t *testing.T) { func TestGetUser(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/users/pg" { - json.NewEncoder(w).Encode(User{Username: "pg", Karma: 157316}) + if r.URL.Path == "/user/pg.json" { + w.Write([]byte(`{"id":"pg","karma":157316,"about":"Bug fixer."}`)) return } - w.WriteHeader(http.StatusNotFound) + w.Write([]byte("null")) })) defer srv.Close() - c := NewClient(srv.URL, srv.Client()) + c := testClient(srv) user, err := c.GetUser("pg") if err != nil { t.Fatalf("GetUser() error: %v", err) } - if user.Username != "pg" { - t.Errorf("expected username 'pg', got %q", user.Username) + if user.Username != "pg" || user.Karma != 157316 || user.About != "Bug fixer." { + t.Errorf("unexpected user: %+v", user) } _, err = c.GetUser("nonexistent_user_xyz") - if err == nil { - t.Error("expected error for missing user") + if !errors.Is(err, ErrNotFound) { + t.Errorf("expected ErrNotFound for missing user, got %v", err) + } +} + +func TestErrorClassification(t *testing.T) { + tests := []struct { + name string + status int + want error + }{ + {"not found", http.StatusNotFound, ErrNotFound}, + {"rate limited", http.StatusTooManyRequests, ErrRetryable}, + {"server error", http.StatusBadGateway, ErrRetryable}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + })) + defer srv.Close() + + c := testClient(srv) + if _, err := c.GetItem("1"); !errors.Is(err, tt.want) { + t.Errorf("GetItem() error = %v, want %v", err, tt.want) + } + }) + } +} + +func TestNetworkFailureIsRetryable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + url := srv.URL + srv.Close() + + c := NewClient(url, http.DefaultClient) + c.firebaseURL = url + if _, err := c.GetItem("1"); !errors.Is(err, ErrRetryable) { + t.Errorf("GetItem() error = %v, want ErrRetryable", err) + } + if _, err := c.Search(SearchOptions{Query: "go"}); !errors.Is(err, ErrRetryable) { + t.Errorf("Search() error = %v, want ErrRetryable", err) + } +} + +func TestClientErrorIsNotRetryable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + })) + defer srv.Close() + + c := testClient(srv) + if _, err := c.Search(SearchOptions{Query: "go"}); err == nil || errors.Is(err, ErrRetryable) { + t.Errorf("Search() error = %v, want a non-retryable error", err) } } diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 284f3a1..ae0ddd0 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "os" "strings" @@ -25,16 +26,6 @@ type ErrNoResults struct{} func (e ErrNoResults) Error() string { return "no results" } -// ErrNotFound signals a missing resource (exit code 5). -type ErrNotFound struct{ msg string } - -func (e ErrNotFound) Error() string { return e.msg } - -// ErrRetryable signals a transient failure (exit code 8). -type ErrRetryable struct{ msg string } - -func (e ErrRetryable) Error() string { return e.msg } - func SetVersion(v, c, d string) { appVersion = v appCommit = c @@ -68,12 +59,12 @@ func Execute() error { // ExitCode maps sentinel errors to process exit codes. func ExitCode(err error) int { - switch err.(type) { - case ErrNoResults: + switch { + case errors.As(err, &ErrNoResults{}): return 3 - case ErrNotFound: + case errors.Is(err, api.ErrNotFound): return 5 - case ErrRetryable: + case errors.Is(err, api.ErrRetryable): return 8 default: return 1 @@ -168,6 +159,10 @@ var frontCmd = &cobra.Command{ return err } + if len(result.Hits) == 0 { + return ErrNoResults{} + } + if jsonOutput { return output.JSON(result) } @@ -192,7 +187,7 @@ var readCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { item, err := client().GetItem(args[0]) if err != nil { - return ErrNotFound{msg: err.Error()} + return err } if jsonOutput { @@ -217,7 +212,7 @@ var userCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { user, err := client().GetUser(args[0]) if err != nil { - return ErrNotFound{msg: err.Error()} + return err } if jsonOutput { @@ -237,9 +232,11 @@ var statusCmd = &cobra.Command{ latency, err := client().HealthCheck() if err != nil { if jsonOutput { - return output.JSON(map[string]any{"status": "error", "error": err.Error()}) + if jsonErr := output.JSON(map[string]any{"status": "error", "error": err.Error()}); jsonErr != nil { + return jsonErr + } } - return ErrRetryable{msg: fmt.Sprintf("HN API: DOWN (%v)", err)} + return fmt.Errorf("HN API: DOWN (%w)", err) } if jsonOutput {