pkg

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: BSD-2-Clause Imports: 29 Imported by: ? modules, 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 pkg implements the GitHub build watcher service. It polls the GitHub Actions API for failed CI workflow runs on default branches, derives a per-repo green/red state, and publishes CreateTaskCommand to Kafka on green → red transitions.

Index

Constants

View Source
const (
	GitHubAPIBucketCore    = "core"
	GitHubAPIBucketSearch  = "search"
	GitHubAPIBucketGraphQL = "graphql"
)

GitHub rate-limit buckets. Each is an independent quota: core is the installation token's hourly budget, search is 30/min, graphql is metered in points.

View Source
const DefaultCursorPath = "/data/cursor.json"

DefaultCursorPath is the default path for cursor state persistence.

View Source
const DefaultMaxTitleLen = 200

DefaultMaxTitleLen is the default safety cap for build-failure filenames. Override via MAX_TITLE_LEN.

View Source
const GitHubAPIClassUnclassified = "unclassified"

GitHubAPIClassUnclassified is the only rate-limit class emitted until a classification rule separating primary exhaustion from secondary rate limiting exists. The label is always present; no other value is guessed.

Variables

View Source
var DependabotGraphUpdatePrefixes = []string{
	"Graph Update:",
	"Dependabot Updates",
}

DependabotGraphUpdatePrefixes are workflow-name prefixes used by Dependabot for internal graph-maintenance jobs. These are NOT real CI failures — their HTTP 503s are Dependabot's own service being temporarily flaky. The real CI workflows on the same commits succeed. These runs must not trigger OpenClaw build-failure tasks.

View Source
var ErrRateLimited = stderrors.New("github rate limited")

ErrRateLimited is returned when the GitHub API responds with a rate-limit or abuse-rate-limit error.

Functions

func DeriveTaskID

func DeriveTaskID(owner, repo, episodeSHA string) uuid.UUID

DeriveTaskID returns a deterministic task identifier for a build-failure episode. Input: "<owner>/<repo>#build-<episodeSHA>", e.g. "bborbe/maintainer#build-abc123".

func DeriveTaskIDForce

func DeriveTaskIDForce(owner, repo, episodeSHA, nonce string) uuid.UUID

DeriveTaskIDForce returns a salted task identifier for an operator-forced re-publish of a build-failure episode (spec 069). The salt is a caller-supplied nonce — typically a microsecond timestamp from libtime.CurrentDateTimeGetter — so successive forced re-publishes for the same (owner, repo, episodeSHA) produce distinct identifiers and the agent controller's deterministic-ID dedup-skip does NOT fire. Pure function; nonce uniqueness is the caller's responsibility.

Key format: "<owner>/<repo>#build-<episodeSHA>!<nonce>". The "!" separator is invalid in GitHub owners/repos and in hex SHAs, so the salted keyspace cannot collide with the canonical DeriveTaskID keyspace for any (owner, repo, sha) tuple.

func GitHubAPIBucket added in v0.6.0

func GitHubAPIBucket(req *http.Request) string

GitHubAPIBucket derives the rate-limit bucket from the request path. It never reads a response: the response's X-RateLimit headers describe whichever bucket answered, which is how a search response once masqueraded as core.

func IsGitHubAPIRequest added in v0.6.0

func IsGitHubAPIRequest(req *http.Request) bool

IsGitHubAPIRequest reports whether req targets the GitHub API and so spends quota. Redirect hops to other hosts (e.g. job logs served from Azure blob storage) share the transport but spend no GitHub quota and are not counted.

func IsGitHubRateLimited added in v0.6.0

func IsGitHubRateLimited(resp *http.Response) bool

IsGitHubRateLimited reports whether resp is a rate-limit rejection: a 429, or a 403 carrying an exhausted X-RateLimit-Remaining or a Retry-After.

func NewMemDB

func NewMemDB() libkv.DB

NewMemDB returns a session-scoped, in-process libkv.DB implementation. It exists because libkv itself does not ship a public NewMemDB constructor (the upstream bborbe/kv package exposes only NewDBWithMetrics). The github-release watcher's command consumer needs an offset store; this in-memory implementation gives it one without requiring a PVC.

The implementation is intentionally minimal — it implements only the methods the offset-store / consumer wiring touches: Update, View, Sync, Close, Remove, Stats, StatsDetailed. Iterator / ListBucketNames return empty results because no caller in this package uses them.

func NewResetCursorHandler

func NewResetCursorHandler(cursorPath string) http.Handler

NewResetCursorHandler returns an HTTP handler that clears the cursor entry for one repo. Repo is taken from the {repo} URL variable (e.g. "github.com/bborbe/maintainer"). Releases an episode lock so the next poll detects the build state from scratch and may publish a fresh create-task.

Wrap with libhttp.NewDangerousHandlerWrapper at the call site to require a passphrase — the bare handler does not enforce auth.

Race: a concurrent Poll may overwrite the reset; operator should retry if the next poll log doesn't show a state transition for the target repo.

func SaveCursor

func SaveCursor(ctx context.Context, path string, c *Cursor) error

SaveCursor persists cursor state to path atomically via a temp file + rename. On error: logs warning and returns error; caller logs and continues.

Types

type AllowlistSnapshot

type AllowlistSnapshot interface {
	Snapshot() []string
}

AllowlistSnapshot returns the current set of concrete "host/owner/repo" entries the poll loop should iterate. Implementations MUST be safe to call from a goroutine concurrent with a refresh writer.

type Cursor

type Cursor struct {
	Repos map[string]*RepoState `json:"repos"` // key: "owner/repo"
}

Cursor is the full persisted state for the build watcher.

func LoadCursor

func LoadCursor(ctx context.Context, path string) (*Cursor, error)

LoadCursor reads cursor state from path. Missing file returns a fresh empty cursor (cold start is valid). Corrupt file returns an error; caller should refuse to proceed.

type Debouncer added in v0.4.0

type Debouncer interface {
	// Allow reports whether a trigger for key is permitted now. Returns false
	// (deny) when a previous trigger for the same key happened less than the
	// configured interval ago; records the trigger time on approval. The
	// caller records the deny reason for traceability (the webhook handler
	// increments webhook_skipped_total{reason="debounced"}).
	Allow(key string) bool
}

Debouncer collapses repeated triggers for the same key within a minimum interval, so a burst of events (e.g. a CI-heavy repo with many workflow runs finishing around the same time) produces at most one accepted trigger per interval.

func NewDebouncer added in v0.4.0

func NewDebouncer(interval time.Duration, clock libtime.CurrentDateTimeGetter) Debouncer

NewDebouncer returns a Debouncer that allows a trigger for key at most once per interval. The clock is injected so tests can fix the current time (libtime go-time rule: never time.Now() in business logic).

type GitHubAPILabels added in v0.6.0

type GitHubAPILabels struct {
	Service    string
	Credential string
	Cluster    string
}

GitHubAPILabels are the per-process label values stamped on every GitHub API counter. Credential carries the App id, never a token.

type GitHubAPIRecorder added in v0.6.0

type GitHubAPIRecorder interface {
	// Record counts the round trip of req. resp is nil and err non-nil on a
	// transport error.
	Record(req *http.Request, resp *http.Response, err error)
}

GitHubAPIRecorder counts one GitHub API round trip.

func NewGitHubAPIRecorder added in v0.6.0

func NewGitHubAPIRecorder(labels GitHubAPILabels) GitHubAPIRecorder

NewGitHubAPIRecorder returns a recorder that stamps labels on every count. Every bounded label combination is pre-initialised to zero so rate() and absent() queries see the series before the first call of that kind.

type GitHubClient

