wait

package
v0.0.0-...-535534a Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT 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.

README

Wait Library for Go

A comprehensive Go library for waiting on various conditions with configurable retry strategies, timeouts, and backoff algorithms.

Features

  • Flexible Wait Conditions: Wait for custom conditions, network connectivity, HTTP endpoints, files, processes, and more
  • Multiple Retry Strategies: Fixed, linear, exponential backoff, Fibonacci, decorrelated jitter, and custom strategies
  • Context Support: Full context.Context support for cancellation and timeouts
  • Composable: Chain multiple conditions with All() and Any() functions
  • Network Utilities: Comprehensive network waiting functions (TCP, UDP, HTTP, DNS)
  • Error Handling: Detailed error reporting with timeout, retry limit, and cancellation errors

Installation

go get github.com/yourusername/wait

Quick Start

package main

import (
    "log"
    "time"
    "github.com/yourusername/wait"
)

func main() {
    // Wait for network connectivity
    err := wait.ForNetwork()
    if err != nil {
        log.Fatal(err)
    }

    // Wait for a TCP service with exponential backoff
    err = wait.ForTCP("localhost:8080",
        wait.DefaultOptions().
            WithTimeout(30 * time.Second).
            WithStrategy(wait.NewExponentialBackoffStrategy(
                1*time.Second,  // initial
                2.0,            // multiplier
                10*time.Second, // max
                true,           // jitter
            )))
    if err != nil {
        log.Fatal(err)
    }
}

Core Functions

Basic Wait Functions
  • Until(condition, opts) - Wait until condition returns true
  • UntilWithResult(condition, opts) - Wait and return a result
  • Poll(fn, opts) - Poll a function until it succeeds
  • All(conditions, opts) - Wait for all conditions
  • Any(conditions, opts) - Wait for any condition
Network Wait Functions
  • ForNetwork() - Wait for global network connectivity
  • ForLocalNetwork() - Wait for local network connectivity
  • ForTCP(address) - Wait for TCP connection
  • ForUDP(address) - Wait for UDP connection
  • ForHTTP(url) - Wait for HTTP 200 response
  • ForHTTPStatus(url, statuses) - Wait for specific HTTP status
  • ForHTTPSHealthy(url) - Wait for any 2xx response
  • ForDNS(hostname) - Wait for DNS resolution
  • ForPort(port) - Wait for localhost port
  • ForMultiplePorts(ports) - Wait for multiple ports
  • ForAnyPort(ports) - Wait for any port
File System Wait Functions
  • ForFile(path) - Wait for file existence
  • ForFileContent(path, minSize) - Wait for file with content
  • ForFileRemoval(path) - Wait for file removal
  • ForDirectory(path) - Wait for directory
Process Wait Functions
  • ForProcess(pid) - Wait for process existence
  • ForProcessExit(pid) - Wait for process to exit
  • ForCommand(name, args) - Wait for command success

Retry Strategies

Fixed Strategy

Wait for a fixed duration between attempts.

strategy := wait.NewFixedStrategy(2 * time.Second)
Linear Strategy

Increase wait time linearly.

strategy := wait.NewLinearStrategy(
    1*time.Second,        // initial
    500*time.Millisecond, // increment
    10*time.Second,       // max
)
Exponential Backoff Strategy

Exponentially increase wait time with optional jitter.

strategy := wait.NewExponentialBackoffStrategy(
    100*time.Millisecond, // initial
    2.0,                  // multiplier
    30*time.Second,       // max
    true,                 // add jitter
)
Fibonacci Strategy

Use Fibonacci sequence for wait times.

strategy := wait.NewFibonacciStrategy(
    100*time.Millisecond, // unit
    10*time.Second,       // max
)
Decorrelated Jitter Strategy

AWS-style decorrelated jitter for distributed systems.

strategy := wait.NewDecorrelatedJitterStrategy(
    100*time.Millisecond, // base
    10*time.Second,       // max
)
Custom Strategy

Define custom wait durations.

durations := []time.Duration{
    100*time.Millisecond,
    500*time.Millisecond,
    1*time.Second,
    5*time.Second,
}
strategy := wait.NewCustomStrategy(durations, false) // don't repeat

Options

Configure wait behavior with options:

opts := wait.DefaultOptions().
    WithMaxRetries(10).
    WithTimeout(30 * time.Second).
    WithStrategy(strategy).
    WithContext(ctx)

Advanced Usage

