app

package
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 14 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 app holds badil's application services: the background job queue that runs reconciles, the latest reconcile outcome of each PR, the wake signal of the waits, the lifecycle APIs built over the gitops store and the forge, the handling of the pull_request and push events, the config syncs, the intake of the renderer status events, the manual deploys, the read model of the previews and the evaluation of the waits.

Index

Constants

View Source
const (
	KindService    = "service"
	KindDependency = "dependency"
)

Kinds of a preview's entries.

View Source
const CleanupTimeout = 10 * time.Minute

CleanupTimeout bounds one cleanup sweep over every preview.

View Source
const ReconcileTimeout = 20 * time.Second

ReconcileTimeout caps the background work for a single reconcile, shared by every service it deploys or by its teardown.

View Source
const StatusUnknown = "unknown"

StatusUnknown is the status of an entry no status was recorded for.

View Source
const SyncTimeout = 10 * time.Minute

SyncTimeout caps each config sync run (a push to the gitops default branch, or Sync), counted from when the run holds the syncer's guard.

Variables

View Source
var ErrNoPreview = errors.New("preview not found")

ErrNoPreview is a preview whose file is not in the gitops repo.

View Source
var ErrServiceNotInCatalog = errors.New("service not in catalog")

ErrServiceNotInCatalog is a deploy of a service badil.yaml does not declare.

View Source
var ErrServiceRepoNotOnForge = errors.New("service repo is not a repository of the forge")

ErrServiceRepoNotOnForge is a deploy of a service whose badil.yaml repo is not a repository URL of the forge.

Functions

func AppliedHook

func AppliedHook(st StatusRepository, w *Wake) func(lifecycle.Result)

AppliedHook returns the hook run when the gitops store lands a push: the status of the previews res deleted is deleted from st, then w wakes the waits.

func CatchUpAPI

CatchUpAPI is st, f, the recorder m and the expiry store e, as lifecycle.CatchUp expects them. A nil m records nothing; a nil e skips no expired PR.

func CleanupCatchUp

CleanupCatchUp is badil cleanup's catch-up over st and f, recording no metrics: it reconciles at once (reconcileNow), checking the namespace of a new preview with ns and remembering expiries in e as serve does.

func CountPreviews

func CountPreviews(ctx context.Context, l PreviewLister, rec PreviewsRecorder)

CountPreviews records with rec the number of previews of one listing of the gitops repo by l, bounded by previewsCountTimeout. serve calls it before the server accepts requests, so no create or delete races the listing. It lists nothing when rec is nil (metrics disabled). A failed or timed-out listing is logged and records nothing.

func HeadMovedHook

func HeadMovedHook(st StatusRepository, w *Wake) func()

HeadMovedHook returns the hook run when a fetch moves the gitops store's head: the status of the previews no longer there is collected from st, then w wakes the waits.

func RunCatchUp

func RunCatchUp(ctx context.Context, c CatchUpRunner)

RunCatchUp runs one catch-up of c, bounded by CleanupTimeout and cancelled with ctx.

func RunCleanup

func RunCleanup(
	ctx, sweepCtx context.Context, api lifecycle.SweepAPI, c CatchUpRunner, now time.Time, ttl time.Duration,
) error

RunCleanup runs one sweep under sweepCtx, then one catch-up of c under its own CleanupTimeout from ctx (RunCatchUp), whether the sweep succeeded or failed. It returns the sweep's error: catch-up's failures are only logged and counted.

func SweepAPI

SweepAPI is st, f and the fan-out lifecycle.FanOutPRComments with the recorder m and the expiry store e, as lifecycle.Sweep expects them. A nil m records nothing; a nil e remembers no expiry.

Types

type App

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

App is badil's application services: the background job queue that runs reconciles, the latest reconcile outcome of each PR, the wake signal of the waits, the lifecycle APIs, the read model of the previews and the evaluation of the waits, built by New.

func New

func New(cfg Config) *App

New returns the App cfg configures.

func (*App) CatchUp

func (a *App) CatchUp() *lifecycle.CatchUp

CatchUp is the catch-up of serve over the app's store, forge and metrics: it records the PRs it filters out as their latest outcome (RecordCatchUpSkip) and reconciles in the app's job queue (QueueReconcile).

func (*App) Deploy

func (a *App) Deploy(ctx context.Context, r DeployRequest) (DeployOutcome, error)

Deploy deploys r through lifecycle.DeployPR, stamped with the current time. A manual deploy always writes: it refreshes updated-at (the TTL clock) and always returns a gitops commit. Its head branch, author and URL are those of the pull request r.PRNumber of the service's repository, read from the forge; the preview's slug is the slugified head branch, set in DeployOutcome.Slug on every return after that read. It is refused with lifecycle.ErrPreviewLimit when the preview does not exist and preview.maxPreviews previews already do, or with lifecycle.ErrNamespaceInUse when the preview does not exist and its namespace is not a preview's; a failed namespace check is a *lifecycle.NamespaceCheckError. A catalog that can't be read is a *CatalogReadError, a service it does not declare ErrServiceNotInCatalog, a service whose repo is not a repository of the forge ErrServiceRepoNotOnForge and a pull request that cannot be read a *PullRequestReadError; each returns a zero DeployOutcome. It does not log.

func (*App) DeployAPI

func (a *App) DeployAPI() lifecycle.DeployAPI

DeployAPI is the store, the forge, the metrics, the fan-out, the namespace check and the expiry store as lifecycle.DeployPR expects them.

func (*App) EvaluatePRWait

func (a *App) EvaluatePRWait(ctx context.Context, q PRQuery) (*WaitResult, error)

