Skip to content

HTTP wrapper: Add helper for link header pagination#355

Merged
ggreer merged 1 commit intomainfrom
ggreer/pagination
Apr 24, 2025
Merged

HTTP wrapper: Add helper for link header pagination#355
ggreer merged 1 commit intomainfrom
ggreer/pagination

Conversation

@ggreer
Copy link
Contributor

@ggreer ggreer commented Apr 16, 2025

Inspired by baton-http.

This was the trickiest of the pagination options. I'll update this PR with the simpler ones.

Summary by CodeRabbit

  • New Features

    • Added support for extracting next page links from HTTP headers to enable NextLink pagination in API responses.
  • Tests

    • Introduced tests to verify correct parsing of HTTP Link headers for pagination.

@coderabbitai
Copy link

coderabbitai bot commented Apr 16, 2025

Walkthrough

A new pagination utility has been introduced in the uhttp package to support handling HTTP pagination via the NextLink pattern. The implementation includes a configuration struct for customizing header parsing, a parser for extracting pagination URLs from HTTP Link headers, and a function to manage pagination state using the parsed information. Additionally, a test has been added to verify the correctness of the Link header parsing logic.

Changes

File(s) Change Summary
pkg/uhttp/pagination.go Added utilities for NextLink HTTP pagination, including config struct, header parser, and state handler.
pkg/uhttp/pagination_test.go Added a unit test for the Link header parsing function.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant PaginationUtil

    Client->>Server: Send HTTP request
    Server-->>Client: Respond with Link header (includes next page URL)
    Client->>PaginationUtil: Call WithNextLinkPagination with response
    PaginationUtil->>PaginationUtil: Parse Link header
    PaginationUtil->>Client: Store next page token in pagination bag
Loading

Poem

In the warren of headers, a link may appear,
A "next" for the journey, the path is now clear.
With parsing and mapping, the tokens in tow,
The rabbit hops forward—onward we go!
Through pages and tokens, we bound without fear,
Pagination made simple, the next hop is here!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/uhttp/pagination.go (1)

28-62: Well-implemented Link header parsing, consider enhancing validation.

The function effectively parses Link headers with good handling of basic cases. However, consider these improvements:

  1. Add URL validation to ensure extracted URLs are well-formed
  2. Document the behavior for duplicate rel values (current implementation will silently use the last occurrence)
  3. Consider adding more specific error types for different parsing failures
func parseLinkHeader(header string) (map[string]string, error) {
	if header == "" {
		// Empty header is fine, it just means there are no more pages.
		return nil, nil
	}

	links := make(map[string]string)
	headerLinks := strings.Split(header, ",")
	for _, headerLink := range headerLinks {
		linkParts := strings.Split(headerLink, ";")
		if len(linkParts) < 2 {
			continue
		}
		linkUrl := strings.TrimSpace(linkParts[0])
		linkUrl = strings.Trim(linkUrl, "<>")
+		// Validate URL format
+		if _, err := url.Parse(linkUrl); err != nil {
+			return nil, fmt.Errorf("invalid URL in link header: %w", err)
+		}
		var relValue string
		for _, rel := range linkParts[1:] {
			rel = strings.TrimSpace(rel)
			relParts := strings.Split(rel, "=")
			if len(relParts) < 2 {
				continue
			}
			if relParts[0] == "rel" {
				relValue = strings.Trim(relParts[1], "\"")
				break
			}
		}
		if relValue == "" {
			continue
		}
+		// Consider adding a check for duplicates 
+		if _, exists := links[relValue]; exists {
+			// Either log, return error, or document that we're overwriting
+		}
		links[relValue] = linkUrl
	}

	return links, nil
}

Don't forget to add the necessary imports:

import (
	"fmt"
	"net/url"
	// existing imports...
)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c9cb24f and c12bc5d.

📒 Files selected for processing (2)
  • pkg/uhttp/pagination.go (1 hunks)
  • pkg/uhttp/pagination_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/uhttp/pagination.go (2)
pkg/pagination/pagination.go (2)
  • Bag (31-34)
  • PageState (23-27)
pkg/uhttp/wrapper.go (2)
  • DoOption (98-98)
  • WrapperResponse (37-42)
🔇 Additional comments (1)
pkg/uhttp/pagination.go (1)

