officership

package
v0.115.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 18 Imported by: 0 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 officership is what lets an officer SHIP: push branches, merge its own pull requests and tag releases in one repository, with every write decided in muster-server (docs/officers.md "Shipping officers").

  • pushgate.go: the connector-proxy write filter (a connectors.Gate) an instance's every GitHub request passes through;
  • gates.go: officer_merge_pr's and officer_tag_release's gates, all read fresh from GitHub and HQ at call time;
  • lint.go: the destructive-DDL lint on migration files;
  • rollout.go: the post-release watch and the automatic rollback.

🔴 THE REPOSITORY ENFORCES NOTHING, SO THIS PACKAGE IS THE BRANCH PROTECTION. A private repository on a plan without branch protection or rulesets lets any `contents: write` token push to its base branch, push any tag and merge with red checks. The officer's write token therefore never leaves muster: the instance's requests reach GitHub only through the push gate, and merges and tags are made here, after the gates, with muster's own token.

Index

Constants

View Source
const (
	GateStage      = "stage"
	GateHQEnabled  = "hq_enabled"
	GatePR         = "pull_request"
	GateBase       = "base"
	GateHeadBranch = "head_branch"
	GateAuthor     = "author"
	GateMergeable  = "mergeable"
	GateUpToDate   = "up_to_date"
	GateChecks     = "checks"
	GateReview     = "review"
	GateHold       = "hold"
	GateMigrations = "migrations"
	GateNotice     = "notice"
	GateMerge      = "merge"
	GateTags       = "tags"
	GateAncestor   = "ancestor"
	GateInFlight   = "in_flight"
	GateRate       = "rate"
	GateQuietHours = "quiet_hours"
	GateMainCI     = "main_ci"
	GateBackup     = "backup"
	GateTagCreate  = "tag_create"
	// GateUntestedMerge refuses a release while the base's head is an
	// officer merge that raced the base (MergeOutcome.UntestedTree).
	GateUntestedMerge = "untested_merge"
)

Gate names, as a refusal and the call log name them.

View Source
const (
	VerdictWatching   = "watching"
	VerdictHealthy    = "healthy"
	VerdictNotLive    = "not_live"
	VerdictUnhealthy  = "unhealthy"
	VerdictSuperseded = "superseded"
	VerdictAborted    = "aborted"
)

Watch verdicts.

Variables

View Source
var ErrMergeConflict = errors.New("officership: merge conflict")

ErrMergeConflict is a merge GitHub could not make cleanly (409).

View Source
var ErrRefExists = errors.New("officership: the ref already exists")

