mirror of
https://tangled.org/evan.jarrett.net/at-container-registry
synced 2026-09-20 17:24:16 +00:00
50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package jetstream
|
|
|
|
import "sync"
|
|
|
|
// EndpointRotator cycles through a list of endpoint URLs for failover.
|
|
// Thread-safe via sync.Mutex.
|
|
type EndpointRotator struct {
|
|
mu sync.Mutex
|
|
endpoints []string
|
|
index int
|
|
}
|
|
|
|
// NewEndpointRotator creates a rotator from a list of endpoints.
|
|
// Panics if endpoints is empty.
|
|
func NewEndpointRotator(endpoints []string) *EndpointRotator {
|
|
if len(endpoints) == 0 {
|
|
panic("EndpointRotator requires at least one endpoint")
|
|
}
|
|
return &EndpointRotator{
|
|
endpoints: endpoints,
|
|
}
|
|
}
|
|
|
|
// Current returns the current endpoint without advancing.
|
|
func (r *EndpointRotator) Current() string {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
return r.endpoints[r.index]
|
|
}
|
|
|
|
// Next advances to the next endpoint (wrapping around) and returns it.
|
|
func (r *EndpointRotator) Next() string {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.index = (r.index + 1) % len(r.endpoints)
|
|
return r.endpoints[r.index]
|
|
}
|
|
|
|
// Reset returns to the first endpoint.
|
|
func (r *EndpointRotator) Reset() {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.index = 0
|
|
}
|
|
|
|
// Len returns the number of endpoints.
|
|
func (r *EndpointRotator) Len() int {
|
|
return len(r.endpoints)
|
|
}
|