refreshloop

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 6 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.

README

refresh-loop-go

The fleet's one keep-X-fresh refresh-loop primitive — a typed FSM, built ON shigoto-go, that drives a set of resources back to a fresh state on a cadence so no tool hand-rolls its own "is-it-stale? → refresh → record → wait → repeat" timer loop again.

Worlds-separate. This is a PUBLIC, generic primitive: it never names or imports akeyless. A secret-rotation Refresher that talks to akeyless (or a pod-recycle Refresher that talks to a Kubernetes API) is a PRIVATE adapter the consumer supplies — refreshloop only knows the generic Refresher shape and the step-kind labels.

What

A typed Loop that owns a shigoto-go scheduler + DAG of keep-fresh items. Each item is a Spec (a stable Scope/Kind/Subject identity, a freshness Interval, a Refresher, and an optional retry policy + timeout). The loop re-arms any item that has gone stale and runs one shigoto Tick, so every refresh, retry, and deadletter flows through shigoto's audited FSM — with per-kind / global concurrency budgets for free.

Two fleet step kinds ship as named constants (the StepKind newtype is open, so a consumer can declare its own):

Step kind StepKind Concern
Secret rotation KindSecretRotation re-mint / re-issue / re-key a credential before it expires
Pod recycle KindPodRecycle recycle a workload so it picks up rotated config or sheds drift

Why

"Keep this fresh" is the shape behind credential rotation, token re-minting, and pod recycling — and every tool that does it re-implements the same loop with its own timer, its own retry-on-failure, its own concurrency cap, and its own audit trail. That is exactly the FSM + DAG + gate + budget + retry + emit algebra shigoto-go already owns. refreshloop is the thin typed layer that turns that algebra into the keep-fresh idiom: declare WHAT to keep fresh and HOW stale is "too stale", and never re-write the loop. The third consumer earns the primitive (PRIME DIRECTIVE); this is it.

Install

go get github.com/pleme-io/refresh-loop-go

Usage

loop, _ := refreshloop.New("akeyless-rotator")

// secret rotation — the Refresher is a PRIVATE adapter you supply.
_ = loop.Register(refreshloop.Spec{
    Kind:      refreshloop.KindSecretRotation,
    Subject:   "db-password",
    Interval:  12 * time.Hour,                // fresh ⇒ rotated within 12h
    Retry:     shigoto.Exponential(4, time.Second, time.Minute, 0.2),
    Refresher: refreshloop.RefresherFunc(func(ctx context.Context, subject string) error {
        return akl.RotateStatic(ctx, subject) // PRIVATE, vendor-coupled
    }),
})

// pod recycle — generic Kubernetes vocabulary.
_ = loop.Register(refreshloop.Spec{
    Kind:      refreshloop.KindPodRecycle,
    Scope:     "ns:payments",
    Subject:   "api",
    Interval:  6 * time.Hour,
    Refresher: refreshloop.RefresherFunc(func(ctx context.Context, name string) error {
        return k8s.RolloutRestart(ctx, "payments", name)
    }),
})

// Drive it. Either the convenience daemon driver…
return loop.Run(ctx, time.Minute)            // tick now, then every minute

// …or one Tick per reconciler event (shigoto's single-step contract):
report, err := loop.Tick(ctx)                // re-arm-due → one scheduler round
_ = report                                   // typed: Rearmed + shigoto receipt

loop.Status() returns a typed Status (per-item phase, stale flag, freshness age) for a CLI to render the uniform way (borealis.Render(theme, loop.Status())).

Freshness model

shigoto's FSM is single-shot (a job runs once, ends Succeeded). A keep-fresh item is recurring, so the loop re-arms it: at the start of each Tick, any item whose last successful refresh is older than its Interval (or which never refreshed) is reset to Pending and runs again; fresh items stay Succeeded and are skipped. Freshness is a pure in-memory decision — no timers, no sleeps inside the FSM — so the whole loop is offline-testable with an injected clock.

Configuration

The LOOP's policy (tool tag, tick cadence, concurrency caps) is a shikumi-go sub-struct consumed by FromConfig (BOREALIS Law 3). The keep-fresh ITEMS are registered imperatively (a Refresher is code, often a PRIVATE adapter, so it cannot come from yaml — only its cadence and bounds do).