Wait Groups
group := wait.NewGroup()

group.Add(func() (bool, error) {
    // Check database
    return isDatabaseReady(), nil
})

group.Add(func() (bool, error) {
    // Check cache
    return isCacheReady(), nil
})

err := group.Wait(wait.DefaultOptions().WithTimeout(30 * time.Second))
Custom Conditions
// Wait with custom condition
err := wait.Until(func() (bool, error) {
    value, err := checkSomething()
    if err != nil {
        return false, err // Return error to stop waiting
    }
    return value > threshold, nil
}, opts)

// Wait and get result
result, err := wait.UntilWithResult(func() (interface{}, bool, error) {
    data, err := fetchData()
    if err != nil {
        return nil, false, nil // Retry on error
    }
    if data.IsReady {
        return data, true, nil // Success
    }
    return nil, false, nil // Not ready, keep waiting
}, opts)
Context Cancellation
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Cancel from another goroutine
go func() {
    <-someSignal
    cancel()
}()

err := wait.ForNetwork(
    wait.DefaultOptions().WithContext(ctx),
)

if err == wait.ErrCanceled {
    // Operation was canceled
}

Error Types

  • ErrTimeout - Timeout exceeded
  • ErrMaxRetriesReached - Maximum retries reached
  • ErrCanceled - Operation canceled via context

Best Practices

  1. Always set timeouts: Prevent infinite waiting
  2. Use appropriate strategies: Exponential backoff for network, fixed for local resources
  3. Add jitter: Prevent thundering herd in distributed systems
  4. Handle errors: Check for timeout vs cancellation vs retry exhaustion
  5. Use context: Enable graceful shutdowns and cancellation

Examples

See example_test.go for comprehensive examples of all features.

License

MIT License - see LICENSE file for details

Documentation

Overview

Package wait provides utilities for waiting on various conditions with configurable strategies

Index

Examples

Constants

This section is empty.

Variables

View Source
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)
	}
}

func ForAnyPort

func ForAnyPort(ports []int, opts ...*Options) (int, error)

ForAnyPort waits until any of the specified ports is open on localhost

func ForCommand

func ForCommand(name string, args []string, opts ...*Options) error

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 ForDNS

func ForDNS(hostname string, opts ...*Options) error

ForDNS waits until a hostname can be resolved

func ForDirectory

func ForDirectory(path string, opts ...*Options) error

ForDirectory waits until a directory exists

func ForDuration

func ForDuration(duration time.Duration) error

ForDuration waits for a specific duration from now

func ForEnvironmentVariable

func ForEnvironmentVariable(key string, opts ...*Options) error

ForEnvironmentVariable waits until an environment variable is set

func ForEnvironmentVariableValue

func ForEnvironmentVariableValue(key, expectedValue string, opts ...*Options) error

ForEnvironmentVariableValue waits until an environment variable has a specific value

func ForFile

func ForFile(path string, opts ...*Options) error

ForFile waits until a file exists

func ForFileContent

func ForFileContent(path string, minSize int64, opts ...*Options) error

ForFileContent waits until a file exists and has content

func ForFileRemoval

func ForFileRemoval(path string, opts ...*Options) error

ForFileRemoval waits until a file is removed

func ForHTTP

func ForHTTP(url string, opts ...*Options) error

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)
	}
}

func ForHTTPSHealthy

func ForHTTPSHealthy(url string, opts ...*Options) error

ForHTTPSHealthy waits until an HTTP endpoint returns any 2xx status

func ForHTTPStatus

func ForHTTPStatus(url string, expectedStatuses []int, opts ...*Options) error

ForHTTPStatus waits until an HTTP endpoint returns one of the expected status codes

func ForLocalNetwork

func ForLocalNetwork(opts ...*Options) error

ForLocalNetwork waits for any network connectivity (including local)

func ForMultiplePorts

func ForMultiplePorts(ports []int, opts ...*Options) error

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")
	}
}

func ForNetwork

func ForNetwork(opts ...*Options) error

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")
	}
}

func ForPort

func ForPort(port int, opts ...*Options) error

ForPort waits until a port is open on localhost

func ForProcess

func ForProcess(pid int, opts ...*Options) error

ForProcess waits until a process with the given PID exists

func ForProcessExit

func ForProcessExit(pid int, opts ...*Options) error

ForProcessExit waits until a process exits

func ForTCP

func ForTCP(address string, opts ...*Options) error

ForTCP waits until a TCP connection can be established