64-99: Good implementation with sensible defaults.

The function handles NextLink pagination well with appropriate defaults and proper error handling. Consider these minor improvements:

  1. Add more context to the error returned from parseLinkHeader
  2. Consider validating or sanitizing the next link URL before pushing it to the pagination bag

Comment on lines +9 to +23
// Parses the link header and returns a map of rel values to URLs.
func TestParseLinkHeader(t *testing.T) {
//nolint:revive // This is fine
// Example link header value: <https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"

//nolint:revive // This is fine
header := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"`

links, err := parseLinkHeader(header)
require.Nil(t, err)
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=2", links["prev"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=515", links["last"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=1", links["first"])
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance test coverage with edge cases.

The test effectively verifies the happy path, but would benefit from additional test cases:

  1. Empty header handling
  2. Malformed header formats
  3. Headers with missing rel attributes
  4. Headers with duplicate rel attributes
  5. Headers with invalid URL formats

Also, consider using require.NoError(t, err) instead of require.Nil(t, err) for more idiomatic Go error assertion.

func TestParseLinkHeader(t *testing.T) {
	//nolint:revive // This is fine
	// Example link header value: <https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"

	//nolint:revive // This is fine
	header := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"`

	links, err := parseLinkHeader(header)
-	require.Nil(t, err)
+	require.NoError(t, err)
	require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=2", links["prev"])
	require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"])
	require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=515", links["last"])
	require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=1", links["first"])
+
+	// Test empty header
+	links, err = parseLinkHeader("")
+	require.NoError(t, err)
+	require.Nil(t, links)
+
+	// Test malformed header
+	malformedHeader := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev" <https://api.github.com/repositories/1300192/issues?page=4>`
+	links, err = parseLinkHeader(malformedHeader)
+	require.NoError(t, err)
+	require.Len(t, links, 1)
+
+	// Test duplicate rel values
+	duplicateRelHeader := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="next", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next"`
+	links, err = parseLinkHeader(duplicateRelHeader)
+	require.NoError(t, err)
+	require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"], "Should use the last occurrence for duplicate rel values")
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Parses the link header and returns a map of rel values to URLs.
func TestParseLinkHeader(t *testing.T) {
//nolint:revive // This is fine
// Example link header value: <https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"
//nolint:revive // This is fine
header := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"`
links, err := parseLinkHeader(header)
require.Nil(t, err)
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=2", links["prev"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=515", links["last"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=1", links["first"])
}
// Parses the link header and returns a map of rel values to URLs.
func TestParseLinkHeader(t *testing.T) {
//nolint:revive // This is fine
// Example link header value: <https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"
//nolint:revive // This is fine
header := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next", <https://api.github.com/repositories/1300192/issues?page=515>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"`
links, err := parseLinkHeader(header)
require.NoError(t, err)
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=2", links["prev"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=515", links["last"])
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=1", links["first"])
// Test empty header
links, err = parseLinkHeader("")
require.NoError(t, err)
require.Nil(t, links)
// Test malformed header
malformedHeader := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="prev" <https://api.github.com/repositories/1300192/issues?page=4>`
links, err = parseLinkHeader(malformedHeader)
require.NoError(t, err)
require.Len(t, links, 1)
// Test duplicate rel values
duplicateRelHeader := `<https://api.github.com/repositories/1300192/issues?page=2>; rel="next", <https://api.github.com/repositories/1300192/issues?page=4>; rel="next"`
links, err = parseLinkHeader(duplicateRelHeader)
require.NoError(t, err)
require.Equal(t, "https://api.github.com/repositories/1300192/issues?page=4", links["next"], "Should use the last occurrence for duplicate rel values")
}


/*
* Uhttp pagination handling.
* There are three common types of pagination:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure how common it is (maybe its not very), but for the Rootly API which followed the JSONAPI spec, links are included as part of the body, separate from data: https://github.com/ConductorOne/baton-rootly/blob/main/pkg/connector/client/models.go#L36

thought i'd mention for awareness

Copy link
Contributor

@gontzess gontzess left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! happy to take another look after you add the other easy cases, if you'd like

@ggreer ggreer merged commit 2576903 into main Apr 24, 2025
4 checks passed
@ggreer ggreer deleted the ggreer/pagination branch April 24, 2025 23:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants