feedsched

package
v1.0.430 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 5 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 feedsched is the shared cadence engine for Culvert's periodic intelligence feeds: bounded exponential backoff after a failed round, a stable per-node jitter offset on the steady-state interval, and prompt cancellation — all behind injectable clock/timer/jitter seams so a feed's schedule is unit-testable with a fake clock and no sleeps.

Why this package exists

Culvert ships THREE periodic feed loops and, before this package, only the newest of them scheduled itself correctly:

  • the signed SaaS URL-category feed (main's saasFeedScheduler) — bounded backoff, stable ±10% jitter, immediate wakeup, fake-clock tests;
  • the UT1 community category feed (internal/feedsync) — a bare time.NewTicker(24h);
  • the URLhaus/OpenPhish threat feed (internal/threatfeed) — a bare time.NewTicker(6h).

A bare ticker has two failure modes, and both are reachable by ordinary operations rather than by an exotic fault.

**A failed round is not retried until the next full interval.** The threat feed's round fetches two public endpoints over the customer's own egress path; a DNS blip, a 503 from the provider, a proxy restart or a few seconds of packet loss fails it. Nothing then re-attempts for SIX HOURS. The worst shape is a node that boots into a feed outage: `Start` syncs immediately when the on-disk DB is empty, so a fresh or re-imaged node whose first sync fails runs with ZERO threat intelligence — not stale intelligence, none — until the first tick, with every probe reporting a healthy node. For the category feed the same window is TWENTY-FOUR hours.

**A fleet stays in phase forever.** `time.NewTicker` fires at a fixed offset from process start, so nodes that boot together — a rolling upgrade, a compose restart, a hypervisor recovering a rack — sync together, forever. Culvert's feed origins are third-party and shared (abuse.ch, openphish.com, and a raw.githubusercontent.com mirror serving a 50+ MB tarball), so a fleet in lockstep is a self-inflicted thundering herd against a provider that answers it by rate-limiting the customer's egress IP. That closes a loop: the herd causes the failure, and the absent retry then holds the whole fleet at that failure for a full interval.

The contract

  • After a SUCCESSFUL round the next delay is the configured interval, offset by a per-scheduler jitter fraction chosen ONCE (stable per node, spread across the fleet — re-rolling per tick would let nodes drift back into phase and would make the cadence untestable).
  • After a FAILED round the next delay is bounded exponential backoff from BackoffMin, doubling, clamped at BackoffMax, jittered the same way. The failure count resets on the first success.
  • BackoffMax is expected to sit BELOW the steady-state interval, so retries are strictly a *tightening* of the cadence: a persistently failing feed converges on one attempt per BackoffMax and never on more traffic than a healthy one would generate at its own interval. `New` clamps a misconfigured BackoffMax down to the interval rather than trusting it.
  • Retries are unbounded in COUNT but bounded in RATE, and never silent: the owning feed counts and reports every failure (see the health planes in internal/threatfeed and internal/feedsync). This is the same posture ha_lease_recovery.go records — "avoid infinite retries" forbids a silent hot loop, not a rate-bounded loop whose state an operator can read. A feed that stopped retrying would be strictly worse: intelligence would freeze permanently on one transient error.
  • The wait is interruptible: ctx cancellation returns promptly from inside a backoff, so shutdown never waits out a delay.
  • A panicking round is a FAILED round, not a dead loop. Containment is at the round, per internal/obs's rule (guard the iteration, never the goroutine) — a bad feed body costs one window and backs off, rather than killing an in-line gateway or silently stalling the loop forever.

The main-side saasFeedScheduler predates this package and additionally owns an immediate config-change wakeup bound to its runtime; migrating it onto these seams is recorded as a follow-up rather than bundled into a chaos fix.

Index

Constants

View Source
const (
	// DefaultBackoffMin is the first retry delay after a failed round. Chosen
	// well above a provider's transient-error window and far below any feed's
	// steady-state interval: it recovers a DNS blip in minutes instead of
	// hours, while never being fast enough to look like a retry storm to the
	// third-party origin.
	DefaultBackoffMin = 5 * time.Minute

	// DefaultBackoffMax caps the retry delay. See the Config.BackoffMax note:
	// New additionally clamps this to the feed's own interval, so retrying can
	// only ever tighten the cadence, never loosen it past a healthy node's.
	DefaultBackoffMax = 1 * time.Hour

	// DefaultJitterFrac matches the main-side saasFeedScheduler's ±10%.
	DefaultJitterFrac = 0.10
)

Variables

This section is empty.

Functions

func StableJitter

func StableJitter(frac float64) func(time.Duration) time.Duration

StableJitter returns a jitter function whose offset within ±frac is chosen ONCE. Stable per node for the process lifetime, spread across the fleet.

Deliberately not re-rolled per tick: a per-tick roll gives the same expected cadence but lets two nodes that happen to draw similar offsets drift back into phase over time, and it makes the schedule unreproducible in a test.

Types

type Clock

type Clock interface {
	NewTimer(d time.Duration) Timer
}

Clock is the injectable timer factory. Production uses RealClock; tests supply a fake so cadence, backoff growth and cancellation are asserted deterministically without sleeping.

Deliberately narrower than the main-side saasFeedScheduler's schedClock: this loop never reads the wall clock (it schedules purely by relative delay), so a Now() method would be dead surface a fake has to implement for nothing.

type Config

type Config struct {
	// Name identifies the feed in log lines. Never rendered into an alert.
	Name string

	// Interval returns the steady-state cadence between successful rounds.
	Interval func() time.Duration

	// Run performs one round and reports whether it succeeded. It must respect
	// ctx and must not panic — but if it does, the scheduler contains it and
	// charges the round as a failure.
	Run func(ctx context.Context) bool

	// RunNow reports whether a round should happen immediately at t=0 rather
	// than after the first interval. Feeds use this for the cold-start case
	// ("the on-disk DB is empty, so serve nothing until we fetch"). Nil means
	// no immediate round.
	RunNow func() bool

	// BackoffMin / BackoffMax bound the post-failure retry delay. Zero values
	// take the package defaults.
	BackoffMin time.Duration
	BackoffMax time.Duration

	// JitterFrac is the ±fraction applied to every computed delay.
	JitterFrac float64

	// Clock and Jitter are test seams; nil takes the production implementations.
	Clock  Clock
	Jitter func(time.Duration) time.Duration

	// OnPanic is invoked when a round panics, before it is charged as a
	// failure. Nil falls back to a WARN line naming the feed.
	//
	// In production both feeds additionally wrap their round body in
	// obs.SafeCall, so a panic in the FEED reaches the crash-recording plane
	// (metric + audit + log) and never gets this far. This recover is the
	// second layer, covering a panic in the Run closure itself; it exists so
	// that layer can never turn into a dead loop or a process kill.
	OnPanic func(v any)
}

Config describes one feed's schedule. Interval is a function rather than a value so a feed whose cadence is admin-tunable is re-read every round instead of being frozen at construction.

type RealClock

type RealClock struct{}

RealClock is the production Clock.

func (RealClock) NewTimer

func (RealClock) NewTimer(d time.Duration) Timer

NewTimer implements Clock.

type Scheduler

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

Scheduler is one feed's cadence loop.

func New

func New(cfg Config) *Scheduler

New builds a Scheduler, filling in production seams and defaults.

The BackoffMax clamp is the load-bearing default: a feed that configured a backoff ceiling ABOVE its own interval would, after a failure, retry LESS often than a healthy node syncs — turning the recovery mechanism into an additional delay. Clamping here means a caller cannot express that.

func (*Scheduler) Failures

func (s *Scheduler) Failures() int

Failures reports the current consecutive-failure count (0 after any success).

func (*Scheduler) NextDelay

func (s *Scheduler) NextDelay(ok bool) time.Duration

NextDelay computes the delay after a round with the given outcome and advances the consecutive-failure count. Exported for the feeds' own tests to pin the cadence contract without driving a loop.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context)

Run drives the loop until ctx is cancelled. It blocks; callers own the goroutine.

type Timer

type Timer interface {
	C() <-chan time.Time
	Reset(d time.Duration) bool
	Stop() bool
}

Timer is the injectable timer seam (production wraps *time.Timer).

Jump to

Keyboard shortcuts

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