api

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package github reads pull requests over GitHub's HTTPS API, batching every pull request of a sweep into aliased GraphQL queries.

Index

Constants

View Source
const (
	StateOpen   = "OPEN"
	StateMerged = "MERGED"
	StateClosed = "CLOSED"
)
View Source
const BriefFilesMax = 300

BriefFilesMax bounds the changed files BriefFacts lists.

View Source
const DiscoveryFirst = 10

DiscoveryFirst is the first page size of the fast discovery searches: a search pays its first times every nested connection, and a quiet window returns a handful of pull requests.

View Source
const MaxThreads = 50

MaxThreads caps the review threads Threads reads of one pull request.

View Source
const SearchFirst = 100

SearchFirst is the page size of a listing expected to fill pages.

View Source
const SearchesPerRequest = 3

SearchesPerRequest bounds the searches one SearchCandidatesEach request carries: GitHub refuses a request that reads 100 candidates.

View Source
const StubBatch = 40

StubBatch is the largest by-ref stub batch GitHub prices at one point.

View Source
const TokenRecheck = time.Minute

TokenRecheck is the least time between two reads of a refused token.

Variables

View Source
var (
	ErrRateLimited  error = &unavailable{"GitHub rate limited"}
	ErrUnavailable  error = &unavailable{"GitHub unreachable"}
	ErrUnauthorized       = errors.New("GitHub token refused")
	ErrEmpty              = errors.New("GitHub returned an empty response")
)
View Source
var ErrBudget = errors.New("GitHub budget low")

Functions

func DefaultHost

func DefaultHost() string

DefaultHost is the host gh uses when none is named: GH_HOST, else the one host gh's hosts.yml lists, else github.com.

func PickByBranch

func PickByBranch(matches []BranchMatch) (int, string)

PickByBranch accepts a single match, or a single open one among several: branch names repeat across time, and a guess could revive a finished review.

func Transient

func Transient(err error) bool

Transient says whether err is worth a split or a later retry: 502, 503, 504, an attempt timeout, a GraphQL timeout, ErrUnavailable or ErrEmpty. The caller's own cancellation or deadline never is.

func ValidLogin

func ValidLogin(s string) bool

func WithPriority

func WithPriority(ctx context.Context, p Priority) context.Context

WithPriority tags ctx.

Types

type BranchMatch

type BranchMatch struct {
	Number int
	State  string
}

type BranchQuery

type BranchQuery struct {
	Owner, Repo, Branch string
}

type BriefFacts

type BriefFacts struct {
	Title, Body string
	Files       []BriefFile
	// MoreFiles is how many changed files are past BriefFilesMax.
	MoreFiles int
	// Issue is the first issue the pull request closes, nil when none.
	Issue *BriefIssue
}

BriefFacts is what a brief reads of a pull request besides its diff.

type BriefFile

type BriefFile struct {
	Path                 string
	Additions, Deletions int
}

type BriefIssue

type BriefIssue struct{ Title, Body string }

type BudgetError

type BudgetError struct {
	Limit    Limit
	Priority Priority
}

BudgetError is a call refused because its bucket fell below the floor of its priority.

func (*BudgetError) Error

func (e *BudgetError) Error() string

func (*BudgetError) Is

func (e *BudgetError) Is(target error) bool

type Candidate

