Documentation
¶
Overview ¶
Package wait provides utilities for waiting on various conditions with configurable strategies
Index ¶
- Variables
- func All(conditions []ConditionFunc, opts ...*Options) error
- func Any(conditions []ConditionFunc, opts ...*Options) (int, error)
- func ForAnyPort(ports []int, opts ...*Options) (int, error)
- func ForCommand(name string, args []string, opts ...*Options) error
- func ForConditionWithTimeout(condition ConditionFunc, timeout time.Duration) error
- func ForDNS(hostname string, opts ...*Options) error
- func ForDirectory(path string, opts ...*Options) error
- func ForDuration(duration time.Duration) error
- func ForEnvironmentVariable(key string, opts ...*Options) error
- func ForEnvironmentVariableValue(key, expectedValue string, opts ...*Options) error
- func ForFile(path string, opts ...*Options) error
- func ForFileContent(path string, minSize int64, opts ...*Options) error
- func ForFileRemoval(path string, opts ...*Options) error
- func ForHTTP(url string, opts ...*Options) error
- func ForHTTPSHealthy(url string, opts ...*Options) error
- func ForHTTPStatus(url string, expectedStatuses []int, opts ...*Options) error
- func ForLocalNetwork(opts ...*Options) error
- func ForMultiplePorts(ports []int, opts ...*Options) error
- func ForNetwork(opts ...*Options) error
- func ForPort(port int, opts ...*Options) error
- func ForProcess(pid int, opts ...*Options) error
- func ForProcessExit(pid int, opts ...*Options) error
- func ForTCP(address string, opts ...*Options) error
- func ForTime(target time.Time, opts ...*Options) error
- func ForUDP(address string, opts ...*Options) error
- func Forever(fn func() error, interval time.Duration) error
- func Poll(fn func() error, opts ...*Options) error
- func Retry(fn func() error, maxRetries int) error
- func RetryWithBackoff(fn func() error, initial time.Duration, maxRetries int) error
- func Until(condition ConditionFunc, opts ...*Options) error
- func UntilWithResult(condition ConditionWithResultFunc, opts ...*Options) (interface{}, error)
- type ConditionFunc
- type ConditionWithResultFunc
- type CustomStrategy
- type DecorrelatedJitterStrategy
- type ExponentialBackoffStrategy
- type FibonacciStrategy
- type FixedStrategy
- type Group
- type InterfaceInfo
- type LinearStrategy
- type NetworkInfo
- type Options
- type Strategy
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrTimeout = errors.New("wait: timeout exceeded") ErrMaxRetriesReached = errors.New("wait: maximum retries reached") ErrCanceled = errors.New("wait: operation canceled") )
Common errors
Functions ¶
func All ¶
func All(conditions []ConditionFunc, opts ...*Options) error
All waits until all conditions are met
func Any ¶
func Any(conditions []ConditionFunc, opts ...*Options) (int, error)
Any waits until any condition is met
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait for any of multiple conditions
conditions := []wait.ConditionFunc{
func() (bool, error) {
// Check primary server
return false, nil // simplified
},
func() (bool, error) {
// Check backup server
return true, nil // simplified
},
}
index, err := wait.Any(
conditions,
wait.DefaultOptions().WithTimeout(10*time.Second),
)
if err != nil {
log.Printf("No server available: %v", err)
} else {
fmt.Printf("Server %d is available\n", index)
}
}
Output:
func ForAnyPort ¶
ForAnyPort waits until any of the specified ports is open on localhost
func ForCommand ¶
ForCommand waits until a command executes successfully
func ForConditionWithTimeout ¶
func ForConditionWithTimeout(condition ConditionFunc, timeout time.Duration) error
ForConditionWithTimeout is a convenience function that waits with a simple timeout
func ForDirectory ¶
ForDirectory waits until a directory exists
func ForDuration ¶
ForDuration waits for a specific duration from now
func ForEnvironmentVariable ¶
ForEnvironmentVariable waits until an environment variable is set
func ForEnvironmentVariableValue ¶
ForEnvironmentVariableValue waits until an environment variable has a specific value
func ForFileContent ¶
ForFileContent waits until a file exists and has content
func ForFileRemoval ¶
ForFileRemoval waits until a file is removed
func ForHTTP ¶
ForHTTP waits until an HTTP endpoint returns a successful response
Example ¶
package main
import (
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait for a service to be healthy
err := wait.ForHTTPSHealthy(
"http://localhost:8080/health",
wait.DefaultOptions().
WithMaxRetries(10).
WithStrategy(wait.NewExponentialBackoffStrategy(
1*time.Second, // initial delay
2.0, // multiplier
30*time.Second, // max delay
true, // add jitter
)),
)
if err != nil {
log.Printf("Service not healthy: %v", err)
}
}
Output:
func ForHTTPSHealthy ¶
ForHTTPSHealthy waits until an HTTP endpoint returns any 2xx status
func ForHTTPStatus ¶
ForHTTPStatus waits until an HTTP endpoint returns one of the expected status codes
func ForLocalNetwork ¶
ForLocalNetwork waits for any network connectivity (including local)
func ForMultiplePorts ¶
ForMultiplePorts waits until all specified ports are open on localhost
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait for multiple services to be ready
ports := []int{8080, 8081, 8082}
err := wait.ForMultiplePorts(
ports,
wait.DefaultOptions().
WithTimeout(2*time.Minute).
WithStrategy(wait.NewLinearStrategy(
1*time.Second, // initial
500*time.Millisecond, // increment
5*time.Second, // max
)),
)
if err != nil {
log.Printf("Not all ports are available: %v", err)
} else {
fmt.Println("All services are ready")
}
}
Output:
func ForNetwork ¶
ForNetwork waits for network connectivity (global unicast IP)
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait for network connectivity with timeout
err := wait.ForNetwork(
wait.DefaultOptions().
WithTimeout(30 * time.Second).
WithStrategy(wait.NewFixedStrategy(2 * time.Second)),
)
if err != nil {
log.Printf("Network not available: %v", err)
} else {
fmt.Println("Network is available")
}
}
Output:
func ForProcess ¶
ForProcess waits until a process with the given PID exists
func ForProcessExit ¶
ForProcessExit waits until a process exits
func RetryWithBackoff ¶
RetryWithBackoff executes a function with exponential backoff
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Retry a function with exponential backoff
attempts := 0
err := wait.RetryWithBackoff(func() error {
attempts++
fmt.Printf("Attempt %d\n", attempts)
if attempts < 3 {
return fmt.Errorf("not ready yet")
}
return nil
}, 100*time.Millisecond, 5)
if err != nil {
log.Printf("Failed after retries: %v", err)
}
}
Output:
func Until ¶
func Until(condition ConditionFunc, opts ...*Options) error
Until waits until the condition returns true or an error occurs
Example ¶
package main
import (
"fmt"
"log"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait until a custom condition is met
counter := 0
err := wait.Until(func() (bool, error) {
counter++
return counter >= 3, nil
}, wait.DefaultOptions().WithMaxRetries(5))
if err != nil {
log.Fatal(err)
}
fmt.Println("Condition met after", counter, "attempts")
}
Output:
func UntilWithResult ¶
func UntilWithResult(condition ConditionWithResultFunc, opts ...*Options) (interface{}, error)
UntilWithResult waits until condition is met and returns the result
Types ¶
type ConditionFunc ¶
ConditionFunc represents a function that returns true when a condition is met
type ConditionWithResultFunc ¶
ConditionWithResultFunc represents a function that returns a result when condition is met
type CustomStrategy ¶
type CustomStrategy struct {
// contains filtered or unexported fields
}
CustomStrategy allows custom wait durations
Example ¶
package main
import (
"fmt"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Use custom wait durations
durations := []time.Duration{
100 * time.Millisecond,
200 * time.Millisecond,
500 * time.Millisecond,
1 * time.Second,
2 * time.Second,
}
strategy := wait.NewCustomStrategy(durations, false)
err := wait.Until(
func() (bool, error) {
// Your condition here
return false, nil
},
wait.DefaultOptions().WithStrategy(strategy),
)
if err != nil {
fmt.Printf("Condition not met: %v\n", err)
}
}
Output:
func NewCustomStrategy ¶
func NewCustomStrategy(durations []time.Duration, repeat bool) *CustomStrategy
NewCustomStrategy creates a new custom wait strategy
type DecorrelatedJitterStrategy ¶
type DecorrelatedJitterStrategy struct {
// contains filtered or unexported fields
}
DecorrelatedJitterStrategy implements AWS-style decorrelated jitter
func NewDecorrelatedJitterStrategy ¶
func NewDecorrelatedJitterStrategy(base, max time.Duration) *DecorrelatedJitterStrategy
NewDecorrelatedJitterStrategy creates a new decorrelated jitter strategy
func (*DecorrelatedJitterStrategy) Next ¶
func (s *DecorrelatedJitterStrategy) Next() (time.Duration, bool)
Next returns the next wait duration
func (*DecorrelatedJitterStrategy) Reset ¶
func (s *DecorrelatedJitterStrategy) Reset()
Reset resets the strategy
type ExponentialBackoffStrategy ¶
type ExponentialBackoffStrategy struct {
// contains filtered or unexported fields
}
ExponentialBackoffStrategy implements exponential backoff with optional jitter
func NewExponentialBackoffStrategy ¶
func NewExponentialBackoffStrategy(initial time.Duration, multiplier float64, max time.Duration, jitter bool) *ExponentialBackoffStrategy
NewExponentialBackoffStrategy creates a new exponential backoff strategy
func (*ExponentialBackoffStrategy) Next ¶
func (s *ExponentialBackoffStrategy) Next() (time.Duration, bool)
Next returns the next wait duration
func (*ExponentialBackoffStrategy) Reset ¶
func (s *ExponentialBackoffStrategy) Reset()
Reset resets the strategy
type FibonacciStrategy ¶
type FibonacciStrategy struct {
// contains filtered or unexported fields
}
FibonacciStrategy implements Fibonacci sequence based backoff
func NewFibonacciStrategy ¶
func NewFibonacciStrategy(unit, max time.Duration) *FibonacciStrategy
NewFibonacciStrategy creates a new Fibonacci wait strategy
type FixedStrategy ¶
type FixedStrategy struct {
// contains filtered or unexported fields
}
FixedStrategy waits for a fixed duration between attempts
func NewFixedStrategy ¶
func NewFixedStrategy(duration time.Duration) *FixedStrategy
NewFixedStrategy creates a new fixed wait strategy
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group manages multiple wait operations
Example ¶
package main
import (
"log"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Wait for multiple conditions
group := wait.NewGroup()
// Add various conditions
group.Add(func() (bool, error) {
// Check if database is ready
return true, nil // simplified
})
group.Add(func() (bool, error) {
// Check if cache is ready
return true, nil // simplified
})
group.AddFunc(func() error {
// Check if config is loaded
return nil // simplified
})
// Wait for all conditions
err := group.Wait(wait.DefaultOptions().WithTimeout(30 * time.Second))
if err != nil {
log.Printf("Not all services ready: %v", err)
}
}
Output:
type InterfaceInfo ¶
InterfaceInfo contains information about a network interface
type LinearStrategy ¶
type LinearStrategy struct {
// contains filtered or unexported fields
}
LinearStrategy increases wait time linearly
func NewLinearStrategy ¶
func NewLinearStrategy(initial, increment, max time.Duration) *LinearStrategy
NewLinearStrategy creates a new linear wait strategy
type NetworkInfo ¶
type NetworkInfo struct {
Interfaces []InterfaceInfo
HasIPv4 bool
HasIPv6 bool
HasGlobal bool
}
NetworkInfo contains information about network interfaces
func ForNetworkWithInfo ¶
func ForNetworkWithInfo(opts ...*Options) (*NetworkInfo, error)
ForNetworkWithInfo waits for network and returns network information
type Options ¶
type Options struct {
MaxRetries int
Timeout time.Duration
Strategy Strategy
Context context.Context
}
Options configures wait behavior
func (*Options) WithContext ¶
WithContext sets the context for cancellation
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/presbrey/pkg/wait"
)
func main() {
// Use context for cancellation
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Start a goroutine that cancels after some condition
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
err := wait.Until(
func() (bool, error) {
// Some long-running check
time.Sleep(1 * time.Second)
return false, nil
},
wait.DefaultOptions().WithContext(ctx),
)
if err == wait.ErrCanceled {
fmt.Println("Operation was canceled")
}
}
Output:
func (*Options) WithMaxRetries ¶
WithMaxRetries sets the maximum number of retries
func (*Options) WithStrategy ¶
WithStrategy sets the wait strategy