githubapi

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 16 Imported by: 0

README

internal/githubapi

Logic overview

The githubapi package contains GitHub API integration primitives:

  • GitHub App installation authentication via ghinstallation.
  • go-github REST client construction with optional Enterprise base URL override.
  • Request execution wrapper with retry and rate-limit-aware pause behavior.
  • Optional detailed dependency span emission for outbound GitHub calls when telemetry mode is detailed.
  • Typed REST endpoint client for org repos, contributor stats, commits, pull requests, pull reviews, and issue comments.
  • Rate-limit header parsing and decision policy.
  • LOC contributor-stats state machine for ready/warming/stale/fallback transitions.

API reference

Types
  • InstallationAuthConfig: inputs for GitHub App installation HTTP client construction.
  • RESTClient: wrapper around *github.Client.
  • RetryConfig: retry backoff settings.
  • HTTPDoer: HTTP client abstraction used by Client.
  • CallMetadata: metadata from Client.Do (attempt count, last rate headers, last decision).
  • Client: retry + rate-limit-aware API caller.
  • EndpointStatus: normalized endpoint status (ok, accepted, forbidden, not_found, conflict, unprocessable, unavailable, unknown).
  • Repository: typed org repository record.
  • OrgReposResult: typed list-org-repos payload and metadata.
  • ContributorWeek: typed weekly contributor record.
  • ContributorStats: typed contributor stats record.
  • ContributorStatsResult: typed contributor-stats payload and metadata.
  • RepoCommit: typed commit list row.
  • CommitListResult: typed list-commits payload and metadata.
  • CommitDetail: typed commit detail payload and metadata.
  • PullRequest: typed pull request row.
  • PullRequestListResult: typed list-pull-requests payload and metadata.
  • PullReview: typed pull review row.
  • PullReviewsResult: typed list-pull-reviews payload and metadata.
  • IssueComment: typed issue comment row.
  • IssueCommentsResult: typed list-issue-comments payload and metadata.
  • DataClient: typed endpoint client built on Client.
  • RateLimitHeaders: parsed GitHub limit headers.
  • Decision: policy decision (Allow, WaitFor, Reason).
  • RateLimitPolicy: threshold and backoff settings for limit handling.
  • LOCMode: LOC state enum (unknown, warming, ready, stale, fallback).
  • LOCState: persistent state for LOC transition logic.
  • LOCEvent: one LOC observation input.
  • LOCStateMachine: transition policy settings.
Functions
  • NewInstallationHTTPClient(cfg InstallationAuthConfig) (*http.Client, error): builds authenticated installation client using private key file.
  • NewGitHubRESTClient(httpClient *http.Client, apiBaseURL string) (*RESTClient, error): creates go-github client with optional base URL override.
  • NewClient(doer HTTPDoer, retry RetryConfig, ratePolicy RateLimitPolicy) *Client: constructs retry/rate-limit aware request client.
  • NewDataClient(baseURL string, requestClient *Client) (*DataClient, error): builds the typed endpoint client with optional API base URL override.
  • ParseRateLimitHeaders(header http.Header, statusCode int) RateLimitHeaders: parses limit and retry headers.
Methods
  • (*Client) Do(req *http.Request) (*http.Response, CallMetadata, error): executes request with retry and rate-limit decision handling and, when enabled, emits detailed OTel span events per attempt.
  • (*DataClient) ListOrgRepos(ctx context.Context, org string) (OrgReposResult, error): lists org repos with pagination and typed status handling.
  • (*DataClient) GetContributorStats(ctx context.Context, owner, repo string) (ContributorStatsResult, error): reads /stats/contributors with explicit 202/403/404/409/422 handling.
  • (*DataClient) ListRepoCommitsWindow(ctx context.Context, owner, repo string, since, until time.Time, maxCommits int) (CommitListResult, error): lists commits for a window with pagination and cap support.
  • (*DataClient) GetCommit(ctx context.Context, owner, repo, sha string) (CommitDetail, error): gets commit detail with additions/deletions and typed status handling.
  • (*DataClient) ListRepoPullRequestsWindow(ctx context.Context, owner, repo string, since, until time.Time) (PullRequestListResult, error): lists pull requests and filters to the requested window.
  • (*DataClient) ListPullReviews(ctx context.Context, owner, repo string, pullNumber int, since, until time.Time) (PullReviewsResult, error): lists pull reviews for one PR and filters to the requested window.
  • (*DataClient) ListIssueCommentsWindow(ctx context.Context, owner, repo string, since, until time.Time) (IssueCommentsResult, error): lists repository issue comments and filters to the requested window.
  • (RateLimitPolicy) Evaluate(headers RateLimitHeaders) Decision: determines allow/pause behavior from parsed headers.
  • (LOCStateMachine) Apply(previous LOCState, event LOCEvent) LOCState: applies LOC state transition rules.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewInstallationHTTPClient

func NewInstallationHTTPClient(cfg InstallationAuthConfig) (*http.Client, error)

NewInstallationHTTPClient creates an authenticated HTTP client for one GitHub App installation.

Types

type CallMetadata

type CallMetadata struct {
	Attempts        int
	LastRateHeaders RateLimitHeaders
	LastDecision    Decision
}

CallMetadata reports execution metadata for a client call.

type Client

type Client struct {

	// Sleep is injected for testability.
	Sleep func(duration time.Duration)
	// contains filtered or unexported fields
}

Client wraps GitHub HTTP requests with retry and rate-limit controls.

func NewClient

func NewClient(doer HTTPDoer, retry RetryConfig, ratePolicy RateLimitPolicy) *Client

NewClient creates a GitHub API client wrapper.

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, CallMetadata, error)

Do executes a request with retry and rate-limit awareness.

type CommitDetail

type CommitDetail struct {
	Status    EndpointStatus
	SHA       string
	Author    string
	Additions int
	Deletions int
	Total     int
	Metadata  CallMetadata
}

CommitDetail is a typed commit detail response.

type CommitListResult

type CommitListResult struct {
	Status    EndpointStatus
	Commits   []RepoCommit
	Truncated bool
	Metadata  CallMetadata
}

CommitListResult is the typed result for listing repository commits in a window.

type ContributorStats

type ContributorStats struct {
	User         string
	TotalCommits int
	Weeks        []ContributorWeek
}

ContributorStats is one contributor's aggregate stats payload.

type ContributorStatsResult

type ContributorStatsResult struct {
	Status       EndpointStatus
	Contributors []ContributorStats
	Metadata     CallMetadata
}

ContributorStatsResult is the typed result for `/stats/contributors`.

type ContributorWeek

type ContributorWeek struct {
	WeekStart time.Time
	Additions int
	Deletions int
	Commits   int
}

ContributorWeek is one contributor weekly summary from contributor stats.

type CopilotReportLinkResult added in v1.2.0

type CopilotReportLinkResult struct {
	Status         EndpointStatus
	URL            string
	DownloadLinks  []string
	ReportDay      time.Time
	ReportStartDay time.Time
	ReportEndDay   time.Time
	ExpiresAt      time.Time
	Metadata       CallMetadata
}

CopilotReportLinkResult is the typed result for Copilot report-link endpoints.

type CopilotReportStreamResult added in v1.2.0

type CopilotReportStreamResult struct {
	Status        EndpointStatus
	RecordsParsed int
	ParseErrors   int
	Metadata      CallMetadata
}

CopilotReportStreamResult is the typed result for streaming Copilot report NDJSON data.

type DataClient

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

DataClient is a typed GitHub REST data client for scrape-relevant endpoints.

func NewDataClient

func NewDataClient(baseURL string, requestClient *Client) (*DataClient, error)

NewDataClient creates a typed data client over the generic retry/rate-limit request client.

func (*DataClient) GetCommit

func (c *DataClient) GetCommit(ctx context.Context, owner, repo, sha string) (CommitDetail, error)

GetCommit reads commit detail including additions/deletions.

func (*DataClient) GetContributorStats

func (c *DataClient) GetContributorStats(ctx context.Context, owner, repo string) (ContributorStatsResult, error)

GetContributorStats reads contributor weekly stats for one repository.

func (c *DataClient) GetEnterpriseCopilotEnterprise1DayReportLink(
	ctx context.Context,
	enterprise string,
	day time.Time,
) (CopilotReportLinkResult, error)

GetEnterpriseCopilotEnterprise1DayReportLink gets an enterprise 1-day aggregate report link.

func (c *DataClient) GetEnterpriseCopilotEnterprise28DayLatestReportLink(
	ctx context.Context,
	enterprise string,
) (CopilotReportLinkResult, error)

GetEnterpriseCopilotEnterprise28DayLatestReportLink gets an enterprise 28-day latest aggregate report link.

func (c *DataClient) GetEnterpriseCopilotUsers1DayReportLink(
	ctx context.Context,
	enterprise string,
	day time.Time,
) (CopilotReportLinkResult, error)

GetEnterpriseCopilotUsers1DayReportLink gets an enterprise 1-day user report link.

func (c *DataClient) GetEnterpriseCopilotUsers28DayLatestReportLink(
	ctx context.Context,
	enterprise string,
) (CopilotReportLinkResult, error)

GetEnterpriseCopilotUsers28DayLatestReportLink gets an enterprise 28-day latest user report link.