type GitHubClient interface {
	// GetWorkflowRuns returns completed workflow runs for a repo branch.
	// In-progress runs (empty Conclusion) are filtered out.
	GetWorkflowRuns(ctx context.Context, owner, repo, branch string) ([]WorkflowRun, error)

	// GetDefaultBranch returns the default branch name for a repository.
	GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)

	// GetDefaultBranchHeadSHA returns the 40-char hex SHA of the branch tip.
	// Used as recovery_sha on a red→green transition (default-branch HEAD at close time).
	GetDefaultBranchHeadSHA(ctx context.Context, owner, repo, branch string) (string, error)

	// GetFileContent fetches the raw content of a file at the given ref.
	// Returns (nil, nil) if the file does not exist (HTTP 404 — the common case).
	// Returns (nil, ErrRateLimited) when rate-limited.
	// Returns (nil, err) for any other API error.
	GetFileContent(ctx context.Context, owner, repo, path, ref string) ([]byte, error)

	// GetJobsForRun returns info about failed jobs in a run.
	// Returns an empty slice (not an error) when the run has no failed jobs.
	// Returns (nil, ErrRateLimited) when rate-limited.
	// Returns (nil, err) for other API errors.
	GetJobsForRun(ctx context.Context, owner, repo string, runID int64) ([]WorkflowJobInfo, error)

	// GetJobLog fetches the plain-text log for a workflow job by following GitHub's
	// redirect to an Azure storage URL. Returns (nil, nil) when the URL is unavailable.
	// Returns (nil, err) for a non-nil error where the log should be omitted.
	// Rejects payloads > 1 MiB before truncation (returns (nil, err)).
	GetJobLog(ctx context.Context, owner, repo string, jobID int64) ([]byte, error)

	// ListOwnerRepos returns the names of every non-archived, non-fork
	// repository owned by `owner`. Owner kind (User vs Organization) is
	// detected via GET /users/<owner>; the method then calls ListByUser
	// or ListByOrg respectively, paginating with PerPage=100 until done.
	// Returns (nil, ErrRateLimited) when rate-limited.
	// Returns (nil, err) for any other API error (network, 401/403, 404).
	// Returns ([]string{}, nil) when the owner has zero eligible repos.
	ListOwnerRepos(ctx context.Context, owner string) ([]string, error)

	// RateLimitRemaining returns the requests remaining in the current primary
	// rate-limit window, as reported by the last core-bucket API response's
	// X-RateLimit-Remaining header. Zero until the first request populates it.
	// The build watcher shares the GitHub App installation token with the
	// pr/release watchers, so this reading reflects the shared 12,500/hour
	// budget — the metric built from this closes the monitoring blind spot for
	// this consumer.
	RateLimitRemaining() int
}

GitHubClient abstracts the GitHub Actions API calls.

func NewGitHubClient

func NewGitHubClient(
	httpClient *http.Client,
	recorder GitHubAPIRecorder,
	apiBaseURL string,
) GitHubClient

NewGitHubClient returns a GitHubClient backed by the real GitHub API. The httpClient must already carry authentication (App auth). The client's transport is wrapped to observe the core-bucket X-RateLimit-Remaining on every response, so RateLimitRemaining() reflects the shared App token's live quota. Every round trip is also counted by recorder (per-caller github_api_calls_total / github_api_rate_limited_total).

type Metrics

type Metrics interface {
	// IncPollCycle increments the poll cycle counter.
	// result: "success" | "error"
	IncPollCycle(result string)
	// IncReposChecked increments the repos-checked counter for each repo polled.
	IncReposChecked()
	// IncStateTransition increments the state-transition counter.
	// transition: "green_to_red" | "red_to_green"
	IncStateTransition(transition string)
	// IncTaskPublished increments the published-task counter.
	IncTaskPublished()
	// IncTaskClosed increments the published-closure counter.
	IncTaskClosed()
	// IncPollError increments the poll-error counter.
	// reason: "rate_limited" | "github_error" | "kafka_error"
	IncPollError(reason string)
	// SetCurrentRedRepos sets the gauge to the current number of repos in red state.
	SetCurrentRedRepos(count float64)
	// SetRateLimitRemaining records the primary rate-limit window's remaining
	// for the shared GitHub App installation token, as read from the last
	// core-bucket API response's X-RateLimit-Remaining header.
	SetRateLimitRemaining(remaining int)
	// IncWebhookDelivery increments the webhook delivery counter with the given result label.
	// result: "success", "skip"
	IncWebhookDelivery(result string)
	// IncWebhookSignatureRejected increments the webhook signature-rejection counter.
	IncWebhookSignatureRejected()
	// ObserveWebhookDispatchLatency records the dispatch latency of a webhook delivery.
	ObserveWebhookDispatchLatency(seconds float64)
	// IncWebhookSkipped increments the webhook skip counter.
	// reason: "not_completed" | "not_failure" | "not_default_branch" | "debounced"
	IncWebhookSkipped(reason string)
}

Metrics defines Prometheus counters and gauges for the build watcher.

func NewMetrics

func NewMetrics() Metrics

NewMetrics returns a Metrics implementation backed by Prometheus counters.

type RepoState