EvaluatePRWait evaluates the wait of the PR of q, in this order: refused when the catalog has no service of its repo; the state its latest recorded outcome decides, when that outcome's head SHA matches q's SHA or q has none; pending when no preview has an entry pinned by the PR (at q's SHA, when set); otherwise the state of the PR's wait set in that preview.

func (*App) EvaluateSlugWait

func (a *App) EvaluateSlugWait(ctx context.Context, slug string) (*WaitResult, error)

EvaluateSlugWait evaluates the wait of the preview slug: ErrNoPreview when it does not exist, pending when it has no pinned entry, otherwise the state of its wait set.

func (*App) Go

func (a *App) Go(f func())

Go runs f in the background, tracked by WaitBackground. Unlike reconciles, f does not wait for other background jobs.

func (*App) HasStatus

func (a *App) HasStatus() bool

HasStatus reports whether the app has a status repository (Config.Status).

func (*App) LatestOutcome

func (a *App) LatestOutcome(t lifecycle.Target) (Outcome, bool)

LatestOutcome returns the latest reconcile outcome of the PR of t, and whether one is recorded.

func (*App) OnPullRequest

func (a *App) OnPullRequest(ctx context.Context, e forge.PullRequestEvent)

OnPullRequest reconciles the PR of a pull_request event whose action is opened, reopened, synchronize, labeled, unlabeled or closed, in a background job (startReconcile). Any other action starts nothing.

func (*App) OnPush

func (a *App) OnPush(ctx context.Context, e forge.PushEvent)

OnPush starts a config sync in the background for a push to the gitops repo's default branch that did not delete it, once the store is told to check the remote on its next read. Any other push is ignored.

func (*App) Preview

func (a *App) Preview(ctx context.Context, slug string) (*PreviewView, error)

Preview reads the preview slug from the gitops clone, with the catalog. It returns ErrNoPreview when the preview does not exist, or slug is not a slug.

func (*App) PreviewStatus

func (a *App) PreviewStatus(slug string) map[string]preview.ServiceStatus

PreviewStatus returns the status of the preview slug's entries, by name: empty when the app has no status repository.

func (*App) Previews

func (a *App) Previews(ctx context.Context) ([]PreviewView, error)

Previews returns every preview file of the gitops clone, sorted by slug, each with the catalog. A preview whose file is gone by the time it is read is left out.

func (*App) QueueReconcile

func (a *App) QueueReconcile(ctx context.Context, ev lifecycle.Event, done func(lifecycle.ReconcileResult))

QueueReconcile reconciles ev in a background job (RunJob), as a pull_request delivery does: after the jobs before it, alone, and capped at the job timeout. done gets ReconcilePR's result once it completes, or the failed outcome at ev's head SHA when it panics; that result is first recorded as the PR's latest outcome (RecordOutcome). It is a lifecycle.ReconcileFunc.

func (*App) ReconcileAPI

func (a *App) ReconcileAPI() lifecycle.ReconcileAPI

ReconcileAPI is the store, the forge, the metrics, the fan-out, the namespace check and the expiry store as lifecycle.ReconcilePR expects them.

func (*App) RecordCatchUpSkip

func (a *App) RecordCatchUpSkip(t lifecycle.Target, res lifecycle.ReconcileResult, listedAt time.Time)

RecordCatchUpSkip records res, the skip catch-up gives a PR it filters out, as the latest outcome of the PR of t, and wakes the waits, only when the PR's stored outcome was recorded before listedAt, the time catch-up started listing the PR's repo. A stale listing then never replaces an outcome a reconcile recorded after it.

func (*App) RecordOutcome

func (a *App) RecordOutcome(t lifecycle.Target, res lifecycle.ReconcileResult)

RecordOutcome records res as the latest reconcile outcome of the PR of t, replacing the one before, and wakes the waits. A skip for a label that is not a preview label (lifecycle.OtherLabelReason) is not recorded: the event did not concern the PR's preview.

func (*App) RecordStatus

func (a *App) RecordStatus(ctx context.Context, e StatusEvent) error

RecordStatus records the status a renderer reports for a preview service, and wakes the waits when it is recorded. The app must have a status repository (HasStatus). An event of an unknown preview or service, or one older than the recorded status, is ignored. Each event is counted and logged with its result. When the preview can't be read, nothing is recorded and the read error is returned.

func (*App) RunJob

func (a *App) RunJob(ctx context.Context, onPanic func(rec any), job func(context.Context))

RunJob runs job in the background, so the webhook is answered within GitHub's 10-second limit. The job is tracked for WaitBackground, runs once no other job holds a.jobs, gets a context detached from ctx's cancellation and capped at a.jobTimeout from when it holds a.jobs, and has its panics passed to onPanic.

func (*App) StartSweepLoop

func (a *App) StartSweepLoop(
	ctx context.Context,
	api lifecycle.SweepAPI,
	catchUp CatchUpRunner,
	rec SweepRecorder,
	interval, ttl time.Duration,
)

StartSweepLoop runs runSweepLoop in the background of a, so shutdown waits for it. It starts nothing when interval is 0.

func (*App) Sync

func (a *App) Sync(ctx context.Context, slug string) (lifecycle.SyncReport, error)

Sync syncs every preview, or the preview slug when it is not empty, with badil.yaml (lifecycle.Syncer.Sync), waiting for the config sync guard.

func (*App) SyncAPI

func (a *App) SyncAPI() lifecycle.SyncAPI

SyncAPI is the store, the forge, the metrics and the fan-out as lifecycle.Syncer expects them.

func (*App) WaitBackground

func (a *App) WaitBackground(ctx context.Context) error

WaitBackground blocks until every background job has finished. It returns nil once they are done, or ctx.Err() when ctx expires first.

func (*App) Wake

func (a *App) Wake() *Wake

Wake returns the wake signal of the waits.

type CatalogReadError

type CatalogReadError struct {
	Err error
}

CatalogReadError is a deploy whose catalog could not be read: Err is the read's error.

func (*CatalogReadError) Error

func (e *CatalogReadError) Error() string

func (*CatalogReadError) Unwrap

func (e *CatalogReadError) Unwrap() error

type CatchUpRunner

type CatchUpRunner interface {
	Run(ctx context.Context)
}

CatchUpRunner runs one catch-up: *lifecycle.CatchUp.

type CleanupStore

type CleanupStore interface {
	lifecycle.CatchUpStore
	lifecycle.ReconcileStore
}

CleanupStore is the gitops store badil cleanup's catch-up reads and writes: *store.GitHubStore.

type Config

type Config struct {
	// Store is the gitops repo.
	Store Store
	// Forge is the forge of the PRs.
	Forge forge.Forge
	// Metrics records the lifecycle outcomes. Nil records nothing.
	Metrics Metrics
	// FanOut posts a preview's summary on its open PRs. Nil is
	// lifecycle.FanOutPRComments.
	FanOut lifecycle.FanOutFunc
	// Namespaces checks the namespace of each new preview before it is
	// written (lifecycle.NamespaceChecker). Nil checks none.
	Namespaces lifecycle.NamespaceChecker
	// Wake is notified on every change a wait may be waiting for; the caller
	// also notifies it on the changes the app does not see itself: a landed
	// Apply (store.WithApplied) and a fetch that moved the gitops head
	// (store.WithHeadMoved). Nil has the app make its own.
	Wake *Wake
	// JobTimeout caps each background job, counted from when it holds the
	// job queue. 0 is ReconcileTimeout.
	JobTimeout time.Duration
	// Status holds the status the renderer reports. Nil means no status is
	// known.
	Status StatusRepository
	// Expiry remembers the PRs of the previews the sweep expired for the TTL
	// (lifecycle.ExpiryStore). Nil remembers none.
	Expiry lifecycle.ExpiryStore
}

Config configures an App built by New.

type DeployOutcome

type DeployOutcome struct {
	Slug        string
	MaxPreviews int
	Deployed    *lifecycle.DeployResult
	FanOutErr   error
}

DeployOutcome is what a deploy did: the slug of the preview it targets, the catalog's preview cap, the deploy's result and its fan-out error (possibly joined, nil when every comment landed).

type DeployRequest

type DeployRequest struct {
	Service        string
	CommitSha      string
	PRNumber       int
	WorkflowRunURL string
}

DeployRequest is a manual deploy of a service's commit into the preview of the head branch of its repository's pull request PRNumber.

type Entry

type Entry struct {
	Name, Kind, Branch, URL string
	Service                 *preview.ServiceEntry
}

Entry is a service or dependency entry of a preview file: its name, kind, branch (services only), the URL of its host (when it has one) and, for a service, its file entry.

func (Entry) Pinned

func (e Entry) Pinned() bool

Pinned reports whether e is a pinned service entry.

type Metrics

type Metrics interface {
	lifecycle.Recorder
	lifecycle.CatchUpRecorder
	// StatusEvent records one renderer status event and its result.
	StatusEvent(status, result string)
	// SpinUp records the time a service took to become ready.
	SpinUp(service string, d time.Duration)
}

Metrics records the outcomes of the lifecycle operations an App runs, the reconciles its catch-up starts, the renderer status events and the spin-up durations it observes. *metrics.Metrics implements it.

type Outcome

type Outcome struct {
	lifecycle.ReconcileResult

	At time.Time
}

Outcome is the latest reconcile outcome of a PR, its reason and head SHA, and when it was recorded. At keeps time.Now's monotonic reading, so it compares with a catch-up listing time on the monotonic clock.

type PRQuery

type PRQuery struct {
	Owner, Repo string
	Number      int
	SHA         string
}

PRQuery is the PR a wait is for, and the SHA waited for, "" when any.

type PreviewLister

type PreviewLister interface {
	ListPreviews(ctx context.Context) ([]string, error)
}

PreviewLister lists the previews of the gitops repo.

type PreviewView

type PreviewView struct {
	Slug    string
	Values  *preview.Values
	Catalog *catalog.Catalog
}

PreviewView is a preview file read from the gitops clone, with the catalog it is read with.

func (PreviewView) Entries

func (v PreviewView) Entries() []Entry

Entries returns the service entries then the dependency entries of v, in file order.

type PreviewsRecorder

type PreviewsRecorder interface {
	PreviewsListed(n int)
}

PreviewsRecorder records the number of previews listed: *metrics.Metrics.

type PullRequestReadError added in v0.31.0

type PullRequestReadError struct {
	Owner  string
	Repo   string
	Number int
	Err    error
}

PullRequestReadError is a deploy whose pull request Owner/Repo#Number could not be read: Err is the forge's error, forge.ErrNotFound when the pull request does not exist.

func (*PullRequestReadError) Error added in v0.31.0

func (e *PullRequestReadError) Error() string

func (*PullRequestReadError) Unwrap added in v0.31.0

func (e *PullRequestReadError) Unwrap() error

type StatusEvent

type StatusEvent struct {
	Preview, Service, Revision, Status string
	At                                 time.Time
}

StatusEvent is the status a renderer reports for one service of a preview, at a revision, and when.

type StatusRepository

type StatusRepository interface {
	// Preview returns the latest status of each service of the preview
	// slug, by name.
	Preview(slug string) map[string]preview.ServiceStatus
	// Record sets the status of service in the preview slug to e, unless e
	// is older than the stored one. It reports whether e was recorded and,
	// when it was, whether it is the first ready recorded for that service
	// at e's revision.
	Record(slug, service string, e preview.ServiceStatus) (bool, bool)
	// Delete forgets the status of the previews slugs.
	Delete(slugs ...string)
	// CollectGarbage asks for the status of the previews no longer in the
	// gitops repo to be forgotten, in the background.
	CollectGarbage()
}

StatusRepository holds the status the renderer reports for each service of each preview. *status.Store implements it.

type Store

type Store interface {
	lifecycle.ReconcileStore
	lifecycle.SyncStore
	// ListPreviewFiles lists the slugs of the previews whose values.yaml is
	// in the gitops repo, sorted.
	ListPreviewFiles(ctx context.Context) ([]string, error)
	// GetPreview reads previews/<slug>/values.yaml, lifecycle.ErrNotFound when
	// it does not exist.
	GetPreview(ctx context.Context, slug string) (*preview.Values, string, error)
	FullName() string
	// Invalidate makes the next read check the gitops remote at once.
	Invalidate()
}

Store is the gitops store the lifecycle APIs of an App are built over.

type SweepRecorder

type SweepRecorder interface {
	SweepRun(ok bool, at time.Time)
}

SweepRecorder records the runs of the sweep loop: *metrics.Metrics.

type WaitEntry

type WaitEntry struct {
	Name     string
	Kind     string
	Status   string
	Revision string
	Ready    bool
	URL      string
}

WaitEntry is an entry of a wait set: its latest status (StatusUnknown when none) and revision, whether it is ready, and its URL.

type WaitResult

type WaitResult struct {
	State    string
	Reason   string
	Slug     string
	SHA      string
	Services []WaitEntry
	URLs     map[string]string
}

WaitResult is the state of a wait: its state, the reason of a failed, refused or skipped state, the preview and the SHA waited for when known, and the wait set's entries with the URLs of those that have one.

func (*WaitResult) Final

func (r *WaitResult) Final() bool

Final reports whether a wait in r's state answers at once.

type Wake

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

Wake is a broadcast signal: each Notify wakes every goroutine blocked on the channel Wait returned before it. Its methods are safe for concurrent use, and Notify never blocks.

func NewWake

func NewWake() *Wake

NewWake returns a Wake no one waits on yet.

func (*Wake) Notify

func (w *Wake) Notify()

Notify wakes every waiter: it closes the current channel and replaces it.

func (*Wake) Wait

func (w *Wake) Wait() <-chan struct{}

Wait returns the channel the next Notify closes.

Jump to

Keyboard shortcuts

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