concurrency

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: BSD-3-Clause Imports: 11 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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PanicToError

func PanicToError(r any) error

PanicToError converts a recovered panic value into an error.

func RecoverToError

func RecoverToError(errPtr *error, label string, args ...any)

RecoverToError converts a panic in the calling goroutine into an error and logs it. x/sync's errgroup does not recover worker panics — they crash the whole process — so every worker defers this as its first statement:

g.Go(func() (workerErr error) {
	defer concurrency.RecoverToError(&workerErr, "image list worker")
	...
})

It must be deferred directly (not wrapped in another closure) for recover() to observe the panic. errPtr may be nil when the caller has no error to report into (e.g. a fire-and-forget goroutine); the panic is still logged. args are extra slog attributes appended to the log record.

func WaitGroup

func WaitGroup(ctx context.Context, group *sync.WaitGroup) error

WaitGroup waits for all work or returns when ctx ends. After a timeout, its waiter goroutine remains until the group eventually completes.

Types

type Backoff

type Backoff struct {
	Base    time.Duration
	Max     time.Duration
	Strikes int
	Jitter  bool
}

func (Backoff) Delay

func (b Backoff) Delay(attempt int) time.Duration

func (Backoff) Sleep

func (b Backoff) Sleep(ctx context.Context, attempt int) error

type KeyedMutex

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

KeyedMutex hands out one mutex per key, so unrelated keys proceed concurrently while work on the same key is serialized.

Entries are reference counted and dropped once nobody holds or awaits them. The naive version of this — a sync.Map of *sync.Mutex — either grows one entry per key ever seen, or, if entries are deleted on release, hands two callers different mutexes for the same key and silently loses mutual exclusion. The reference count is taken under the map lock, so a key with waiters is never removed.

The zero value is ready to use.

func (*KeyedMutex) Lock

func (k *KeyedMutex) Lock(key string) func()

Lock blocks until the key's mutex is held and returns its unlock function. Intended to be deferred at the point of acquisition:

defer locks.Lock(id)()

func (*KeyedMutex) LockContext

func (k *KeyedMutex) LockContext(ctx context.Context, key string) (func(), error)

LockContext is Lock bounded by ctx. When ctx ends first the key is left untouched and the waiter is released once the lock would have been taken.

func (*KeyedMutex) RLock

func (k *KeyedMutex) RLock(key string) func()

RLock blocks until the key's mutex is held for reading and returns its unlock function. Multiple readers for the same key may proceed concurrently.

func (*KeyedMutex) TryLock

func (k *KeyedMutex) TryLock(key string) (func(), bool)

TryLock acquires the key's mutex without blocking. It reports whether the lock was taken; the unlock function is only valid when it was.

type Signal

type Signal[T any] struct {
	// contains filtered or unexported fields
}

Signal delivers each published value once to every current subscriber. Subscribers run sequentially on the publishing goroutine.

func NewSignal

func NewSignal[T any]() *Signal[T]

NewSignal creates an empty typed signal.

func (*Signal[T]) Publish

func (s *Signal[T]) Publish(value T)

Publish synchronously delivers value without holding the subscriber lock.

func (*Signal[T]) Subscribe

func (s *Signal[T]) Subscribe(callback func(T)) func()

Subscribe registers a callback and returns an idempotent unsubscribe function.

type Snapshot

type Snapshot[T any] struct {
	// contains filtered or unexported fields
}

Snapshot publishes immutable copies of a value for lock-free readers.

func (*Snapshot[T]) Load

func (s *Snapshot[T]) Load() (T, bool)

Load returns a copy of the latest published value.

func (*Snapshot[T]) Store

func (s *Snapshot[T]) Store(value T)

Store replaces the published value with an immutable copy.

type StateMap

type StateMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

StateMap owns mutable keyed state while publishing immutable snapshots for readers.

func NewStateMap

func NewStateMap[K comparable, V any]() *StateMap[K, V]

NewStateMap creates a locally serialized state map for process-local state.

func (*StateMap[K, V]) Apply

func (s *StateMap[K, V]) Apply(ctx context.Context, label string, mutate func(map[K]V) (changed bool, err error)) error

Apply serializes a mutation and publishes it atomically when changed is true.

func (*StateMap[K, V]) ApplyTyped

func (s *StateMap[K, V]) ApplyTyped[R any](
	ctx context.Context,
	label string,
	mutate func(map[K]V) (result R, changed bool, err error),
) (R, error)

ApplyTyped serializes a typed mutation and publishes its resulting state.

func (*StateMap[K, V]) Get

func (s *StateMap[K, V]) Get(key K) (V, bool)

Get reads one value from the latest immutable snapshot without acquiring the mutation lock.

func (*StateMap[K, V]) Remove

func (s *StateMap[K, V]) Remove(ctx context.Context, label string, key K) (V, bool, error)

Remove deletes and returns one value.

func (*StateMap[K, V]) RemoveWhere

func (s *StateMap[K, V]) RemoveWhere(ctx context.Context, label string, predicate func(K, V) bool) ([]V, error)

RemoveWhere atomically removes every value selected by predicate.

func (*StateMap[K, V]) Store

func (s *StateMap[K, V]) Store(ctx context.Context, label string, key K, value V) (V, bool, error)

Store publishes a value and returns the value it replaced, if any.

func (*StateMap[K, V]) Values

func (s *StateMap[K, V]) Values() []V

Values reads every value from the latest immutable snapshot.

type SuperviseConfig

type SuperviseConfig struct {
	Run     func(context.Context) error
	Logger  *slog.Logger
	Name    string
	Backoff Backoff
}

type Supervisor

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

func Supervise

func Supervise(ctx context.Context, cfg SuperviseConfig) *Supervisor

func (*Supervisor) Restart

func (s *Supervisor) Restart()

func (*Supervisor) State

func (s *Supervisor) State() SupervisorState

func (*Supervisor) Stop

func (s *Supervisor) Stop(ctx context.Context) error

type SupervisorState

type SupervisorState struct {
	UpdatedAt time.Time
	NextRetry *time.Time
	Status    SupervisorStatus
	LastError string
}

type SupervisorStatus

type SupervisorStatus string
const (
	SupervisorStarting       SupervisorStatus = "starting"
	SupervisorRunning        SupervisorStatus = "running"
	SupervisorRetrying       SupervisorStatus = "retrying"
	SupervisorNeedsAttention SupervisorStatus = "needs_attention"
	SupervisorStopped        SupervisorStatus = "stopped"
)

type SyncGate

type SyncGate struct {
	Expiry time.Duration
	// contains filtered or unexported fields
}

SyncGate remembers the SHA-256 of the last payload delivered per scope and key so periodic re-syncs skip the network when nothing changed, and serializes deliveries for one key so overlapping pushes reach the target in the order they are remembered. Only the digest is retained. Expiry bounds how long a delivery is trusted (zero means forever) so a target rebuilt behind an unchanged status still converges. The zero value is ready to use.

func (*SyncGate) Begin

func (g *SyncGate) Begin(ctx context.Context, scope, key string, body []byte) (unchanged bool, finish func(delivered bool), err error)

Begin reports whether body is already delivered for scope and key. When it is not, the key stays locked until finish runs; finish(true) remembers the delivery unless the scope was forgotten in between. Callers must invoke finish exactly once. Waiting for an in-flight delivery ends with ctx.

func (*SyncGate) Forget

func (g *SyncGate) Forget(scope string)

Forget drops every remembered payload for scope so the next sync resends, and discards the outcome of deliveries still in flight for it.

Jump to

Keyboard shortcuts

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