func ForTime

func ForTime(target time.Time, opts ...*Options) error

ForTime waits until a specific time is reached

func ForUDP

func ForUDP(address string, opts ...*Options) error

ForUDP waits until a UDP connection can be established

func Forever

func Forever(fn func() error, interval time.Duration) error

Forever executes a function forever until it succeeds or context is canceled

func Poll

func Poll(fn func() error, opts ...*Options) error

Poll executes a function repeatedly until it succeeds or timeout

func Retry

func Retry(fn func() error, maxRetries int) error

Retry executes a function with retries

func RetryWithBackoff

func RetryWithBackoff(fn func() error, initial time.Duration, maxRetries int) error

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)
	}
}

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")
}

func UntilWithResult

func UntilWithResult(condition ConditionWithResultFunc, opts ...*Options) (interface{}, error)

UntilWithResult waits until condition is met and returns the result

Types

type ConditionFunc

type ConditionFunc func() (bool, error)

ConditionFunc represents a function that returns true when a condition is met

type ConditionWithResultFunc

type ConditionWithResultFunc func() (interface{}, bool, error)

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)
	}
}

func NewCustomStrategy

func NewCustomStrategy(durations []time.Duration, repeat bool) *CustomStrategy

NewCustomStrategy creates a new custom wait strategy

func (*CustomStrategy) Next

func (s *CustomStrategy) Next() (time.Duration, bool)

Next returns the next wait duration

func (*CustomStrategy) Reset

func (s *CustomStrategy) Reset()

Reset resets the 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

Example
package main

import (
	"log"
	"time"

	"github.com/presbrey/pkg/wait"
)

func main() {
	// Use AWS-style decorrelated jitter for better distributed systems behavior
	strategy := wait.NewDecorrelatedJitterStrategy(
		100*time.Millisecond, // base
		10*time.Second,       // max
	)

	err := wait.ForTCP(
		"database:5432",
		wait.DefaultOptions().
			WithStrategy(strategy).
			WithMaxRetries(20),
	)

	if err != nil {
		log.Printf("Database connection failed: %v", err)
	}
}

func (*DecorrelatedJitterStrategy) Next

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

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

func (*FibonacciStrategy) Next

func (s *FibonacciStrategy) Next() (time.Duration, bool)

Next returns the next wait duration

func (*FibonacciStrategy) Reset

func (s *FibonacciStrategy) Reset()

Reset resets the 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

func (*FixedStrategy) Next

func (s *FixedStrategy) Next() (time.Duration, bool)

Next returns the next wait duration

func (*FixedStrategy) Reset

func (s *FixedStrategy) Reset()

Reset resets the 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)
	}
}

func NewGroup

func NewGroup() *Group

NewGroup creates a new wait group

func (*Group) Add

func (g *Group) Add(condition ConditionFunc)

Add adds a condition to the group

func (*Group) AddFunc

func (g *Group) AddFunc(fn func() error)

AddFunc adds a function-based condition to the group

func (*Group) Errors

func (g *Group) Errors() []error

Errors returns any errors from the last Wait operation

func (*Group) Wait

func (g *Group) Wait(opts ...*Options) error

Wait waits for all conditions in the group

func (*Group) WaitAny

func (g *Group) WaitAny(opts ...*Options) (int, error)

WaitAny waits for any condition in the group

type InterfaceInfo

type InterfaceInfo struct {
	Name       string
	Addresses  []net.Addr
	IsUp       bool
	IsLoopback bool
}

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

func (*LinearStrategy) Next

func (s *LinearStrategy) Next() (time.Duration, bool)

Next returns the next wait duration

func (*LinearStrategy) Reset

func (s *LinearStrategy) Reset()

Reset resets the 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 DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default wait options

func (*Options) WithContext

func (o *Options) WithContext(ctx context.Context) *Options

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")
	}
}

func (*Options) WithMaxRetries

func (o *Options) WithMaxRetries(n int) *Options

WithMaxRetries sets the maximum number of retries

func (*Options) WithStrategy

func (o *Options) WithStrategy(s Strategy) *Options

WithStrategy sets the wait strategy

func (*Options) WithTimeout

func (o *Options) WithTimeout(d time.Duration) *Options

WithTimeout sets the overall timeout

type Strategy

type Strategy interface {
	Next() (time.Duration, bool)
	Reset()
}

Strategy defines the interface for wait strategies

Jump to

Keyboard shortcuts

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