type Candidate struct {
	Ref            pr.Ref    `json:"ref"`
	URL            string    `json:"url"`
	Title          string    `json:"title"`
	Author         string    `json:"author"`
	State          string    `json:"state"`
	IsDraft        bool      `json:"draft"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	Additions      int       `json:"additions"`
	Deletions      int       `json:"deletions"`
	ChangedFiles   int       `json:"changed_files"`
	HeadBranch     string    `json:"head"`
	BaseBranch     string    `json:"base"`
	ReviewDecision string    `json:"review_decision"`
	ReviewRequests []string  `json:"review_requests"` // logins and team:org/slug
	ChecksState    string    `json:"checks"`
	Comments       int       `json:"comments"`
	// MyReview is the viewer's latest review state, "" when none.
	MyReview       string `json:"my_review"`
	MyReviewOnHead bool   `json:"my_review_on_head"`
}

Candidate is a pull request Explore found, with what deciding whether to help on it needs.

type CandidatePage

type CandidatePage struct {
	Candidates []Candidate
	Total      int
	RateLimit  RateLimit
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the loop's one connection to GitHub. Safe for concurrent use.

func NewClient

func NewClient(o Options) *Client

func (*Client) Allow

func (c *Client) Allow(p Priority) bool

Allow says, without I/O, whether a call of p would be admitted now on the GraphQL bucket, the one every job spends.

func (*Client) Basics

func (c *Client) Basics(ctx context.Context, r Ref) (*pr.PullRequest, error)

func (*Client) BriefFacts

func (c *Client) BriefFacts(ctx context.Context, ref Ref) (BriefFacts, error)

BriefFacts reads ref's title, body, first closing issue and changed files in one GraphQL call, and one more per further 100 files up to BriefFilesMax.

func (*Client) Budget

func (c *Client) Budget() map[Resource]Limit

Budget is the lowest live bucket of each resource seen so far.

func (*Client) CandidateByRef

func (c *Client) CandidateByRef(ctx context.Context, ref Ref, viewer string) (CandidatePage, error)

CandidateByRef reads one pull request as a candidate, in any state.

func (*Client) Diff

func (c *Client) Diff(ctx context.Context, ref Ref, limit int) (diff []byte, cut bool, err error)

Diff reads ref's diff, at most limit bytes when limit > 0: it reads limit+1 bytes and closes the response, with cut true when there were more.

func (*Client) FindByBranch

func (c *Client) FindByBranch(ctx context.Context, queries []BranchQuery) (map[BranchQuery][]BranchMatch, error)

func (*Client) GraphQL

func (c *Client) GraphQL(ctx context.Context, query string, vars map[string]any) (map[string]json.RawMessage, map[string]string, error)

GraphQL posts a read query and returns the data by top-level alias and the error per alias; an error with no alias in its path fails the whole call. It refuses a document with a mutation or a subscription. The cost a selected rateLimit reports goes to the meter.

func (*Client) InventoryByRef

func (c *Client) InventoryByRef(ctx context.Context, refs []Ref) (map[Ref]Snapshot, map[Ref]error, RateLimit, error)

InventoryByRef reads full snapshots by reference. The rate limit adds up the cost of every batch and keeps the budget the last one reported.

func (*Client) IsUser

func (c *Client) IsUser(ctx context.Context, login string) (bool, error)

IsUser reports whether login names a GitHub user; an organization or an unknown login is not one.

func (*Client) REST

func (c *Client) REST(ctx context.Context, r Request) (Response, error)

REST sends r. A 304 is a Response with Status 304 and no error; any other status outside 2xx is a *StatusError, with the Response.

func (*Client) Restore

func (c *Client) Restore(limits []Limit)

Restore seeds the budget, as a store kept it; a bucket already reset is dropped.

func (*Client) SearchCandidates

func (c *Client) SearchCandidates(ctx context.Context, q, viewer string, first int) (CandidatePage, error)

SearchCandidates reads the first page of a pull request search; viewer names whose review is "mine", "" asks for none. It does not retry: the caller pauses before it does.

func (*Client) SearchCandidatesEach

func (c *Client) SearchCandidatesEach(ctx context.Context, qs []string, viewer string, first int) (pages []CandidatePage, errs []error, err error)

SearchCandidatesEach reads the first page of each search in qs as aliases of one GraphQL request, the pages in the order of qs; every page carries the request's rate limit, and errs holds, per query, the error of that search alone. It does not retry: the caller pauses before it does.

func (*Client) SearchStubs

func (c *Client) SearchStubs(ctx context.Context, q, after string) (StubPage, error)

SearchStubs reads one page of a pull request search; after is the previous page's EndCursor, empty for the first page.

func (*Client) SearchStubsFirst

func (c *Client) SearchStubsFirst(ctx context.Context, qs []string, first int) (pages []StubPage, errs []error, err error)

SearchStubsFirst reads the first page, of first stubs, of every query in one request; errs holds, per query, the error of that search alone.

func (*Client) SetFloors

func (c *Client) SetFloors(f Floors)

SetFloors replaces the floors the client admits calls by.

func (*Client) StubsByRef

func (c *Client) StubsByRef(ctx context.Context, refs []Ref) (map[Ref]Stub, map[Ref]error, error)

StubsByRef reads the stub of every ref in requests of StubBatch aliases. errs holds the refs GitHub did not return; err fails the whole read.

func (*Client) TeamMembers

func (c *Client) TeamMembers(ctx context.Context, org, slug string) ([]string, error)

func (*Client) Threads

func (c *Client) Threads(ctx context.Context, refs map[Ref]int) (threads map[Ref][]pr.Thread, errs map[Ref]error, err error)

Threads reads the unresolved threads among the newest refs[ref] review threads of each ref, at most MaxThreads, in batches of 20 aliases. Per-ref failures are in errs; a failed request is err, returned with what the earlier requests read.

func (*Client) Viewer

func (c *Client) Viewer(ctx context.Context) (string, error)

type DatedCommit

type DatedCommit struct {
	Oid     string
	Parents int
	At      time.Time
}

type DraftEvent

type DraftEvent struct {
	Actor string
	At    time.Time
}

DraftEvent is the pull request going back to draft.

type Floors

type Floors struct{ User, Background float64 }

Floors are, per priority, the fraction of Limit below which a call of that priority is refused until the bucket resets.

func DefaultFloors

func DefaultFloors(f float64) Floors

DefaultFloors takes plugins.github.rate_limit_fraction as f.

type Limit

type Limit struct {
	Resource         Resource
	Limit, Remaining int
	ResetAt          time.Time
}

Limit is one bucket as a response reported it.

type Meter

type Meter func(ctx context.Context, s Sample)

Meter hears the client's samples.

type Options

type Options struct {
	// Host is the GitHub hostname as gh names it; empty is DefaultHost(). A
	// host other than github.com is served the Enterprise Server layout
	// (/api/v3 and /api/graphql); it may carry its scheme.
	Host string
	// Base is the transport; nil is HTTP/2 with IdleConnTimeout 30 s and
	// MaxIdleConnsPerHost 4.
	Base http.RoundTripper
	// Token is nil for `gh auth token --hostname <Host>`; it runs once, and
	// again after a 401 at most once per TokenRecheck.
	Token func(ctx context.Context) (string, error)
	// Floors is zero for DefaultFloors(0.5).
	Floors      Floors
	Retry       Retry
	MaxInFlight int           // 2; one slot is kept for PriorityUser
	Timeout     time.Duration // per attempt; 30 s
	Now         func() time.Time
	Sleep       func(ctx context.Context, d time.Duration) error
	// GH runs gh for the token; nil is gh on the PATH.
	GH gh.Runner
	// UserAgent names the caller to GitHub.
	UserAgent string
	// Meter hears every request and every cost a response reported; nil
	// meters nothing.
	Meter Meter
}

type Priority

type Priority uint8

Priority orders who may spend the budget when it runs low.

const (
	PriorityUser       Priority = iota // a user action; keeps the reserve
	PriorityBackground                 // jobs and reads the plugin runs on its own
)

func PriorityOf

func PriorityOf(ctx context.Context) Priority

PriorityOf is the priority ctx is tagged with, else the one the host's call carries.

type RateLimit

type RateLimit struct {
	Cost      int       `json:"cost"`
	Remaining int       `json:"remaining"`
	Limit     int       `json:"limit"`
	ResetAt   time.Time `json:"reset_at"`
}

type RateLimitedError

type RateLimitedError struct {
	Resource  Resource
	RetryAt   time.Time
	Secondary bool
}

RateLimitedError is a resource GitHub asked to leave alone until RetryAt. Secondary is a secondary (abuse) limit; otherwise the bucket ran out.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

func (*RateLimitedError) Is

func (e *RateLimitedError) Is(target error) bool

type Ref

type Ref = pr.Ref

func ParseURL

func ParseURL(raw string) (Ref, error)

type Request

type Request struct {
	Method, Path, Accept         string // Path from the host root, with its query
	IfNoneMatch, IfModifiedSince string
	MaxBytes                     int64 // > 0: read at most this many body bytes, then close
	Body                         []byte
	// Mutation is never retried once its request was written; only a failure
	// before the write (dial, breaker) is retried.
	Mutation bool
}

Request is a REST call.

type Resource

type Resource string

Resource is a rate-limit bucket family, as x-ratelimit-resource names it.

const (
	ResourceGraphQL Resource = "graphql"
	ResourceCore    Resource = "core"
	ResourceSearch  Resource = "search"
)

type Response

type Response struct {
	Status       int
	Body         []byte
	Truncated    bool // the body had more than MaxBytes
	ETag         string
	LastModified string
	PollInterval time.Duration
	Limit        Limit
	// contains filtered or unexported fields
}

type Retry

type Retry struct {
	Attempts   int           // tries in all; 3
	Base, Max  time.Duration // full-jitter backoff bounds; 1 s, 30 s
	BreakAfter int           // consecutive network failures that open the breaker; 3
	BreakFor   time.Duration // how long the open breaker fails fast; 60 s
}

Retry bounds the retries of one call and the breaker every call shares.

type ReviewRequestEvent

type ReviewRequestEvent struct {
	Reviewer string
	Actor    string
	At       time.Time
}

type Sample

type Sample struct {
	Op          string
	Spawn       bool
	Dur         time.Duration
	Failed      bool
	NotModified bool
	Points      int64
	Bytes       int64
	Spend       bool
}

Sample is one request the client sent, or, with Spend, the points a response reported for a request already counted.

type Snapshot

type Snapshot struct {
	pr.PullRequest
	URL            string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	MergedAt       time.Time
	ClosedAt       time.Time
	LastEditedAt   time.Time // last edit of the description; zero when never edited
	ChangedFiles   int
	ReadyAt        time.Time
	ReviewRequests []ReviewRequestEvent
	CommitsDated   []DatedCommit
	MergedBy       string
	MergeCommit    string
	Drafts         []DraftEvent
	RemovedReviews []ReviewRequestEvent
	// TimelineMissed counts the earliest timeline events the read left out.
	TimelineMissed int
	// ThreadsRead says OpenThreads is known: Threads read it, or there are
	// no threads. A full read only counts them.
	ThreadsRead bool
}

Snapshot is one pull request as the inventory sees it.

type StatusError

type StatusError struct {
	Status  int
	Message string
}

StatusError is a response GitHub answered with a status the call does not take as an answer.

func (*StatusError) Error

func (e *StatusError) Error() string

type Stub

type Stub struct {
	Ref            Ref
	Author         string
	UpdatedAt      time.Time
	IsDraft        bool
	HeadOid        string
	ReviewDecision string
	ReviewRequests []string // logins and team:org/slug
	NameWithOwner  string
	// ChecksState is the head commit's status check rollup, as in Snapshot:
	// checks concluding do not move UpdatedAt.
	ChecksState string
	// FailedChecks are the names of the head's failed checks, sorted: a
	// check can fail or recover without moving UpdatedAt or the rollup.
	FailedChecks []string
	State        string // OPEN, CLOSED or MERGED
	// Mergeable, as in PullRequest: a base that moves leaves UpdatedAt.
	Mergeable string
}

Stub is what the cheap search or by-ref read returns: enough to decide whether to read the full snapshot.

type StubPage

type StubPage struct {
	Stubs     []Stub
	HasNext   bool
	EndCursor string
	RateLimit RateLimit
}

Directories

Path Synopsis
Package apitest serves an api.Client from gh fakes, as the plugin's tests write them, and records what it meters.
Package apitest serves an api.Client from gh fakes, as the plugin's tests write them, and records what it meters.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL