resolver

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 15 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 resolver wraps a segment.Provider with what a network store needs on the evaluation path: an in-process cache, coalescing of identical concurrent lookups and a circuit breaker for each segment.

The Resolver is itself a segment.Provider, so it fits any store. For each lookup it applies, in order: the normalisation of the segment, the cache (a bounded LRU with a TTL for members and a shorter one for non members), the breaker of the segment, and one coalesced call to the store for all the lookups that are neither cached nor already being asked by another caller.

Only a Member and a NotMember answer is cached. Unknown and errors never are. The resolver never applies a failure policy: a lookup it could not answer stays Unknown and the engine applies the policy.

Index

Constants

View Source
const (
	DefaultTTL             = 30 * time.Second
	DefaultNegativeTTL     = 5 * time.Second
	DefaultMaxEntries      = 10000
	DefaultShards          = 16
	DefaultBreakerFailures = 5
	DefaultBreakerCooldown = 10 * time.Second
	DefaultCallTimeout     = 2 * time.Second
	// DefaultMaxOverdue is the number of overdue shared calls from which no new call is started (see Options.MaxOverdue).
	DefaultMaxOverdue = 8
	// DefaultMaxIDBytes is the longest id that is looked up: a longer one is left Unknown and never sent to the store.
	DefaultMaxIDBytes = 512
	// DefaultShutdownGrace is how long the Shutdown of the store may run past the deadline of the first Shutdown of
	// the resolver (see Options.ShutdownGrace).
	DefaultShutdownGrace = 5 * time.Second
)

The defaults of a segment whose option is zero.

View Source
const DurationBucketCount = 14

DurationBucketCount is the number of buckets of the duration of a call: one for each of DurationBounds and one for the calls above the last bound.

View Source
const MaxObservedSegments = 8

MaxObservedSegments is the number of segments of one call that are reported one by one.

View Source
const ReasonCount = int(ReasonOverdue) + 1

ReasonCount is the number of values of Reason.

Variables

View Source
var (
	// ErrInvalidOptions is wrapped by the errors of options that are not valid.
	ErrInvalidOptions = errors.New("resolver: invalid options")
	// ErrNilProvider is returned when the wrapped provider is nil.
	ErrNilProvider = errors.New("resolver: nil provider")
)
View Source
var (
	// ErrCircuitOpen is returned when the breaker of a segment is open: the lookups are Unknown and the store was
	// not called.
	ErrCircuitOpen = errors.New("resolver: circuit open")
	// ErrWaiting is wrapped, with the error of the context, when the context of a caller (or the shared call)
	// ended while it waited for the store. The lookups it waited for are Unknown; the shared call goes on for the
	// other callers until its own timeout.
	ErrWaiting = errors.New("resolver: the context ended while waiting for the store")
	// ErrClosed is returned after Shutdown: no call reaches the store.
	ErrClosed = errors.New("resolver: closed")
	// ErrOverdue is returned when too many calls to the store are running after their timeout: the lookups that needed a
	// new call are Unknown and the store was not called.
	ErrOverdue = errors.New("resolver: too many calls to the store are overdue")
	// ErrShutdown is wrapped by the error of a Shutdown that ended before the calls in flight did.
	ErrShutdown = errors.New("resolver: shutdown ended before the calls in flight")
	// ErrProviderPanic is the error of a call to the store that panicked. The value of the panic is not kept.
	ErrProviderPanic = errors.New("resolver: the store panicked")
	// ErrUnsupported is returned by Exists when the store has no such operation.
	ErrUnsupported = errors.New("resolver: the store does not support this operation")
)

Functions

func DurationBounds

func DurationBounds() []time.Duration

DurationBounds returns the inclusive upper bounds of the duration buckets of Distribution; the last has none.

func NormalizeID

func NormalizeID(norm Normalization, id string) (string, bool)

NormalizeID returns the key of an id under a normalization: the bytes that the relay looks up and that a writer must store. An id that is not valid UTF-8 has no key when the segment normalises (ok is false): the lowering would replace its bytes by U+FFFD and two different ids could meet a member that holds that character. The resolver and the tools that write members both call it, so the two sides cannot drift.

Types

type BreakerEvent

type BreakerEvent struct {
	Segment  string
	From, To BreakerState
}

BreakerEvent is a change of state of the breaker of a segment.

type BreakerState

type BreakerState uint8

BreakerState is the state of the circuit breaker of a segment.