ErrRefExists is a create of a ref that already exists (GitHub's 422): the compare-and-swap against a concurrent tag or branch.

Functions

func BotLogin

func BotLogin(slug string) string

BotLogin is a GitHub App's bot account login.

func IsRollbackTag

func IsRollbackTag(message string) bool

IsRollbackTag reports whether an annotated tag's message carries the rollback trailer (a whole line, exactly).

func SensitiveFiles

func SensitiveFiles(patterns []string, files []File) []string

SensitiveFiles are the changed paths (a rename's old path included) that match any pattern, sorted and unique.

Types

type CheckRun

type CheckRun struct {
	ID         int64
	Name       string
	Status     string
	Conclusion string
	AppSlug    string
}

CheckRun is one check run on a commit.

type Comment

type Comment struct {
	Author     string
	AuthorType string // User | Bot | Organization
	Body       string
}

Comment is any human-or-bot text on a pull request: a conversation comment, a review body or a review comment.

type Compare

type Compare struct {
	Status   string // ahead | behind | diverged | identical
	AheadBy  int
	BehindBy int
	Files    []File
	Commits  []string // shas, oldest first
}

Compare is GET compare/{base}...{head}.

type File

type File struct {
	Path     string
	Previous string // a rename's old path
	Status   string // added | modified | removed | renamed | copied | changed | unchanged
}

File is one changed file of a pull request or a comparison.

type Finding

type Finding struct {
	File string
	Rule string
	Text string // the normalised statement, bounded
}

Finding is one destructive statement in a migration file.

func LintMigration

func LintMigration(file, sql string) []Finding

LintMigration returns every destructive statement in one migration file. An empty result is a pass.

type Gates

type Gates struct {
	OfficerID string
	Repo      string
	Ship      *officers.Ship
	GH        GitHub
	HQ        HQ
	Now       func() time.Time
	// InFlight reports a release the rollout watch still owns (its tag).
	InFlight func() (string, bool)
	// LiveVersion reads the version the service reports now (the rollout's
	// health URL).
	LiveVersion func(ctx context.Context) (string, error)
	// contains filtered or unexported fields
}

Gates are officer_merge_pr's and officer_tag_release's checks for one officer. Every input is read from GitHub and HQ at call time; nothing is cached between calls.

func (*Gates) MergePR

func (g *Gates) MergePR(ctx context.Context, n int) (MergeOutcome, error)

MergePR squash-merges the officer's own pull request n if, and only if, every merge gate passes now. A refusal is a *Refusal naming the gate; on a refusal nothing was written (a sensitive-path notice may have been posted only when every OTHER gate had passed).

The gates, in order:

  1. stage — the officer's stage allows merging;
  2. hq_enabled — HQ answers and says the officer is enabled (fail closed);
  3. base / head_branch / author — open, not draft, into the base branch, from <prefix>… in the same repository, authored by the officer App's bot;
  4. mergeable — GitHub says mergeable (unknown is "call again");
  5. up_to_date — the head contains the base's head (behind_by 0);
  6. checks — every required check is success on the head commit (a commit status, or a completed check run);
  7. review — the newest review check run on the head is completed+success (neutral fails; from review_app when set);
  8. hold — no human wrote /hold on the pull request;
  9. migrations — no destructive DDL in an added or changed migration, and no migration removed or renamed;
  10. notice — if a sensitive path changed, HQ accepted the notice;
  11. merge — GitHub squash-merges with the head pinned to the checked sha.

func (*Gates) TagRelease

func (g *Gates) TagRelease(ctx context.Context, opt TagOptions) (TagOutcome, error)

TagRelease creates the next minor release tag (annotated) on the base branch's head if, and only if, every release gate passes now:

  1. stage — the officer's stage allows releasing;
  2. hq_enabled — HQ says the officer is enabled (fail closed);
  3. tags / ancestor — the highest vX.Y.Z tag T is an ancestor of the base's head H, and H is ahead of it (else nothing to release);
  4. in_flight — no release the rollout watch still owns, and the service reports T's version (the previous release is live);
  5. rate — fewer than releases_per_day officer tags in the last 24 h, and none in the last min_release_gap;
  6. quiet_hours — not inside them;
  7. main_ci — the required checks are success for H's exact tree;
  8. migrations / backup — no destructive DDL in a migration added in T..H, and, when one was added, HQ's backup preflight passes;
  9. tag_create — GitHub creates refs/tags/<next>; a tag pushed by someone else first makes this fail, and the tool reports it.

type GitHub

type GitHub interface {
	AppSlug(ctx context.Context) (string, error)
	PR(ctx context.Context, n int) (PR, error)
	PRFiles(ctx context.Context, n int) ([]File, error)
	Compare(ctx context.Context, base, head string) (Compare, error)
	// Statuses is the latest commit status per context on sha.
	Statuses(ctx context.Context, sha string) (map[string]string, error)
	CheckRuns(ctx context.Context, sha, name string) ([]CheckRun, error)
	PRComments(ctx context.Context, n int) ([]Comment, error)
	FileAt(ctx context.Context, path, ref string) ([]byte, error)
	BranchSHA(ctx context.Context, branch string) (string, error)
	Tags(ctx context.Context) ([]TagRef, error)
	TagObject(ctx context.Context, sha string) (TagObject, error)
	// Commit is a commit's tree and parents.
	Commit(ctx context.Context, sha string) (tree string, parents []string, err error)
	PRsForCommit(ctx context.Context, sha string) ([]PR, error)
	Merge(ctx context.Context, n int, sha string) (string, error)
	CreateTag(ctx context.Context, name, message, sha string, t Tagger) (string, error)
	CreateRef(ctx context.Context, ref, sha string) error
	CreateCommit(ctx context.Context, message, tree string, parents []string) (string, error)
	MergeInto(ctx context.Context, base, head, message string) (string, error)
	OpenPR(ctx context.Context, title, head, base, body string) (int, error)
}

GitHub is every GitHub read and write the gates and the watcher make, for ONE repository. The REST implementation is REST; the tests use a fake.

type HQ

type HQ interface {
	// Enabled is HQ's on/off switch for the officer (GET /officers/{id}).
	Enabled(ctx context.Context) (bool, error)
	// PostNotice posts the sensitive-path notice (POST to path under hq_url).
	PostNotice(ctx context.Context, path string, n officers.Notice) error
	// Preflight is HQ's database backup health (POST /officers/{id}/preflight).
	Preflight(ctx context.Context) (officers.Preflight, error)
}

HQ is what the gates ask HQ, with the officer's own token.

type MergeOutcome

type MergeOutcome struct {
	PR       int      `json:"pr"`
	HeadSHA  string   `json:"head_sha"`
	MergeSHA string   `json:"merge_sha"`
	Passed   []string `json:"gates_passed"`
	Noticed  []string `json:"sensitive_paths_noticed,omitempty"`
	// UntestedTree: the merge landed on a base that moved after the gates
	// read it, so the base now holds a tree no CI run saw (Warning says so).
	UntestedTree bool   `json:"untested_tree,omitempty"`
	Warning      string `json:"warning,omitempty"`
}

MergeOutcome is what officer_merge_pr did.

type PR

type PR struct {
	Number         int
	State          string
	Draft          bool
	Merged         bool
	Mergeable      *bool
	Author         string
	AuthorType     string
	HeadRef        string
	HeadSHA        string
	HeadRepo       string
	BaseRef        string
	BaseRepo       string
	Title          string
	MergeCommitSHA string
}

PR is the part of a pull request the gates read.

type PushGate

type PushGate struct {
	// Repo is the officer's repository (owner/name).
	Repo string
	// Ship is the officer's policy (Base, BranchPrefix).
	Ship *officers.Ship
	// GitHost and APIHost are the hosts served (github.com, api.github.com).
	GitHost, APIHost string
	// Cred mints the credential for an admitted request (the officer App's
	// connectors.Virtual Credential: its token for Repo, anonymous elsewhere).
	Cred func(ctx context.Context, caller connectors.Caller, host, rest string) (string, bool, error)
	// OnRejected drops a cached credential after a 401.
	OnRejected func(caller connectors.Caller)
	// GH reads a pull request (PATCH's own-PR check) and the App's slug.
	GH GitHub
}

PushGate is a shipping officer's connectors.Gate: the write filter every one of its instance's GitHub requests passes through in muster's connector proxy, and the source of the (write-capable) credential an admitted request carries.

🔴 IT IS AN ALLOWLIST. A read (GET, HEAD) is forwarded. A write is forwarded only when it is one of these, in the officer's own repository:

  • git push (POST …/git-receive-pack) whose EVERY ref update targets refs/heads/<prefix>… — so never the base branch, never a tag;
  • git fetch (POST …/git-upload-pack), which writes nothing;
  • POST /repos/{repo}/pulls with head <prefix>… and base = the base branch;
  • PATCH /repos/{repo}/pulls/{n} of the officer's OWN pull request (its App's bot authored it, its head is <prefix>…), title/body/state only;
  • POST /repos/{repo}/issues/{n}/comments on its OWN pull request.

Every other method, path and host shape is refused — the merge endpoint, the git/refs and git/tags endpoints, releases, the contents API (which commits to any branch), the merges API, GraphQL (which can do all of those), and every DELETE. Merges and tags are made by officer_merge_pr and officer_tag_release in muster-server, after their gates.

func (*PushGate) Admit

func (g *PushGate) Admit(r *http.Request, host, rest string) (*http.Request, error)

Admit implements connectors.Gate.

func (*PushGate) Connector

func (g *PushGate) Connector() string

Connector implements connectors.Gate.

func (*PushGate) Credential

func (g *PushGate) Credential(ctx context.Context, caller connectors.Caller, host, rest string) (string, bool, error)

Credential implements connectors.Gate.

func (*PushGate) Describe

func (g *PushGate) Describe() connectors.Connector

Describe implements connectors.Gate: the GitHub preset's shape.

func (*PushGate) Rejected

func (g *PushGate) Rejected(caller connectors.Caller)

Rejected implements connectors.Gate.

type REST

type REST struct {
	Base  string // API base, no trailing slash
	Repo  string // owner/name
	Token func(ctx context.Context) (string, error)
	// Slug reads the App's slug (GET /app, as the App).
	Slug func(ctx context.Context) (string, error)
	HTTP *http.Client
}

REST is GitHub over GitHub's REST API for Repo, authenticated by Token (the officer App's installation token, minted per call by muster).

func (*REST) AppSlug

func (g *REST) AppSlug(ctx context.Context) (string, error)

AppSlug implements GitHub.

func (*REST) BranchSHA

func (g *REST) BranchSHA(ctx context.Context, branch string) (string, error)

BranchSHA implements GitHub.

func (*REST) CheckRuns

func (g *REST) CheckRuns(ctx context.Context, sha, name string) ([]CheckRun, error)

CheckRuns implements GitHub.

func (*REST) Commit

func (g *REST) Commit(ctx context.Context, sha string) (string, []string, error)

Commit implements GitHub.

func (*REST) Compare

func (g *REST) Compare(ctx context.Context, base, head string) (Compare, error)

Compare implements GitHub. 🔴 GitHub lists at most 300 files and 250 commits in one comparison; a comparison at either cap is refused rather than read as complete.

func (*REST) CreateCommit

func (g *REST) CreateCommit(ctx context.Context, message, tree string, parents []string) (string, error)

CreateCommit implements GitHub.

func (*REST) CreateRef

func (g *REST) CreateRef(ctx context.Context, ref, sha string) error

CreateRef implements GitHub. An existing ref is ErrRefExists.

func (*REST) CreateTag

func (g *REST) CreateTag(ctx context.Context, name, message, sha string, t Tagger) (string, error)

CreateTag implements GitHub: an annotated tag OBJECT (no ref yet).

func (*REST) FileAt

func (g *REST) FileAt(ctx context.Context, path, ref string) ([]byte, error)

FileAt implements GitHub (the raw bytes of path at ref).

func (*REST) Merge

func (g *REST) Merge(ctx context.Context, n int, sha string) (string, error)

Merge implements GitHub: a squash merge that GitHub refuses (409) unless the head is still sha — the match-head-commit guard.

func (*REST) MergeInto

func (g *REST) MergeInto(ctx context.Context, base, head, message string) (string, error)

MergeInto implements GitHub (POST merges: head merged into branch base). A conflict is ErrMergeConflict.

func (*REST) OpenPR

func (g *REST) OpenPR(ctx context.Context, title, head, base, body string) (int, error)

OpenPR implements GitHub.

func (*REST) PR

func (g *REST) PR(ctx context.Context, n int) (PR, error)

PR implements GitHub.

func (*REST) PRComments

func (g *REST) PRComments(ctx context.Context, n int) ([]Comment, error)

PRComments implements GitHub: conversation comments, review bodies and review comments, every page.

func (*REST) PRFiles

func (g *REST) PRFiles(ctx context.Context, n int) ([]File, error)

PRFiles implements GitHub.

func (*REST) PRsForCommit

func (g *REST) PRsForCommit(ctx context.Context, sha string) ([]PR, error)

PRsForCommit implements GitHub.

func (*REST) Statuses

func (g *REST) Statuses(ctx context.Context, sha string) (map[string]string, error)

Statuses implements GitHub (the combined status: the latest per context).

func (*REST) TagObject

func (g *REST) TagObject(ctx context.Context, sha string) (TagObject, error)

TagObject implements GitHub.

func (*REST) Tags

func (g *REST) Tags(ctx context.Context) ([]TagRef, error)

Tags implements GitHub: every refs/tags/v* ref.

type Refusal

type Refusal struct {
	Gate   string
	Reason string
}

Refusal is a gate that did not pass. Nothing was written.

func AsRefusal

func AsRefusal(err error) (*Refusal, bool)

AsRefusal reports whether err is a gate refusal.

func (*Refusal) Error

func (r *Refusal) Error() string

type TagObject

type TagObject struct {
	SHA        string
	Tagger     string
	TaggedAt   time.Time
	TargetSHA  string
	TargetType string
	Message    string
}

TagObject is an annotated tag.

type TagOptions

type TagOptions struct {
	// Rollback is the rollout watch's own release of a revert: it skips the
	// in-flight, rate, quiet-hours and HQ-enabled gates (the release being
	// rolled back is the one in flight, and HQ may be what is down) and keeps
	// every other.
	Rollback bool
}

TagOptions are officer_tag_release's inputs.

type TagOutcome

type TagOutcome struct {
	Tag         string    `json:"tag"`
	SHA         string    `json:"sha"`
	Previous    string    `json:"previous"`
	PreviousSHA string    `json:"previous_sha"`
	TaggedAt    time.Time `json:"tagged_at"`
	Passed      []string  `json:"gates_passed"`
	Migrations  []string  `json:"migrations,omitempty"`
}

TagOutcome is what officer_tag_release did.

type TagRef

type TagRef struct {
	Name       string
	ObjectSHA  string
	ObjectType string // commit (lightweight) | tag (annotated)
}

TagRef is one refs/tags/* ref: its name and the object it points at.

type Tagger

type Tagger struct {
	Name, Email string
	When        time.Time
}

Tagger is who an annotated tag is made by.

type Version

type Version struct{ Major, Minor, Patch int }

Version is a vMAJOR.MINOR.PATCH tag.

func ParseVersion

func ParseVersion(tag string) (Version, bool)

ParseVersion reads a release tag; ok is false for anything else.

func (Version) Less

func (v Version) Less(w Version) bool

Less orders versions.

func (Version) NextMinor

func (v Version) NextMinor() Version

NextMinor is the release after v: minor bumped, patch 0.

func (Version) String

func (v Version) String() string

type WatchStatus

type WatchStatus struct {
	Tag         string    `json:"tag"`
	SHA         string    `json:"sha"`
	Previous    string    `json:"previous"`
	ItemID      string    `json:"item_id,omitempty"`
	TaggedAt    time.Time `json:"tagged_at"`
	Phase       string    `json:"phase"`
	Verdict     string    `json:"verdict"`
	LiveAt      time.Time `json:"live_at,omitempty"`
	RevertPR    int       `json:"revert_pr,omitempty"`
	RollbackTag string    `json:"rollback_tag,omitempty"`
	Escalated   bool      `json:"escalated"`
	// Rollback is true for the watch of a ROLLBACK release: it is never itself
	// rolled back.
	Rollback bool     `json:"rollback"`
	Events   []string `json:"events"`
	Done     bool     `json:"done"`
}

WatchStatus is one release's watch, as officer_rollout_status reports it.

type Watcher

type Watcher struct {
	OfficerID string
	Repo      string
	Ship      *officers.Ship
	GH        GitHub
	Gates     *Gates
	HTTP      *http.Client
	Now       func() time.Time
	// Sleep waits d or until ctx ends (tests replace it).
	Sleep func(ctx context.Context, d time.Duration) error
	Logf  func(format string, args ...any)
	// contains filtered or unexported fields
}

Watcher watches one officer's releases, one at a time.

func (*Watcher) InFlight

func (w *Watcher) InFlight() (string, bool)

InFlight reports the tag of a release still being watched.

func (*Watcher) LiveVersion

func (w *Watcher) LiveVersion(ctx context.Context) (string, error)

LiveVersion is the version the service reports now (Gates.LiveVersion).

func (*Watcher) Resume

func (w *Watcher) Resume(ctx context.Context)

Resume restarts the watch of the newest release after a muster restart, when that release is the officer's own and still inside its watch window. A restart therefore costs at most the probes it missed, not the watch.

func (*Watcher) Start

func (w *Watcher) Start(ctx context.Context, rel TagOutcome, itemID string) error

Start begins watching a release in the background (ctx ends it). A watch already in flight is refused: officer_tag_release's in-flight gate makes that unreachable except by a rollback, which watches inline.

func (*Watcher) Status

func (w *Watcher) Status() (cur *WatchStatus, history []WatchStatus)

Status is the current (or last) watch and the earlier ones of this process.

func (*Watcher) Wait

func (w *Watcher) Wait()

Wait blocks until every watch goroutine has returned (shutdown, tests).

Jump to

Keyboard shortcuts

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