From 9a5cc3e05613fc257b1cd3210c7c0cb1f8f1dbba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jc=20Mi=C3=B1arro?= Date: Sun, 15 Nov 2026 14:37:51 +0100 Subject: [PATCH 1/4] feat(user): expose pagination for `user items` via --next and bounded --all The user-items endpoint pages 40 items at a time through meta.next/?since=, but Client.UserItems discarded the cursor, so sellers with more than 40 active listings were unreachable. - Add Client.UserItemsPage(ctx, hash, since) returning one page plus cursor. - `user items USER` gains --next (resume from a previous next_page token) and --all (sequential bounded walk, 50 pages max, stops with a warning and keeps the pending cursor in next_page when the bound is hit). - Without flags the output shape is unchanged apart from the additive next_page field. - Fake server now paginates /api/v3/users/{hash}/items like /user/items. --- docs-site/content/docs/reference/user.mdx | 18 ++++- internal/cli/cli_test.go | 96 +++++++++++++++++++++++ internal/cli/item.go | 78 +++++++++++++++--- internal/fakewallapop/fake.go | 12 ++- internal/wallapop/users.go | 11 ++- 5 files changed, 198 insertions(+), 17 deletions(-) diff --git a/docs-site/content/docs/reference/user.mdx b/docs-site/content/docs/reference/user.mdx index 816ef27..36e951d 100644 --- a/docs-site/content/docs/reference/user.mdx +++ b/docs-site/content/docs/reference/user.mdx @@ -16,9 +16,25 @@ Look at a seller. USER is a user hash, a profile URL, or the web slug (name-1234 Active listings ```bash -wallapop user items USER +wallapop user items USER [flags] ``` +List a seller's active listings. Wallapop pages this endpoint 40 items at a +time: a plain call returns one page with its next_page cursor, --all walks +every page (bounded at 50 pages), --next resumes from a previous cursor +(single page, or the whole walk when combined with --all). + +```bash +wallapop user items p8j35kmwr7z9 +wallapop user items p8j35kmwr7z9 --all +wallapop user items p8j35kmwr7z9 --next "$(wallapop user items p8j35kmwr7z9 | jq -r .next_page)" +``` + +| Flag | Type | Default | Description | +| --- | --- | --- | --- | +| `--all` | bool | `false` | walk every page until exhausted (bounded) | +| `--next` | string | - | continue from a previous next_page token | + ## `wallapop user reviews` Reviews received diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 0f3cb75..3a8fe1f 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -516,6 +516,102 @@ func TestUserBySlugURLAndHash(t *testing.T) { } } +// user items pagination + +func TestUserItemsReturnsPageWithNextCursor(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 2 + for i := 0; i < 5; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + r := h.must("", "user", "items", fakewallapop.OtherHash) + var page struct { + Items []struct{ Hash string } + NextPage string `json:"next_page"` + } + decode(t, r.stdout, &page) + if len(page.Items) != 2 || page.NextPage == "" { + t.Fatalf("got %d items, next %q", len(page.Items), page.NextPage) + } + reqs := h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items") + if len(reqs) != 1 || reqs[0].Query.Get("since") != "" { + t.Fatalf("first page request: %d, query %v", len(reqs), reqs[0].Query) + } + next := page.NextPage + + r = h.must("", "user", "items", fakewallapop.OtherHash, "--next", next) + decode(t, r.stdout, &page) + if len(page.Items) != 2 { + t.Fatalf("second page got %d items", len(page.Items)) + } + reqs = h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items") + if len(reqs) != 2 || reqs[1].Query.Get("since") != next { + t.Fatalf("second page did not pass since=%q: %v", next, reqs[len(reqs)-1].Query) + } + if page.NextPage == "" { + t.Fatal("second page lost the next cursor") + } + + r = h.must("", "user", "items", fakewallapop.OtherHash, "--next", page.NextPage) + var last struct { + Items []struct{ Hash string } + NextPage string `json:"next_page"` + } + decode(t, r.stdout, &last) + if len(last.Items) != 1 || last.NextPage != "" { + t.Fatalf("last page: %d items, next %q", len(last.Items), last.NextPage) + } +} + +func TestUserItemsAllWalksEveryPage(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 2 + for i := 0; i < 5; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + r := h.must("", "user", "items", fakewallapop.OtherHash, "--all") + var page struct { + Items []struct{ Hash string } + NextPage string `json:"next_page"` + } + decode(t, r.stdout, &page) + if len(page.Items) != 5 || page.NextPage != "" { + t.Fatalf("got %d items, next %q", len(page.Items), page.NextPage) + } + if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 3 { + t.Fatalf("expected 3 sequential page requests, got %d", n) + } + if strings.Contains(r.stderr, "warning") { + t.Fatalf("unexpected warning: %s", r.stderr) + } +} + +func TestUserItemsAllStopsAtBoundWithWarning(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 1 + for i := 0; i < 60; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + r := h.must("", "user", "items", fakewallapop.OtherHash, "--all") + var page struct { + Items []struct{ Hash string } + NextPage string `json:"next_page"` + } + decode(t, r.stdout, &page) + if len(page.Items) != 50 || page.NextPage == "" { + t.Fatalf("bound walk: %d items, next %q", len(page.Items), page.NextPage) + } + if !strings.Contains(r.stderr, "stopped after 50 pages") { + t.Fatalf("missing bound warning: %s", r.stderr) + } + if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 50 { + t.Fatalf("expected bounded 50 requests, got %d", n) + } +} + // chat func TestChatSendPublishesWebShapedPayload(t *testing.T) { diff --git a/internal/cli/item.go b/internal/cli/item.go index dcef356..a43c6de 100644 --- a/internal/cli/item.go +++ b/internal/cli/item.go @@ -584,35 +584,63 @@ func (a *App) userCmd() *cobra.Command { resolve := func(cmd *cobra.Command, ref string) (string, error) { return a.Client.ResolveUserHash(cmd.Context(), ref) } - cmd.AddCommand( - &cobra.Command{ - Use: "show USER", Short: "Profile and stats", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - hash, err := resolve(cmd, args[0]) + var itemsNext string + var itemsAll bool + var itemsCmd = &cobra.Command{ + Use: "items USER", Short: "Active listings", Args: cobra.ExactArgs(1), + Long: `List a seller's active listings. Wallapop pages this endpoint 40 items at a +time: a plain call returns one page with its next_page cursor, --all walks +every page (bounded at 50 pages), --next resumes from a previous cursor +(single page, or the whole walk when combined with --all). + +Examples: + wallapop user items p8j35kmwr7z9 + wallapop user items p8j35kmwr7z9 --all + wallapop user items p8j35kmwr7z9 --next "$(wallapop user items p8j35kmwr7z9 | jq -r .next_page)"`, + RunE: func(cmd *cobra.Command, args []string) error { + hash, err := resolve(cmd, args[0]) + if err != nil { + return err + } + if itemsAll { + items, truncated, err := a.allUserItems(cmd.Context(), hash, itemsNext) if err != nil { return err } - u, err := a.Client.User(cmd.Context(), hash) - if err != nil { - return err + view := itemsView{Items: items, NextPage: truncated} + if truncated != "" { + // The walk hit its bound, not the end of the list: + // say so on stderr, and keep the cursor in the JSON + // so callers can pick up where this left off. + fmt.Fprintf(a.Stderr, "wallapop: warning: stopped after %d pages (%d items); more pages remain, continue with --next\n", maxUserItemPages, len(items)) } - return a.Printer.Print(userView(u)) - }, + return a.Printer.Print(view) + } + items, cursor, err := a.Client.UserItemsPage(cmd.Context(), hash, itemsNext) + if err != nil { + return err + } + return a.Printer.Print(itemsView{Items: items, NextPage: cursor}) }, + } + itemsCmd.Flags().StringVar(&itemsNext, "next", "", "continue from a previous next_page token") + itemsCmd.Flags().BoolVar(&itemsAll, "all", false, "walk every page until exhausted (bounded)") + cmd.AddCommand( &cobra.Command{ - Use: "items USER", Short: "Active listings", Args: cobra.ExactArgs(1), + Use: "show USER", Short: "Profile and stats", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { hash, err := resolve(cmd, args[0]) if err != nil { return err } - items, err := a.Client.UserItems(cmd.Context(), hash) + u, err := a.Client.User(cmd.Context(), hash) if err != nil { return err } - return a.Printer.Print(itemsView{Items: items}) + return a.Printer.Print(userView(u)) }, }, + itemsCmd, &cobra.Command{ Use: "reviews USER", Short: "Reviews received", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -631,6 +659,30 @@ func (a *App) userCmd() *cobra.Command { return cmd } +// maxUserItemPages bounds `user items --all` (40 items per page, so 2000 +// items at most); hitting it is a warning, not an error. +const maxUserItemPages = 50 + +// allUserItems walks a seller's pages sequentially, from since ("" = start) +// until the cursor runs out or the bound is hit. When truncated, it returns +// the last cursor so the caller can warn and let consumers resume. +func (a *App) allUserItems(ctx context.Context, hash, since string) (items []wallapop.Item, truncated string, err error) { + items = []wallapop.Item{} + for page := 0; page < maxUserItemPages; page++ { + batch, cursor, err := a.Client.UserItemsPage(ctx, hash, since) + if err != nil { + return items, "", err + } + items = append(items, batch...) + // A cursor repeated unchanged would loop forever; treat it as done. + if cursor == "" || cursor == since { + return items, "", nil + } + since = cursor + } + return items, since, nil +} + func (a *App) meCmd() *cobra.Command { cmd := &cobra.Command{Use: "me", Short: "Your own account: profile, listings, favorites"} var sold bool diff --git a/internal/fakewallapop/fake.go b/internal/fakewallapop/fake.go index c2d7170..e49165b 100644 --- a/internal/fakewallapop/fake.go +++ b/internal/fakewallapop/fake.go @@ -528,7 +528,17 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) { if data == nil { data = []map[string]any{} } - writeJSON(w, 200, map[string]any{"data": data, "meta": map[string]any{}}) + meta := map[string]any{} + if n := s.UserItemsPageSize; n > 0 { + start, _ := strconv.Atoi(r.URL.Query().Get("since")) + start = min(max(start, 0), len(data)) + end := min(start+n, len(data)) + if end < len(data) { + meta["next"] = strconv.Itoa(end) + } + data = data[start:end] + } + writeJSON(w, 200, map[string]any{"data": data, "meta": meta}) case "stats": writeJSON(w, 200, map[string]any{"ratings": []map[string]any{{"type": "reviews", "value": 97}}, "counters": []map[string]any{{"type": "sold", "value": 36}, {"type": "publish", "value": 9}}, "rating_average": 4.9}) case "reviews": diff --git a/internal/wallapop/users.go b/internal/wallapop/users.go index fb3c098..52b0639 100644 --- a/internal/wallapop/users.go +++ b/internal/wallapop/users.go @@ -137,9 +137,16 @@ func (c *Client) userStats(ctx context.Context, hash string) (UserStats, error) return s, nil } -// UserItems lists a seller's active items. +// UserItems lists a seller's active items (first page only). func (c *Client) UserItems(ctx context.Context, hash string) ([]Item, error) { - return c.userItems(ctx, "/api/v3/users/"+hash+"/items", false, hash) + items, _, err := c.UserItemsPage(ctx, hash, "") + return items, err +} + +// UserItemsPage lists one page of a seller's active items and returns the +// next cursor ("" when there are no more pages). Empty since = first page. +func (c *Client) UserItemsPage(ctx context.Context, hash, since string) ([]Item, string, error) { + return c.userItemsPage(ctx, "/api/v3/users/"+hash+"/items", since, false, hash) } // UserReviews lists the reviews a user has received. From 146a9849d5a1e56c7c2eb2a653d662ae9c9c73bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jc=20Mi=C3=B1arro?= Date: Sun, 15 Nov 2026 15:04:11 +0100 Subject: [PATCH 2/4] fix(user): preserve pagination state and surface incomplete walks - Keep next_page present as an empty string on the final user-items page. - Return a cursor-stalled error instead of reporting a repeated cursor as successful exhaustion. - Preserve and print successful pages plus the last resume cursor when a later page request fails, while still returning the request error. - Assert ordered hashes, the exact bound cursor and a successful resume. - Use Item terminology in CLI help and generated docs. --- docs-site/content/docs/reference/user.mdx | 4 +- internal/cli/cli_test.go | 74 ++++++++++++++++++++--- internal/cli/item.go | 41 ++++++++++--- internal/fakewallapop/fake.go | 32 ++++++++-- 4 files changed, 127 insertions(+), 24 deletions(-) diff --git a/docs-site/content/docs/reference/user.mdx b/docs-site/content/docs/reference/user.mdx index 36e951d..2e2d264 100644 --- a/docs-site/content/docs/reference/user.mdx +++ b/docs-site/content/docs/reference/user.mdx @@ -13,13 +13,13 @@ Look at a seller. USER is a user hash, a profile URL, or the web slug (name-1234 ## `wallapop user items` -Active listings +Active Items ```bash wallapop user items USER [flags] ``` -List a seller's active listings. Wallapop pages this endpoint 40 items at a +List a seller's active Items. Wallapop pages this endpoint 40 Items at a time: a plain call returns one page with its next_page cursor, --all walks every page (bounded at 50 pages), --next resumes from a previous cursor (single page, or the whole walk when combined with --all). diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 3a8fe1f..d11e191 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -554,13 +554,13 @@ func TestUserItemsReturnsPageWithNextCursor(t *testing.T) { } r = h.must("", "user", "items", fakewallapop.OtherHash, "--next", page.NextPage) - var last struct { - Items []struct{ Hash string } - NextPage string `json:"next_page"` - } + var last map[string]any decode(t, r.stdout, &last) - if len(last.Items) != 1 || last.NextPage != "" { - t.Fatalf("last page: %d items, next %q", len(last.Items), last.NextPage) + if got, ok := last["next_page"]; !ok || got != "" { + t.Fatalf("last page must carry an empty next_page key, got %q present=%v", got, ok) + } + if n := len(last["items"].([]any)); n != 1 { + t.Fatalf("last page: %d items", n) } } @@ -580,6 +580,14 @@ func TestUserItemsAllWalksEveryPage(t *testing.T) { if len(page.Items) != 5 || page.NextPage != "" { t.Fatalf("got %d items, next %q", len(page.Items), page.NextPage) } + // Count alone would let a duplicate hide an omission: assert the whole + // ordered listing. + want := []string{"hash00000000", "hash00000001", "hash00000002", "hash00000003", "hash00000004"} + for i, it := range page.Items { + if it.Hash != want[i] { + t.Fatalf("item %d = %s, want %s", i, it.Hash, want[i]) + } + } if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 3 { t.Fatalf("expected 3 sequential page requests, got %d", n) } @@ -601,7 +609,7 @@ func TestUserItemsAllStopsAtBoundWithWarning(t *testing.T) { NextPage string `json:"next_page"` } decode(t, r.stdout, &page) - if len(page.Items) != 50 || page.NextPage == "" { + if len(page.Items) != 50 || page.NextPage != "50" { t.Fatalf("bound walk: %d items, next %q", len(page.Items), page.NextPage) } if !strings.Contains(r.stderr, "stopped after 50 pages") { @@ -610,6 +618,58 @@ func TestUserItemsAllStopsAtBoundWithWarning(t *testing.T) { if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 50 { t.Fatalf("expected bounded 50 requests, got %d", n) } + resume := h.must("", "user", "items", fakewallapop.OtherHash, "--next", page.NextPage) + var resumed struct { + Items []struct{ Hash string } `json:"items"` + } + decode(t, resume.stdout, &resumed) + if len(resumed.Items) != 1 || resumed.Items[0].Hash != "hash00000050" { + t.Fatalf("resume from %q returned %d items starting at %q", page.NextPage, len(resumed.Items), resumed.Items[0].Hash) + } +} + +func TestUserItemsAllRejectsRepeatedCursor(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 1 + h.fake.UserItemsStickyCursor = "1" + for i := 0; i < 3; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + r := h.run("", "user", "items", fakewallapop.OtherHash, "--all") + if r.code == 0 || !strings.Contains(r.stderr, "cursor did not advance") { + t.Fatalf("expected stalled cursor error, exit %d stderr %q", r.code, r.stderr) + } + var partial struct { + Items []struct{ Hash string } `json:"items"` + Next string `json:"next_page"` + } + decode(t, r.stdout, &partial) + if len(partial.Items) != 2 || partial.Next != "1" { + t.Fatalf("stalled walk lost partial results/cursor: %+v", partial) + } +} + +func TestUserItemsAllPreservesPagesWhenLaterRequestFails(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 2 + h.fake.UserItemsFailSince = "2" + for i := 0; i < 5; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + r := h.run("", "user", "items", fakewallapop.OtherHash, "--all") + if r.code == 0 || !strings.Contains(r.stderr, "500") { + t.Fatalf("expected later-page error, exit %d stderr %q", r.code, r.stderr) + } + var partial struct { + Items []struct{ Hash string } `json:"items"` + Next string `json:"next_page"` + } + decode(t, r.stdout, &partial) + if len(partial.Items) != 2 || partial.Next != "2" { + t.Fatalf("failed walk lost partial results/cursor: %+v", partial) + } } // chat diff --git a/internal/cli/item.go b/internal/cli/item.go index a43c6de..282b3e7 100644 --- a/internal/cli/item.go +++ b/internal/cli/item.go @@ -575,6 +575,16 @@ func (v reviewsView) Pretty(w io.Writer, color bool) { output.Table(w, color, []string{"DATE", "SCORE", "BY", "ITEM", "COMMENT"}, rows) } +// userItemsView is itemsView for `user items`, with next_page always present: +// an absent key would be indistinguishable from a CLI without pagination, so +// consumers reading the field explicitly get "" on the last page. +type userItemsView struct { + Items []wallapop.Item `json:"items"` + NextPage string `json:"next_page"` +} + +func (v userItemsView) Pretty(w io.Writer, color bool) { itemsView(v).Pretty(w, color) } + func (a *App) userCmd() *cobra.Command { cmd := &cobra.Command{ Use: "user", @@ -587,8 +597,8 @@ func (a *App) userCmd() *cobra.Command { var itemsNext string var itemsAll bool var itemsCmd = &cobra.Command{ - Use: "items USER", Short: "Active listings", Args: cobra.ExactArgs(1), - Long: `List a seller's active listings. Wallapop pages this endpoint 40 items at a + Use: "items USER", Short: "Active Items", Args: cobra.ExactArgs(1), + Long: `List a seller's active Items. Wallapop pages this endpoint 40 Items at a time: a plain call returns one page with its next_page cursor, --all walks every page (bounded at 50 pages), --next resumes from a previous cursor (single page, or the whole walk when combined with --all). @@ -604,14 +614,18 @@ Examples: } if itemsAll { items, truncated, err := a.allUserItems(cmd.Context(), hash, itemsNext) + view := userItemsView{Items: items, NextPage: truncated} if err != nil { + // The pages already fetched are still real data: print + // them (with the cursor to resume from) and then fail + // with the request error, so a partial walk need not be + // repeated from the beginning. + _ = a.Printer.Print(view) return err } - view := itemsView{Items: items, NextPage: truncated} if truncated != "" { - // The walk hit its bound, not the end of the list: - // say so on stderr, and keep the cursor in the JSON - // so callers can pick up where this left off. + // The walk hit its bound: say so on stderr, and keep the cursor in + // the JSON so callers can pick up where this left off. fmt.Fprintf(a.Stderr, "wallapop: warning: stopped after %d pages (%d items); more pages remain, continue with --next\n", maxUserItemPages, len(items)) } return a.Printer.Print(view) @@ -620,7 +634,7 @@ Examples: if err != nil { return err } - return a.Printer.Print(itemsView{Items: items, NextPage: cursor}) + return a.Printer.Print(userItemsView{Items: items, NextPage: cursor}) }, } itemsCmd.Flags().StringVar(&itemsNext, "next", "", "continue from a previous next_page token") @@ -671,13 +685,20 @@ func (a *App) allUserItems(ctx context.Context, hash, since string) (items []wal for page := 0; page < maxUserItemPages; page++ { batch, cursor, err := a.Client.UserItemsPage(ctx, hash, since) if err != nil { - return items, "", err + // Keep what succeeded and the cursor to resume from; the caller + // prints the partial result and still reports this error. + return items, since, err } items = append(items, batch...) - // A cursor repeated unchanged would loop forever; treat it as done. - if cursor == "" || cursor == since { + if cursor == "" { return items, "", nil } + // A cursor repeated unchanged means the API stopped advancing the + // walk: report it as truncated (not exhausted) so the caller warns + // and can resume, instead of seeing an incomplete walk as complete. + if cursor == since { + return items, since, fmt.Errorf("user items pagination cursor did not advance (since=%q)", since) + } since = cursor } return items, since, nil diff --git a/internal/fakewallapop/fake.go b/internal/fakewallapop/fake.go index e49165b..2b06a28 100644 --- a/internal/fakewallapop/fake.go +++ b/internal/fakewallapop/fake.go @@ -125,9 +125,15 @@ type Server struct { NewItemPageLags bool // UserItemsPageSize pages /user/items via meta.next and ?since= (zero: one page). UserItemsPageSize int - Uploads map[string]int // pictures received per upload id - WebhookStatus int // status for POST /hook (0 = 200) - Hooks []json.RawMessage + // UserItemsStickyCursor overrides meta.next with this value on every + // page, modelling an API whose cursor never advances. + UserItemsStickyCursor string + // UserItemsFailSince makes the user-items endpoint answer 500 when the + // request's since equals this value (the walk's later pages fail). + UserItemsFailSince string + Uploads map[string]int // pictures received per upload id + WebhookStatus int // status for POST /hook (0 = 200) + Hooks []json.RawMessage } func New() *Server { @@ -255,12 +261,17 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) { data = append(data, s.userItemJSON(it)) } } + failSince, pageSize, stickyCursor := s.UserItemsFailSince, s.UserItemsPageSize, s.UserItemsStickyCursor s.mu.Unlock() if data == nil { data = []map[string]any{} } + if q := r.URL.Query().Get("since"); failSince != "" && q == failSince { + writeJSON(w, 500, map[string]any{"code": 500, "message": "fake failure"}) + return + } meta := map[string]any{} - if n := s.UserItemsPageSize; n > 0 && p != "/api/v3/user/items/favorited" { + if n := pageSize; n > 0 && p != "/api/v3/user/items/favorited" { start, _ := strconv.Atoi(r.URL.Query().Get("since")) start = min(max(start, 0), len(data)) end := min(start+n, len(data)) @@ -269,6 +280,9 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) { } data = data[start:end] } + if stickyCursor != "" && p != "/api/v3/user/items/favorited" { + meta["next"] = stickyCursor + } writeJSON(w, 200, map[string]any{"data": data, "meta": meta}) case p == "/api/v3/items" && r.Method == http.MethodPost: s.createItem(w, r) @@ -524,12 +538,17 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) { data = append(data, s.userItemJSON(it)) } } + failSince, pageSize, stickyCursor := s.UserItemsFailSince, s.UserItemsPageSize, s.UserItemsStickyCursor s.mu.Unlock() if data == nil { data = []map[string]any{} } + if q := r.URL.Query().Get("since"); failSince != "" && q == failSince { + writeJSON(w, 500, map[string]any{"code": 500, "message": "fake failure"}) + return + } meta := map[string]any{} - if n := s.UserItemsPageSize; n > 0 { + if n := pageSize; n > 0 { start, _ := strconv.Atoi(r.URL.Query().Get("since")) start = min(max(start, 0), len(data)) end := min(start+n, len(data)) @@ -538,6 +557,9 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) { } data = data[start:end] } + if stickyCursor != "" { + meta["next"] = stickyCursor + } writeJSON(w, 200, map[string]any{"data": data, "meta": meta}) case "stats": writeJSON(w, 200, map[string]any{"ratings": []map[string]any{{"type": "reviews", "value": 97}}, "counters": []map[string]any{{"type": "sold", "value": 36}, {"type": "publish", "value": 9}}, "rating_average": 4.9}) From 91e54f80483dcee79b7aed098dbc748899512213 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jc=20Mi=C3=B1arro?= Date: Sun, 15 Nov 2026 14:40:42 +0100 Subject: [PATCH 3/4] fix(watch): walk all seller pages so removal detection stays truthful checkSeller compared the seen hashes against only the first page of the seller's items, so with more than 40 listings every check reported false item.removed events for items that had merely scrolled to a later page (and ghost recoveries when they scrolled back). - Add Client.UserItemsAll: sequential bounded walk (MaxItemWalkPages, renamed from maxOwnItemPages and now shared with MyItem) returning the pending cursor when the bound truncates the list. - checkSeller uses the walk and skips the removal sweep while the list is truncated: an absent hash may sit on an unfetched page, so staying silent beats a false alarm. `user items --all` reuses the same walk. --- internal/cli/cli_test.go | 44 ++++++++++++++++++++++++++++++++++++++ internal/cli/item.go | 40 +++++----------------------------- internal/wallapop/items.go | 10 +++++---- internal/wallapop/users.go | 28 ++++++++++++++++++++++++ internal/watch/watch.go | 21 +++++++++++------- 5 files changed, 96 insertions(+), 47 deletions(-) diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index d11e191..fe779b5 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -672,6 +672,50 @@ func TestUserItemsAllPreservesPagesWhenLaterRequestFails(t *testing.T) { } } +// watch seller pagination (UserItemsAll) + +func TestSellerWatchWalksAllPages(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 2 + var items []*fakewallapop.Item + for i := 0; i < 3; i++ { + items = append(items, h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})) + } + h.must("", "watch", "add", "seller", "other-seller-68037934", "--name", "fran") + // The third item lives on page 2; removing a page-1 item must not + // ghost-remove it, and the real removal is reported exactly once. + items[0].Removed = true + r := h.must("", "watch", "check", "fran", "--format", "jsonl") + if strings.Count(r.stdout, `"item.removed"`) != 1 || !strings.Contains(r.stdout, "hash00000000") { + t.Fatalf("events:\n%s", r.stdout) + } + // The page-2 item is tracked: its removal is seen on the next check. + items[2].Removed = true + r = h.must("", "watch", "check", "fran", "--format", "jsonl") + if strings.Count(r.stdout, `"item.removed"`) != 1 || !strings.Contains(r.stdout, "hash00000002") { + t.Fatalf("page-2 item not tracked:\n%s", r.stdout) + } +} + +func TestSellerWatchDoesNotReportRemovedWhenWalkTruncates(t *testing.T) { + h := newHarness(t) + h.login() + h.fake.UserItemsPageSize = 1 + for i := 0; i < 55; i++ { + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash}) + } + h.must("", "watch", "add", "seller", "other-seller-68037934", "--name", "fran") + r := h.must("", "watch", "check", "fran") + if strings.Contains(r.stdout, `"item.removed"`) { + t.Fatalf("truncated walk must not report removals:\n%s", r.stdout) + } + // Both the baseline check (at add) and this check walked the bound. + if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 100 { + t.Fatalf("expected bounded 50 page requests per check, got %d", n) + } +} + // chat func TestChatSendPublishesWebShapedPayload(t *testing.T) { diff --git a/internal/cli/item.go b/internal/cli/item.go index 282b3e7..831cea2 100644 --- a/internal/cli/item.go +++ b/internal/cli/item.go @@ -613,7 +613,7 @@ Examples: return err } if itemsAll { - items, truncated, err := a.allUserItems(cmd.Context(), hash, itemsNext) + items, truncated, err := a.Client.UserItemsAll(cmd.Context(), hash, itemsNext) view := userItemsView{Items: items, NextPage: truncated} if err != nil { // The pages already fetched are still real data: print @@ -624,9 +624,10 @@ Examples: return err } if truncated != "" { - // The walk hit its bound: say so on stderr, and keep the cursor in - // the JSON so callers can pick up where this left off. - fmt.Fprintf(a.Stderr, "wallapop: warning: stopped after %d pages (%d items); more pages remain, continue with --next\n", maxUserItemPages, len(items)) + // The walk hit its bound, not the end of the list: + // say so on stderr, and keep the cursor in the JSON + // so callers can pick up where this left off. + fmt.Fprintf(a.Stderr, "wallapop: warning: stopped after %d pages (%d items); more pages remain, continue with --next\n", wallapop.MaxItemWalkPages, len(items)) } return a.Printer.Print(view) } @@ -673,37 +674,6 @@ Examples: return cmd } -// maxUserItemPages bounds `user items --all` (40 items per page, so 2000 -// items at most); hitting it is a warning, not an error. -const maxUserItemPages = 50 - -// allUserItems walks a seller's pages sequentially, from since ("" = start) -// until the cursor runs out or the bound is hit. When truncated, it returns -// the last cursor so the caller can warn and let consumers resume. -func (a *App) allUserItems(ctx context.Context, hash, since string) (items []wallapop.Item, truncated string, err error) { - items = []wallapop.Item{} - for page := 0; page < maxUserItemPages; page++ { - batch, cursor, err := a.Client.UserItemsPage(ctx, hash, since) - if err != nil { - // Keep what succeeded and the cursor to resume from; the caller - // prints the partial result and still reports this error. - return items, since, err - } - items = append(items, batch...) - if cursor == "" { - return items, "", nil - } - // A cursor repeated unchanged means the API stopped advancing the - // walk: report it as truncated (not exhausted) so the caller warns - // and can resume, instead of seeing an incomplete walk as complete. - if cursor == since { - return items, since, fmt.Errorf("user items pagination cursor did not advance (since=%q)", since) - } - since = cursor - } - return items, since, nil -} - func (a *App) meCmd() *cobra.Command { cmd := &cobra.Command{Use: "me", Short: "Your own account: profile, listings, favorites"} var sold bool diff --git a/internal/wallapop/items.go b/internal/wallapop/items.go index f97d44d..1d9cc53 100644 --- a/internal/wallapop/items.go +++ b/internal/wallapop/items.go @@ -114,7 +114,7 @@ func (c *Client) MyItem(ctx context.Context, ref string) (Item, error) { } next := "" more := false - for page := 0; page < maxOwnItemPages; page++ { + for page := 0; page < MaxItemWalkPages; page++ { mine, cursor, err := c.userItemsPage(ctx, "/api/v3/user/items", next, true, "") if err != nil { return Item{}, err @@ -131,13 +131,15 @@ func (c *Client) MyItem(ctx context.Context, ref string) (Item, error) { next = cursor } if more { - return Item{}, Usage("%s was not found in the first %d pages of your listings", ref, maxOwnItemPages) + return Item{}, Usage("%s was not found in the first %d pages of your listings", ref, MaxItemWalkPages) } return Item{}, Usage("%s is not one of your listings (see `wallapop me items`)", ref) } -// maxOwnItemPages bounds the walk through /user/items (40 per page). -const maxOwnItemPages = 50 +// MaxItemWalkPages bounds every walk over the 40-per-page items endpoints: +// MyItem's search through the account's listings and UserItemsAll's walk +// through a seller's listings. +const MaxItemWalkPages = 50 // slugMatches compares a canonical slug ("old-thing-123") with a reference // that is either that slug or its trailing numeric id ("123"). diff --git a/internal/wallapop/users.go b/internal/wallapop/users.go index 52b0639..d1cbd16 100644 --- a/internal/wallapop/users.go +++ b/internal/wallapop/users.go @@ -3,6 +3,7 @@ package wallapop import ( "context" "errors" + "fmt" "net/url" "strings" ) @@ -149,6 +150,33 @@ func (c *Client) UserItemsPage(ctx context.Context, hash, since string) ([]Item, return c.userItemsPage(ctx, "/api/v3/users/"+hash+"/items", since, false, hash) } +// UserItemsAll walks a seller's pages sequentially, from since ("" = start), +// until the cursor runs out or MaxItemWalkPages is hit. truncated carries the +// last cursor when the bound was reached ("" otherwise), so callers can tell +// an exhausted list from a bounded one and resume later. +func (c *Client) UserItemsAll(ctx context.Context, hash, since string) (items []Item, truncated string, err error) { + items = []Item{} + for page := 0; page < MaxItemWalkPages; page++ { + batch, cursor, err := c.UserItemsPage(ctx, hash, since) + if err != nil { + // Keep successful pages and the cursor for the failed request so + // callers can expose partial results and resume without restarting. + return items, since, err + } + items = append(items, batch...) + if cursor == "" { + return items, "", nil + } + // A repeated nonempty cursor is a stalled, incomplete walk, not + // successful exhaustion. Preserve it for callers and stop the loop. + if cursor == since { + return items, since, fmt.Errorf("user items pagination cursor did not advance (since=%q)", since) + } + since = cursor + } + return items, since, nil +} + // UserReviews lists the reviews a user has received. func (c *Client) UserReviews(ctx context.Context, hash string) ([]Review, error) { var raw []struct { diff --git a/internal/watch/watch.go b/internal/watch/watch.go index e45cc74..148e72c 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -191,7 +191,7 @@ func isExpired(prev store.Seen) bool { func checkSeller(ctx context.Context, c *wallapop.Client, w store.Watch, t SellerTarget, seen map[string]store.Seen, baseline bool) (Result, error) { var res Result - items, err := c.UserItems(ctx, t.Hash) + items, truncated, err := c.UserItemsAll(ctx, t.Hash, "") if err != nil { return Result{}, err } @@ -207,13 +207,18 @@ func checkSeller(ctx context.Context, c *wallapop.Client, w store.Watch, t Selle } res.Upserts = append(res.Upserts, seenOf(it)) } - // The seller's list is complete, so a missing hash really is gone. - for hash, prev := range seen { - if !current[hash] { - var last wallapop.Item - _ = json.Unmarshal(prev.Snapshot, &last) - res.Events = append(res.Events, event(w, "item.removed", last, nil)) - res.Removed = append(res.Removed, hash) + // The walk is complete, so a missing hash really is gone. When the bound + // truncated it, hashes outside the fetched pages may just sit on a later + // page: reporting them gone would be a false alarm, so stay silent and + // wait for a walk that fits (the seller may list less) or the next check. + if truncated == "" { + for hash, prev := range seen { + if !current[hash] { + var last wallapop.Item + _ = json.Unmarshal(prev.Snapshot, &last) + res.Events = append(res.Events, event(w, "item.removed", last, nil)) + res.Removed = append(res.Removed, hash) + } } } return res, nil From fa953bca09284081c1fdb43f825b5d0e3bd71914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jc=20Mi=C3=B1arro?= Date: Sun, 15 Nov 2026 15:07:25 +0100 Subject: [PATCH 4/4] fix(watch): keep seller watch safe when pagination stalls --- internal/cli/cli_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index fe779b5..64cb3c5 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -716,6 +716,21 @@ func TestSellerWatchDoesNotReportRemovedWhenWalkTruncates(t *testing.T) { } } +func TestSellerWatchDoesNotReportRemovedWhenCursorStalls(t *testing.T) { + h := newHarness(t) + h.login() + first := h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(0), Title: "Bike", Seller: fakewallapop.OtherHash}) + h.must("", "watch", "add", "seller", "other-seller-68037934", "--name", "fran") + h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(1), Title: "Bike", Seller: fakewallapop.OtherHash}) + first.Removed = true + h.fake.UserItemsPageSize = 1 + h.fake.UserItemsStickyCursor = "1" + r := h.run("", "watch", "check", "fran", "--format", "jsonl") + if r.code == 0 || strings.Contains(r.stdout, `"item.removed"`) { + t.Fatalf("stalled walk must fail without false removals, exit %d stdout:\n%s\nstderr:\n%s", r.code, r.stdout, r.stderr) + } +} + // chat func TestChatSendPublishesWebShapedPayload(t *testing.T) {