const (
	// BreakerClosed lets every call through.
	BreakerClosed BreakerState = iota
	// BreakerOpen answers Unknown at once, without a call to the store.
	BreakerOpen
	// BreakerHalfOpen lets one probe call through; its result closes or reopens the breaker.
	BreakerHalfOpen
)

func (BreakerState) String

func (s BreakerState) String() string

String implements fmt.Stringer.

type CallObservation

type CallObservation struct {
	// Lookups is the number of lookups of the call.
	Lookups int
	// Hits is the number answered by the cache.
	Hits int
	// Misses is the number this call asked the store for.
	Misses int
	// Coalesced is the number of lookups that joined a flight that already existed: one of another caller, or an earlier
	// lookup of the same call for the same id. Each of them costs no call to the store.
	Coalesced int
	// ShortCircuited is the number of lookups that were not sent to the store because the breaker of their segment was
	// open, or because too many calls were overdue (the Failure of the segment tells which: ReasonCircuitOpen or
	// ReasonOverdue).
	ShortCircuited int
	// NotLoaded is the number not asked because the segment was recently found not loaded.
	NotLoaded int
	// Oversized is the number left Unknown because the id is longer than MaxIDBytes.
	Oversized int
	// Invalid is the number left Unknown because the id is not valid UTF-8 and is normalised.
	Invalid int
	// Unknown is the number left Unknown.
	Unknown int
	// Duration is the time of the call, read from the clock package.
	Duration time.Duration
	// Failed is true when the call returned an error.
	Failed bool
}

CallObservation describes one call of Contains. It holds counts only, never an id.

type Counters

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

Counters is an Observer that counts with atomics. The zero value is ready to use.

func (*Counters) Distribution

func (c *Counters) Distribution() Distribution

Distribution returns the current duration buckets and reasons.

func (*Counters) ObserveBreaker

func (c *Counters) ObserveBreaker(ev BreakerEvent)

ObserveBreaker implements Observer.

func (*Counters) ObserveCall

func (c *Counters) ObserveCall(obs CallObservation)

ObserveCall implements Observer.

func (*Counters) ObserveSegment

func (c *Counters) ObserveSegment(obs SegmentObservation)

ObserveSegment implements Observer. The counters keep the totals of the calls, and the unknown lookups by reason.

func (*Counters) Snapshot

func (c *Counters) Snapshot() Stats

Snapshot returns the current counts.

type Distribution

type Distribution struct {
	// DurationBuckets counts the calls by duration, not cumulative (see [DurationBounds]).
	DurationBuckets [DurationBucketCount]uint64
	// Reasons counts the lookups that stayed Unknown by [Reason] of their segment (up to MaxObservedSegments segments of
	// a call are reported).
	Reasons [ReasonCount]uint64
}

Distribution is what Counters knows beyond the totals of Stats.

type Normalization

type Normalization string

Normalization is applied once to the id of a lookup, before the cache and the store.

const (
	// NormalizeNone leaves the id as it is. It is the default.
	NormalizeNone Normalization = "none"
	// NormalizeTrimLower trims the white space around the id and lowers it.
	NormalizeTrimLower Normalization = "trimLower"
)

type Observer

type Observer interface {
	ObserveCall(CallObservation)
	ObserveSegment(SegmentObservation)
	ObserveBreaker(BreakerEvent)
}

Observer receives what the resolver does. Its methods are called on the goroutine of the caller or of the shared call, so they must be fast, safe for concurrent use and must not call the resolver.

type Options

type Options struct {
	// Segments holds the settings of the named segments. A segment that is not here uses Default.
	Segments map[string]SegmentOptions
	// Observer (optional) receives the calls and the breaker transitions.
	Observer Observer
	// Default is the settings of the segments that Segments does not name.
	Default SegmentOptions
	// CallTimeout bounds the shared call to the store, which does not depend on the context of any one caller.
	// Zero means DefaultCallTimeout.
	CallTimeout time.Duration
	// MaxOverdue is the number of shared calls still running after their call timeout (a store that ignores its
	// context) from which no new call is started: the lookups that would need one are Unknown with ErrOverdue. It is
	// a threshold checked when a lookup would start a call, not a hard cap: calls that are started together, or just
	// before the count reaches it, can leave more overdue calls than MaxOverdue. Zero means DefaultMaxOverdue.
	MaxOverdue int
	// MaxIDBytes is the longest id, in bytes, that the resolver looks up. A longer id stays Unknown, is not cached
	// and is not sent to the store. Zero means DefaultMaxIDBytes.
	MaxIDBytes int
	// ShutdownGrace bounds the Shutdown of the store. The context that the resolver passes to it ends ShutdownGrace
	// after the deadline of the context of the first Shutdown of the resolver (ShutdownGrace after the call when that
	// context has no deadline), so a store that stops only when its context ends does not stay pending after every
	// caller has left. Zero means DefaultShutdownGrace.
	ShutdownGrace time.Duration
}

Options configures a Resolver.

type Reason

type Reason uint8

Reason is why the lookups of a segment in a call stayed Unknown, for the observers. The first reason wins.

const (
	// ReasonNone means every lookup was answered.
	ReasonNone Reason = iota
	// ReasonStore means the call to the store failed or left a lookup unanswered.
	ReasonStore
	// ReasonCircuitOpen means the breaker of the segment dropped the lookups.
	ReasonCircuitOpen
	// ReasonWaiting means the context of the caller, or the shared call, ended while it waited.
	ReasonWaiting
	// ReasonNotLoaded means the store said recently that the segment is not loaded, so it was not asked again.
	ReasonNotLoaded
	// ReasonOversized means the id is longer than MaxIDBytes.
	ReasonOversized
	// ReasonInvalid means the id is not valid UTF-8 and the segment normalises its ids.
	ReasonInvalid
	// ReasonUnanswered means the store replied without error and without an answer for the lookup.
	ReasonUnanswered
	// ReasonOverdue means too many calls to the store were still running after their timeout.
	ReasonOverdue
)

func (Reason) String

func (r Reason) String() string

String implements fmt.Stringer.

type Resolver

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

Resolver is a segment.Provider with a cache, coalescing and a breaker in front of another provider. It is safe for concurrent use.

func New

func New(inner segment.Provider, opts *Options) (*Resolver, error)

New returns a Resolver in front of inner.

func (*Resolver) AtomicExistence

func (r *Resolver) AtomicExistence() bool

AtomicExistence implements segment.AtomicExistencer by asking the store behind the resolver. It reports false for a store that is not an AtomicExistencer, so nothing above the resolver assumes a store: the lookups of such a store are answered by its own non-atomic behaviour, and the resolver's check of a segment that is not loaded (see segment.Existencer) stays a separate read.

func (*Resolver) Contains

func (r *Resolver) Contains(ctx context.Context, lookups []segment.Lookup) error

Contains implements segment.Provider.

func (*Resolver) Exists

func (r *Resolver) Exists(ctx context.Context, names []string) ([]segment.State, error)

Exists asks the store whether the segments are loaded. It returns ErrUnsupported when the store cannot tell.

func (*Resolver) Health

func (r *Resolver) Health() segment.Health

Health implements segment.HealthReporter: the health of the store when it reports one, and whether the resolver is closed.

func (*Resolver) Init

func (r *Resolver) Init(ctx context.Context) error

Init calls Init of the store when it has one.

func (*Resolver) Invalidate

func (r *Resolver) Invalidate(name string)

Invalidate drops the cached answers of a segment, the memory of a segment that was not loaded, and detaches the calls that are in flight for it: their answers are not cached, and a caller that comes after Invalidate asks the store again instead of joining them. It is the seam for a change notification: whatever learns that the members of a segment changed (a new version of the set, a sync of the tooling) calls it.

func (*Resolver) RefreshVersions

func (r *Resolver) RefreshVersions(ctx context.Context, versioner segment.Versioner) error

RefreshVersions is one step of the version watcher, driven by the caller off the request path (the resolver has no timer): it asks versioner for the version of each segment that has SegmentOptions.Versioned set, in name order, and applies it. It is admitted like a lookup: after Shutdown it returns ErrClosed, and Shutdown waits for a step in flight. A version that was read while a newer one was set (a push, another refresh) is dropped, the newer one wins. A segment whose version cannot be read keeps its current version (the time-to-live is the fallback); the errors of all such segments are joined, and the step goes on after one.

func (*Resolver) SetVersion

func (r *Resolver) SetVersion(name, token string) bool

SetVersion tells the resolver the current version of a segment. A token that differs from the current one starts a new generation: cached answers fetched under an earlier generation become misses (they are not flushed: they age out of the LRU), also when the token is one that the segment had before, and the calls in flight for the segment are detached, so their answers are not cached and a caller that comes after asks the store again. The same token changes nothing. It reports whether the version changed; a segment that is unknown to the resolver or has no cache is ignored.

It is the seam of change detection: Resolver.RefreshVersions calls it with what a versioner reports, and a segment.ChangeNotifier consumer calls it with a pushed change.

func (*Resolver) Shutdown

func (r *Resolver) Shutdown(ctx context.Context) error

Shutdown stops accepting calls, waits for the calls to the store that are in flight (until ctx ends), and calls Shutdown of the store once. After it started, no call reaches the store: Contains returns ErrClosed. A second Shutdown waits again for the calls in flight, and returns nil when they are done.

func (*Resolver) Status

func (r *Resolver) Status() Status

Status returns a snapshot of the breakers and the caches.

type SegmentObservation

type SegmentObservation struct {
	// Segment is the name of the segment.
	Segment string
	// Lookups is the number of lookups of the segment in the call.
	Lookups int
	// Hits, Misses, Coalesced and Unknown are as in [CallObservation], for this segment.
	Hits, Misses, Coalesced, Unknown int
	// Failure is why lookups stayed Unknown.
	Failure Reason
}

SegmentObservation is the part of a call that concerns one segment. A call that touches more than MaxObservedSegments segments reports the first ones.

type SegmentOptions

type SegmentOptions struct {
	// Normalize is applied to the ids. Empty means NormalizeNone.
	Normalize Normalization
	// TTL is how long a Member is cached. Zero means DefaultTTL.
	TTL time.Duration
	// NegativeTTL is how long a NotMember is cached. Zero means DefaultNegativeTTL.
	NegativeTTL time.Duration
	// MaxEntries bounds the entries of the cache of the segment. Zero means DefaultMaxEntries.
	MaxEntries int
	// Shards is the number of locks of the cache. Zero means DefaultShards, 1 is one lock.
	Shards int
	// BreakerFailures is the number of consecutive failed calls that open the breaker. Zero means
	// DefaultBreakerFailures.
	BreakerFailures int
	// BreakerCooldown is how long the breaker stays open before it lets one probe through. Zero means
	// DefaultBreakerCooldown.
	BreakerCooldown time.Duration
	// NoCache turns the cache of the segment off.
	NoCache bool
	// NoBreaker turns the breaker of the segment off.
	NoBreaker bool
	// Versioned makes [Resolver.RefreshVersions] ask for the version of the segment. Without it the segment has no
	// version and only the time-to-live applies.
	Versioned bool
}

SegmentOptions are the settings of one segment. A zero field takes its default.

type SegmentStatus

type SegmentStatus struct {
	// Version is the segment version that cached answers must match, empty when none was learned.
	Version string
	// Breaker is the state of the breaker, BreakerClosed when there is none.
	Breaker BreakerState
	// Failures is the number of consecutive failed calls counted by a closed breaker.
	Failures int
	// Entries is the number of cached answers.
	Entries int
	// Joined is the number of lookups that joined the call of another caller since the start.
	Joined uint64
	// NotLoaded is the number of lookups not asked because the segment was recently found not loaded.
	NotLoaded uint64
}

SegmentStatus is the state of one segment of the resolver.

type Stats

type Stats struct {
	// Calls .. Failed sum the fields of the observations of the same name.
	Calls, Lookups, Hits, Misses, Coalesced, ShortCircuited, NotLoaded, Oversized, Invalid, Unknown, Failed uint64
	// Duration is the sum of the durations.
	Duration time.Duration
	// BreakerOpened, BreakerHalfOpened and BreakerClosed count the transitions to each state.
	BreakerOpened, BreakerHalfOpened, BreakerClosed uint64
}

Stats is a snapshot of the counters of Counters.

type Status

type Status struct {
	// Segments is the state of each segment that was configured or looked up.
	Segments map[string]SegmentStatus
	// Running is the number of shared calls to the store that have not returned.
	Running int
	// Overdue is the number of those that are running after their context ended: a store that ignores its context.
	Overdue int
	// Closed is true after Shutdown.
	Closed bool
}

Status is a snapshot of the resolver.

type StoreError

type StoreError struct {
	// Err is the error of the store.
	Err error
}

StoreError is the error of a call to the store as the callers of the resolver see it. Its message is fixed: the message of the store may hold an address, a key or an id, and a caller logs what it gets. The error of the store is still there for errors.Is and errors.As.

func (*StoreError) Error

func (*StoreError) Error() string

Error implements error.

func (*StoreError) Unwrap

func (e *StoreError) Unwrap() error

Unwrap returns the error of the store.

Jump to

Keyboard shortcuts

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