type Root struct {
    Refresh refreshloop.Config `yaml:"refresh"`
}
// after shikumi.For[Root](…).Load(ctx):
loop, _ := refreshloop.FromConfig(cfg.Refresh)
return loop.Run(ctx, cfg.Refresh.TickInterval())
refresh:
  tool: akeyless-rotator     # stamped on every shigoto Transition (required)
  interval: 1m               # daemon poll cadence for Run (default 30s)
  max_concurrent: 8          # global cap on concurrent refreshes (0 ⇒ unbounded)
  kind_concurrency:          # per-kind caps (avoid a thundering recycle)
    pod-recycle: 2

Design notes (BOREALIS)

  • §3.5 shapes. New(tool, opts…) (*Loop, error), FromConfig(cfg) (*Loop, error); FromConfig never calls shikumi.Load. Typed Status rendered via borealis.Render.
  • Law 2 — composition over framework. A thin layer over shigoto's scheduler; it owns no FSM of its own — every transition is shigoto's Advance.
  • Law 5 — behaviour carriers. Refresher is a one-method interface; RefresherFunc adapts a closure. Consumers depend on the interface, not us.
  • Law 6 — weight import-gated. The only dependency is shigoto-go (itself x/sync only). No vendor SDKs in the core — those live in PRIVATE adapters.
  • Law 8 — no core-core cycle. Imports only shigoto-go; Config is a plain yaml-tagged struct read externally; the borealis render adapter for Status would live in a leaf sub-package, never the core.

Release

Pull-model (Go modules): an annotated vX.Y.Z tag is the release; pkg.go.dev indexes it. See the GSDS module delivery FSM. (Pre-publish, the cross-import of shigoto-go uses a replace … => ../shigoto-go directive, removed once shigoto-go is published.)

Documentation

Overview

Package refreshloop is the Go representation of pleme-io's "keep-X-fresh" refresh-loop primitive: a typed FSM, built ON shigoto-go, that drives a set of resources back to a fresh state on a cadence — rotating a secret before it expires, recycling a pod that has drifted, re-minting a token before its TTL elapses.

The recurring shape it removes: every keep-fresh tool hand-rolls the same loop — "is this thing stale? → if so, do the refresh → record when → wait → repeat" — with its own ad-hoc timer, its own retry-on-failure logic, its own concurrency cap, and its own audit trail. That is exactly the FSM + DAG + gate + budget + retry + emit algebra shigoto-go already owns. refreshloop is the thin, typed layer that turns that algebra into the keep-fresh idiom, so a consumer declares WHAT to keep fresh and HOW stale is "too stale", and never re-implements the loop.

The model

  • A Spec declares one keep-fresh item: a stable shigoto.JobID, a StepKind (the work class — KindSecretRotation, KindPodRecycle, or a caller-defined kind), an [Interval] (how fresh is fresh), and a Refresher (the side-effecting work).
  • A Refresher is the behaviour carrier (BOREALIS Law 5): one method, Refresh(ctx) error, the idempotent work that returns the item to fresh.
  • Freshness is a pure shigoto.Gate: an item is Ready to refresh iff its last-success age exceeds its Interval. Until then the gate Waits, so the scheduler holds the job in Gated — no timer, no sleep, just the FSM.
  • A Loop owns a shigoto.InProcessScheduler + a shigoto.Dag of the registered items. Loop.Tick advances every item one FSM round; the LOOP across ticks is the caller's (a daemon loops Tick→wait→Tick; a K8s reconciler maps each event to one Tick) — exactly shigoto's single-step contract. Loop.Run is the convenience daemon driver.

Worlds-separate (the public/private boundary)

This is a PUBLIC, generic primitive: it never names or imports akeyless. A secret-rotation Refresher that talks to akeyless is a PRIVATE adapter the consumer supplies — refreshloop only knows the generic Refresher shape and the KindSecretRotation step-kind label. "Pod recycle" is generic Kubernetes vocabulary; "secret rotation" is generic secret-management vocabulary; neither couples to a vendor.

Weight

The only dependency is github.com/pleme-io/shigoto-go (itself x/sync only). Everything here is stdlib + shigoto. Offline-testable: a Refresher and a clock are injectable, so a full keep-fresh cycle runs with no real timers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Tool is the consumer name stamped on every emitted shigoto Transition.
	// Required (an empty tool fails [FromConfig], matching [New]).
	Tool string `yaml:"tool" json:"tool"`

	// Interval is the daemon tick cadence used by [Loop.Run] (how often freshness
	// is re-checked). Zero defaults to 30s. It is the loop's poll period, not an
	// item's freshness window (that is per-[Spec]).
	Interval time.Duration `yaml:"interval" json:"interval"`

	// MaxConcurrent, when > 0, installs a global [shigoto.BudgetTree] cap on how
	// many items refresh at once. Zero means unbounded.
	MaxConcurrent uint32 `yaml:"max_concurrent" json:"max_concurrent"`

	// KindConcurrency sets per-kind concurrency caps (e.g. {"pod-recycle": 2}) so
	// a thundering recycle is bounded independently of the global cap. Absent
	// kinds are unbounded.
	KindConcurrency map[string]uint32 `yaml:"kind_concurrency" json:"kind_concurrency"`
}

Config is the typed, yaml-tagged knob surface for a Loop (BOREALIS Law 3). It is the sub-struct a caller's shikumi-loaded root config embeds:

type Root struct {
    Refresh refreshloop.Config `yaml:"refresh"`
}

and hands to FromConfig. Per §3.5, FromConfig consumes this already-loaded struct and MUST NOT itself call shikumi.Load — config loading happens once, at main, via shikumi.For[Root]; this primitive only consumes its sub-struct.

Config declares the LOOP's policy (tool tag, tick interval, per-kind concurrency caps). The keep-fresh ITEMS themselves are registered imperatively via Loop.Register with a live Refresher — a Refresher is code (often a PRIVATE vendor adapter), so it cannot come from yaml; only its cadence and bounds do.

func (Config) TickInterval

func (c Config) TickInterval() time.Duration

TickInterval is the resolved daemon poll cadence for Loop.Run: the configured Config.Interval, or 30s when unset. Exposed so a caller that builds a Loop via FromConfig can pass the same cadence to Loop.Run without re-deriving the default:

loop, _ := refreshloop.FromConfig(cfg.Refresh)
return loop.Run(ctx, cfg.Refresh.TickInterval())

type ItemStatus

type ItemStatus struct {
	// Scope/Kind/Subject identify the item.
	Scope   string `json:"scope" yaml:"scope"`
	Kind    string `json:"kind" yaml:"kind"`
	Subject string `json:"subject" yaml:"subject"`
	// Phase is the item's current shigoto FSM phase name (kebab-case).
	Phase string `json:"phase" yaml:"phase"`
	// Stale reports whether the item is currently due for refresh.
	Stale bool `json:"stale" yaml:"stale"`
	// AgeSeconds is how long since the last successful refresh (0 if never).
	AgeSeconds float64 `json:"age_seconds" yaml:"age_seconds"`
}

ItemStatus is one keep-fresh item's current state.

type Loop

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

Loop is the keep-X-fresh runtime: it owns a shigoto.InProcessScheduler and a shigoto.Dag of registered keep-fresh items, plus the per-item freshness bookkeeping (last-success time) that drives the re-arm decision. One Loop.Tick advances every DUE item one FSM round; the loop across ticks is the caller's (the shigoto single-step contract) — use Loop.Run for the daemon driver, or call Tick from a Kubernetes reconciler.

Freshness model. shigoto's FSM is single-shot: a job runs once and ends in the terminal Succeeded phase. A keep-fresh item is RECURRING, so the loop re-arms it: at the start of each Tick, any item whose last successful refresh is older than its Spec.Interval (or which has never refreshed) is reset to Pending so the scheduler runs it again; fresh items stay Succeeded and are skipped. This keeps freshness a pure, in-memory decision (no timers, no sleeps inside the FSM) and keeps every refresh, retry, and deadletter on shigoto's audited FSM.

The zero value is not usable; construct with New or FromConfig.

Concurrency: a Loop is safe for concurrent Loop.Register and freshness reads; Loop.Tick/Loop.Run are intended to be driven from a single goroutine (the scheduler advances one round per call).

func FromConfig

func FromConfig(cfg Config, opts ...Option) (*Loop, error)

FromConfig builds a *Loop from an already-loaded Config (§3.5). It is the canonical config-consuming constructor: it takes the sub-struct and MUST NOT call shikumi.Load. Extra [Option]s are applied after the config-derived ones, so a caller can layer non-yaml knobs (a real WithEmitter, a custom WithClock) on top. It returns an error for an empty Config.Tool.

The budget (global + per-kind caps) is built from the Config and installed via WithBudget before any caller option, so a caller's WithBudget wins by being applied last.

func New

func New(tool string, opts ...Option) (*Loop, error)

New constructs a Loop tagged with tool — the consumer name stamped on every emitted shigoto.Transition (e.g. "akeyless-rotator") — plus functional [Option]s (§3.5 canonical constructor). It returns an error only for an empty tool; the option-free path otherwise never errors. New never loads config from disk (Law 3); use FromConfig to consume an already-loaded sub-struct.

func (*Loop) Register

func (l *Loop) Register(s Spec) error

Register adds a keep-fresh item to the loop: it validates the Spec, records it, adds its shigoto.JobID as a DAG node, registers the per-kind retry policy and (once per kind) a freshness gate, and registers the wrapped Refresher as the shigoto job whose success stamps the item fresh.

Re-registering the same (Scope, Kind, Subject) replaces the prior Spec; the freshness clock is preserved. Returns an error for a malformed Spec. The item starts stale (never refreshed), so its first eligible Loop.Tick refreshes it.

func (*Loop) Run

func (l *Loop) Run(ctx context.Context, interval time.Duration) error

Run drives the keep-fresh loop until ctx is cancelled: it Ticks immediately, then every interval thereafter, returning ctx.Err() on cancellation (nil-able by the caller — a cancelled keep-fresh daemon is a clean stop, not a failure). interval should be the smallest Spec.Interval / a fraction of it, so a due item is noticed promptly; a non-positive interval defaults to 30s.

Run is the convenience daemon driver; a service composes lifecycle-go and calls Tick from an app.Go unit instead, so Run is for standalone tools.

func (*Loop) Status

func (l *Loop) Status() Status

Status returns a typed Status snapshot of every registered item — its FSM phase, whether it is currently stale, and its freshness age — for a CLI to render. Items are sorted by their stable (scope|kind|subject) key for deterministic output.

func (*Loop) Tick

func (l *Loop) Tick(ctx context.Context) (TickReport, error)

Tick advances the keep-fresh loop one round: it first re-arms every item that is DUE (stale per its Spec.Interval) back to Pending, then runs one shigoto.InProcessScheduler Tick over the DAG, which drives the due items Pending→Ready→Running (invoking their Refresher) →Succeeded, applying per-kind budgets and retry policies. Fresh items are untouched.

The LOOP across ticks is the caller's responsibility — a daemon loops Tick→wait→Tick (see Loop.Run); a Kubernetes reconciler maps each event to one Tick. A non-nil error means the DAG itself was malformed (a cycle); per-item refresh failures are reported via the receipt's phases/transitions, not the error.

type Option

type Option func(*Loop)

Option configures a Loop at construction (the functional-options half of the canonical `New(required…, opts…)` shape, BOREALIS §3.5).

func WithBudget

func WithBudget(b *shigoto.BudgetTree) Option

WithBudget installs a shigoto.BudgetTree on the underlying scheduler, capping how many keep-fresh items refresh concurrently (global × per-kind × per-scope). Without one, refreshes are unbounded — set a per-kind cap (e.g. at most 2 concurrent pod-recycles) to avoid a thundering recycle.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides the wall clock used for freshness decisions. It is the seam for deterministic tests and for a reconciler that wants a fixed "now" per event. A nil clock keeps time.Now.

func WithEmitter

func WithEmitter(e shigoto.TransitionEmitter) Option

WithEmitter installs a shigoto.TransitionEmitter on the underlying scheduler, so every keep-fresh FSM transition (Pending→Ready→Running→Succeeded, and every retry/deadletter) lands in an append-only audit sink. The default is the scheduler's NullEmitter.

type Refresher

type Refresher interface {
	// Refresh performs the (idempotent) keep-fresh work for subject within ctx.
	Refresh(ctx context.Context, subject string) error
}

Refresher is the behaviour carrier (BOREALIS Law 5): the one idempotent side-effecting operation that returns a keep-fresh item to a FRESH state. It is the seam a PRIVATE, vendor-coupled adapter implements (an akeyless secret rotator, a client-go pod recycler) while this PUBLIC package depends only on the interface.

Contract (mirroring shigoto's Job.Execute):

  • Refresh MUST be idempotent: the loop may re-invoke it after a crash between doing the work and recording success, so re-running must be safe.
  • Refresh MUST honour ctx cancellation (a per-item timeout or operator cancel maps to a failing return).
  • A returned error drives the item through shigoto's Failed → retry FSM. Wrap shigoto.ErrSkipRetry to deadletter immediately on a fatal failure.

type RefresherFunc

type RefresherFunc func(ctx context.Context, subject string) error

RefresherFunc adapts a plain function into a Refresher — the common authoring shape, so a caller rarely declares a bespoke struct:

spec := refreshloop.Spec{
    Subject:  "db-password",
    Kind:     refreshloop.KindSecretRotation,
    Interval: 12 * time.Hour,
    Refresher: refreshloop.RefresherFunc(func(ctx context.Context, subj string) error {
        return akl.RotateStatic(ctx, subj) // PRIVATE adapter
    }),
}

func (RefresherFunc) Refresh

func (f RefresherFunc) Refresh(ctx context.Context, subject string) error

Refresh calls the wrapped function.

type Spec

type Spec struct {
	// Scope is the breadth label flowed onto [shigoto.JobID].Scope (e.g.
	// "cluster:prod", "namespace:payments"). Empty defaults to "global". Budgets
	// can be set per-scope on the underlying scheduler.
	Scope string

	// Kind is the work class flowed onto [shigoto.JobID].Kind. Required.
	Kind StepKind

	// Subject is the concrete thing kept fresh, flowed onto
	// [shigoto.JobID].Subject (a secret path, a workload name). Required and
	// unique within (Scope, Kind).
	Subject string

	// Interval is the freshness window: the item is considered stale (and the
	// freshness gate opens) once its last successful refresh is older than this.
	// Must be positive.
	Interval time.Duration

	// Refresher is the idempotent keep-fresh work. Required.
	Refresher Refresher

	// Retry is the per-kind retry policy applied when [Refresher.Refresh] fails.
	// The zero value is [shigoto.NoRetry] (deadletter on first failure); set an
	// [shigoto.Exponential] policy for transient-failure resilience.
	Retry shigoto.RetryPolicy

	// Timeout optionally bounds a single Refresh call. Zero means run to
	// completion (or ctx cancellation).
	Timeout time.Duration
}

Spec declares one keep-fresh item: WHAT to keep fresh (Spec.Subject within a Spec.Kind and Spec.Scope), HOW fresh is fresh (Spec.Interval), and HOW to refresh it (Spec.Refresher). Loop.Register turns a Spec into a registered shigoto job + DAG node + freshness gate.

type Status

type Status struct {
	// Items is the per-item freshness snapshot, sorted by stable job key.
	Items []ItemStatus `json:"items" yaml:"items"`
}

Status is the typed point-in-time view of the loop for rendering, returned by Loop.Status. It is the data behind borealis.Render(theme, loop.Status()) (BOREALIS §3.5 / Law 4); the borealis render adapter would live in a leaf sub-package so this core never imports borealis (Law 8).

type StepKind

type StepKind string

StepKind is the work class of a keep-fresh item — the kind label that flows onto the underlying shigoto.JobID.Kind, so the scheduler's per-kind budgets, gates, and retry policies key off it. It is a string newtype (not an enum) so a consumer can declare its own kinds beyond the two the fleet recon surfaced, without this package gating the set (BOREALIS PRIME DIRECTIVE: the shape is fixed; the vocabulary is open).

const (
	// KindSecretRotation is the keep-fresh class for rotating a secret/credential
	// before it expires (re-mint, re-issue, re-key). Generic
	// secret-management vocabulary — the akeyless-specific Refresher that fulfils
	// it is a PRIVATE adapter the consumer supplies (worlds-separate).
	KindSecretRotation StepKind = "secret-rotation"

	// KindPodRecycle is the keep-fresh class for recycling a workload (delete +
	// let the controller recreate, or rollout-restart) so it picks up rotated
	// config/secrets or sheds drift. Generic Kubernetes vocabulary.
	KindPodRecycle StepKind = "pod-recycle"
)

func (StepKind) String

func (k StepKind) String() string

String returns the kind label.

type TickReport

type TickReport struct {
	// At is when the tick began.
	At time.Time
	// Rearmed is how many keep-fresh items were found due and reset to run this
	// tick (stale → Pending). Zero means everything was still fresh.
	Rearmed int
	// Receipt is the underlying shigoto rollup: per-phase counts, the FSM
	// transitions that fired, and the unhealed (deadlettered / awaiting-operator)
	// jobs.
	Receipt shigoto.TickReceipt
}

TickReport is the per-tick rollup Loop.Tick returns: the count of items re-armed (found due and reset to run again), the underlying shigoto.TickReceipt (phase counts + transitions + unhealed drift), and the items needing operator attention. It is the typed value a CLI renders the uniform way (BOREALIS Law 4: borealis.Render(theme, report)).

Jump to

Keyboard shortcuts

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