func (c *DataClient) GetOrgCopilotOrganization1DayReportLink(
	ctx context.Context,
	org string,
	day time.Time,
) (CopilotReportLinkResult, error)

GetOrgCopilotOrganization1DayReportLink gets an org 1-day aggregate report link.

func (c *DataClient) GetOrgCopilotOrganization28DayLatestReportLink(
	ctx context.Context,
	org string,
) (CopilotReportLinkResult, error)

GetOrgCopilotOrganization28DayLatestReportLink gets an org 28-day latest aggregate report link.

func (c *DataClient) GetOrgCopilotUsers1DayReportLink(
	ctx context.Context,
	org string,
	day time.Time,
) (CopilotReportLinkResult, error)

GetOrgCopilotUsers1DayReportLink gets an org 1-day user report link.

func (c *DataClient) GetOrgCopilotUsers28DayLatestReportLink(
	ctx context.Context,
	org string,
) (CopilotReportLinkResult, error)

GetOrgCopilotUsers28DayLatestReportLink gets an org 28-day latest user report link.

func (*DataClient) ListIssueCommentsWindow

func (c *DataClient) ListIssueCommentsWindow(ctx context.Context, owner, repo string, since, until time.Time) (IssueCommentsResult, error)

ListIssueCommentsWindow lists repository issue comments filtered to a window.

func (*DataClient) ListOrgRepos

func (c *DataClient) ListOrgRepos(ctx context.Context, org string) (OrgReposResult, error)

ListOrgRepos lists repositories for an organization and falls back to user repositories on 404.

func (*DataClient) ListPullReviews

func (c *DataClient) ListPullReviews(ctx context.Context, owner, repo string, pullNumber int, since, until time.Time) (PullReviewsResult, error)

ListPullReviews lists reviews for one pull request and filters them to a window.

func (*DataClient) ListRepoCommitsWindow

func (c *DataClient) ListRepoCommitsWindow(ctx context.Context, owner, repo string, since, until time.Time, maxCommits int) (CommitListResult, error)

ListRepoCommitsWindow lists repository commits in a time window with pagination and optional cap.

func (*DataClient) ListRepoPullRequestsWindow

func (c *DataClient) ListRepoPullRequestsWindow(ctx context.Context, owner, repo string, since, until time.Time) (PullRequestListResult, error)

ListRepoPullRequestsWindow lists repository pull requests and filters them to a window.

func (*DataClient) StreamCopilotReportNDJSON added in v1.2.0

func (c *DataClient) StreamCopilotReportNDJSON(
	ctx context.Context,
	signedReportURL string,
	handler func(record map[string]any) error,
) (CopilotReportStreamResult, error)

StreamCopilotReportNDJSON downloads and line-parses a Copilot report payload.

type Decision

type Decision struct {
	Allow   bool
	WaitFor time.Duration
	Reason  string
}

Decision represents a rate-limit action decision.

type EndpointStatus

type EndpointStatus string

EndpointStatus represents a normalized GitHub API endpoint outcome.

const (
	// EndpointStatusOK indicates a successful response.
	EndpointStatusOK EndpointStatus = "ok"
	// EndpointStatusAccepted indicates GitHub accepted the request and is still computing results.
	EndpointStatusAccepted EndpointStatus = "accepted"
	// EndpointStatusForbidden indicates authorization failure or restricted access.
	EndpointStatusForbidden EndpointStatus = "forbidden"
	// EndpointStatusNotFound indicates the resource does not exist or is hidden.
	EndpointStatusNotFound EndpointStatus = "not_found"
	// EndpointStatusConflict indicates a state conflict, like unsupported stats on empty repositories.
	EndpointStatusConflict EndpointStatus = "conflict"
	// EndpointStatusUnprocessable indicates request validation/processing failure.
	EndpointStatusUnprocessable EndpointStatus = "unprocessable"
	// EndpointStatusUnavailable indicates a temporary service-side failure.
	EndpointStatusUnavailable EndpointStatus = "unavailable"
	// EndpointStatusUnknown indicates an unclassified non-success status.
	EndpointStatusUnknown EndpointStatus = "unknown"
)

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer is implemented by http.Client.

type InstallationAuthConfig

type InstallationAuthConfig struct {
	AppID          int64
	InstallationID int64
	PrivateKeyPath string
	Timeout        time.Duration
	BaseTransport  http.RoundTripper
}

InstallationAuthConfig configures GitHub App installation authentication.

type IssueComment

type IssueComment struct {
	ID        int64
	User      string
	CreatedAt time.Time
}

IssueComment is one repository issue comment.

type IssueCommentsResult

type IssueCommentsResult struct {
	Status   EndpointStatus
	Comments []IssueComment
	Metadata CallMetadata
}

IssueCommentsResult is the typed result for listing repository issue comments.

type LOCEvent

type LOCEvent struct {
	ObservedAt             time.Time
	HTTPStatus             int
	StatsPresent           bool
	ContributionsNonZero   bool
	AdditionsDeletionsZero bool
}

LOCEvent represents one contributor-stats observation.

type LOCMode

type LOCMode string

LOCMode represents the contributor-stats processing mode.

const (
	// LOCModeUnknown is the initial mode before first observation.
	LOCModeUnknown LOCMode = "unknown"
	// LOCModeWarming indicates contributor stats are still being generated.
	LOCModeWarming LOCMode = "warming"
	// LOCModeReady indicates contributor stats are available and usable.
	LOCModeReady LOCMode = "ready"
	// LOCModeStale indicates contributor stats have remained unavailable too long.
	LOCModeStale LOCMode = "stale"
	// LOCModeFallback indicates commit-stat fallback mode is active.
	LOCModeFallback LOCMode = "fallback"
)

type LOCState

type LOCState struct {
	Mode                   LOCMode
	Consecutive202         int
	ConsecutiveZeroWindows int
	LastReadyAt            time.Time
	FallbackUntil          time.Time
	LastObservedAt         time.Time
}

LOCState tracks contributor-stats state transitions.

type LOCStateMachine

type LOCStateMachine struct {
	RefreshInterval       time.Duration
	StaleWindowMultiplier int
	ZeroDetectionWindows  int
	FallbackCooldown      time.Duration
}

LOCStateMachine configures transition rules.

func (LOCStateMachine) Apply

func (m LOCStateMachine) Apply(previous LOCState, event LOCEvent) LOCState

Apply applies an event to a previous state and returns a new state.

type OrgReposResult

type OrgReposResult struct {
	Status   EndpointStatus
	Repos    []Repository
	Metadata CallMetadata
}

OrgReposResult is the typed result for listing organization repositories.

type PullRequest

type PullRequest struct {
	Number    int
	User      string
	CreatedAt time.Time
	UpdatedAt time.Time
	MergedAt  time.Time
}

PullRequest is one pull request summary.

type PullRequestListResult

type PullRequestListResult struct {
	Status       EndpointStatus
	PullRequests []PullRequest
	Metadata     CallMetadata
}

PullRequestListResult is the typed result for listing pull requests in a window.

type PullReview

type PullReview struct {
	ID          int64
	User        string
	State       string
	SubmittedAt time.Time
}

PullReview is one pull request review submission.

type PullReviewsResult

type PullReviewsResult struct {
	Status   EndpointStatus
	Reviews  []PullReview
	Metadata CallMetadata
}

PullReviewsResult is the typed result for listing pull reviews.

type RESTClient

type RESTClient struct {
	Client *github.Client
}

RESTClient wraps the go-github REST client.

func NewGitHubRESTClient

func NewGitHubRESTClient(httpClient *http.Client, apiBaseURL string) (*RESTClient, error)

NewGitHubRESTClient creates a go-github client with optional API base URL override.

type RateLimitHeaders

type RateLimitHeaders struct {
	Remaining        int
	ResetUnix        int64
	Used             int
	RetryAfter       time.Duration
	SecondaryLimited bool
}

RateLimitHeaders contains parsed GitHub rate-limit response headers.

func ParseRateLimitHeaders

func ParseRateLimitHeaders(header http.Header, statusCode int) RateLimitHeaders

ParseRateLimitHeaders parses rate-limit and retry headers.

type RateLimitPolicy

type RateLimitPolicy struct {
	MinRemainingThreshold int
	MinResetBuffer        time.Duration
	SecondaryLimitBackoff time.Duration
	Now                   func() time.Time
}

RateLimitPolicy evaluates rate-limit actions from parsed headers.

func (RateLimitPolicy) Evaluate

func (p RateLimitPolicy) Evaluate(headers RateLimitHeaders) Decision

Evaluate decides whether calls may continue or should pause.

type RepoCommit

type RepoCommit struct {
	SHA            string
	Author         string
	Committer      string
	AuthorName     string
	AuthorEmail    string
	CommitterName  string
	CommitterEmail string
	CommittedAt    time.Time
}

RepoCommit is one commit summary from the commit list endpoint.

type Repository

type Repository struct {
	Name          string
	FullName      string
	DefaultBranch string
	Archived      bool
	Disabled      bool
	Fork          bool
}

Repository is one GitHub repository in an organization.

type RetryConfig

type RetryConfig struct {
	MaxAttempts    int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

RetryConfig configures GitHub client retry behavior.

Jump to

Keyboard shortcuts

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