type RepoState struct {
	LastKnownState    string `json:"last_known_state"`    // "green" | "red" | ""
	CurrentEpisodeSHA string `json:"current_episode_sha"` // empty when green
	DefaultBranch     string `json:"default_branch"`      // cached; fetched via API if empty
}

RepoState holds the persisted build state for one repository.

func GetOrCreateRepoState

func GetOrCreateRepoState(c *Cursor, key string) *RepoState

GetOrCreateRepoState returns the existing state for key or inserts a new zero-value RepoState. A zero-value LastKnownState ("") is treated as green by the state machine.

type StaticSnapshot

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

StaticSnapshot is an AllowlistSnapshot backed by an immutable slice. Used by the pure-literal binary path so no wildcard machinery runs.

func NewStaticSnapshot

func NewStaticSnapshot(entries []string) *StaticSnapshot

NewStaticSnapshot returns a snapshot holding a defensive copy of entries.

func (*StaticSnapshot) Snapshot

func (s *StaticSnapshot) Snapshot() []string

Snapshot returns the held entry slice. Callers MUST NOT mutate it.

type Watcher

type Watcher interface {
	Poll(ctx context.Context, force bool, scope string) error
}

Watcher polls GitHub Actions for build status changes.

When force is true, the red×red episode-lock arm of the state machine publishes a salted CreateTaskCommand instead of skipping (spec 069), so operators can force a re-publish for a still-red build via the /trigger HTTP path. The poll-interval loop always passes false.

When scope is non-empty ("owner/repo"), only that single repo is scanned — the webhook path — so one workflow_run delivery costs ~3 API calls, not a full fleet scan. Empty scope runs the full allowlist.

func NewWatcher

func NewWatcher(
	githubClient GitHubClient,
	createSender task.CreateCommandSender,
	completeSender task.CompleteCommandSender,
	metrics Metrics,
	repoFilter filter.RepoFilter,
	allowlist AllowlistSnapshot,
	cursorPath string,
	assignee string,
	taskStatus string,
	taskPhase string,
	stage string,
	maintenanceLoader maintenance.Loader,
	maxTitleLen int,
	taskSuffix string,
	currentDateTime libtime.CurrentDateTimeGetter,
) Watcher

NewWatcher returns a Watcher that polls GitHub Actions and publishes commands.

type WorkflowJobInfo

type WorkflowJobInfo struct {
	JobID          int64
	JobName        string
	FailedStepName string // first failed step's name; empty when not determinable
}

WorkflowJobInfo holds the failed job and step names for one failing workflow run. If no failed job is found in the response, JobName and FailedStepName are empty strings.

type WorkflowRun

type WorkflowRun struct {
	WorkflowID   int64
	RunID        int64 // run instance ID — used by jobs API (GET /actions/runs/{id}/jobs)
	Name         string
	HeadSHA      string
	Conclusion   string
	HTMLURL      string
	CreatedAt    time.Time
	DisplayTitle string    // display_title: commit message shown in GitHub UI
	HeadBranch   string    // head_branch: branch that triggered the run
	Event        string    // event: push / pull_request / schedule / workflow_dispatch / etc.
	StartedAt    time.Time // run_started_at: when execution began (not queuing time)
	UpdatedAt    time.Time // updated_at: last status change — completion time for done runs
}

WorkflowRun holds the fields the watcher needs from a GitHub Actions workflow run.

Directories

Path Synopsis
Package auth resolves a GitHub App HTTP client for the watcher binaries.
Package auth resolves a GitHub App HTTP client for the watcher binaries.
Package command defines the TriggerBuildCheckCommand payload and its Kafka sender for the github-build watcher's request topic.
Package command defines the TriggerBuildCheckCommand payload and its Kafka sender for the github-build watcher's request topic.
Package factory wires concrete dependencies for the maintainer-watcher-github-build binary.
Package factory wires concrete dependencies for the maintainer-watcher-github-build binary.
Package handler contains the HTTP handlers for the github-build watcher.
Package handler contains the HTTP handlers for the github-build watcher.
Package maintenance loads per-repo config from .maintenance.yaml on GitHub.
Package maintenance loads per-repo config from .maintenance.yaml on GitHub.
Package wildcard expands owner-level wildcard allowlist entries (e.g.
Package wildcard expands owner-level wildcard allowlist entries (e.g.

Jump to

Keyboard shortcuts

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