-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaitfor.go
More file actions
193 lines (165 loc) · 5.94 KB
/
waitfor.go
File metadata and controls
193 lines (165 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Package waitfor provides utilities for testing and waiting for resource availability
// before executing programs. It supports various resource types through a plugin system
// and offers configurable retry mechanisms with exponential backoff.
//
// This package is designed for scenarios where applications need to wait for dependencies
// like databases, web services, files, or other external resources to be available
// before starting up.
//
// Basic usage:
//
// runner := waitfor.New(
// postgres.Use(),
// http.Use(),
// )
//
// err := runner.Test(ctx, []string{
// "postgres://user:pass@localhost:5432/db",
// "http://localhost:8080/health",
// })
//
// The package supports custom resource types through the ResourceConfig interface
// and provides flexible configuration options for retry behavior and timeouts.
package waitfor
import (
"bytes"
"context"
"fmt"
"os/exec"
"sync"
"github.com/cenkalti/backoff/v5"
)
type (
// Program represents a command to execute along with the resources
// that must be available before execution. It encapsulates the executable
// path, command arguments, and dependency resource URLs.
Program struct {
Executable string // The path or name of the executable to run
Args []string // Command line arguments for the executable
Resources []string // List of resource URLs that must be available
}
// Runner is the main component responsible for testing resource availability
// and executing programs. It maintains a registry of resource types and
// provides methods to test resources and run programs conditionally.
Runner struct {
registry *Registry
}
)
// New creates a new Runner instance with the specified resource configurations.
// Each ResourceConfig defines how to handle specific resource URL schemes.
// Multiple configurations can be provided to support different resource types.
//
// Example:
//
// runner := waitfor.New(
// postgres.Use(),
// http.Use(),
// fs.Use(),
// )
func New(configurators ...ResourceConfig) *Runner {
r := new(Runner)
r.registry = newRegistry(configurators)
return r
}
// Resources returns the resource registry associated with this Runner.
// The registry can be used to manually register additional resource types
// or query available resource schemes.
func (r *Runner) Resources() *Registry {
return r.registry
}
// Run tests resource availability and executes the given program if all resources are ready.
// It first validates that all resources specified in program.Resources are available,
// then executes the program's command if the tests pass. Returns the combined output
// from the executed command or an error if resources are not ready or execution fails.
//
// The setters parameter allows customization of retry behavior, timeouts, and intervals.
//
// Example:
//
// program := waitfor.Program{
// Executable: "myapp",
// Args: []string{"--config", "prod.yaml"},
// Resources: []string{"postgres://localhost:5432/db", "http://api:8080/health"},
// }
// output, err := runner.Run(ctx, program, waitfor.WithAttempts(10))
func (r *Runner) Run(ctx context.Context, program Program, setters ...Option) ([]byte, error) {
err := r.Test(ctx, program.Resources, setters...)
if err != nil {
return nil, err
}
cmd := exec.Command(program.Executable, program.Args...)
return cmd.CombinedOutput()
}
// Test validates that all specified resources are available and responding correctly.
// It tests each resource concurrently using their respective Test implementations
// with configurable retry logic and exponential backoff. Returns an error if any
// resource fails its availability test after all retry attempts are exhausted.
//
// The setters parameter allows customization of retry behavior including:
// - Initial retry interval (WithInterval)
// - Maximum retry interval (WithMaxInterval)
// - Number of retry attempts (WithAttempts)
// - Multiplier for exponential backoff (WithMultiplier)
// - Randomization factor for backoff intervals (WithRandomizationFactor)
//
// Example:
//
// resources := []string{
// "postgres://user:pass@localhost:5432/db",
// "http://localhost:8080/health",
// "file://./config.json",
// }
// err := runner.Test(ctx, resources, waitfor.WithAttempts(5), waitfor.WithInterval(2))
func (r *Runner) Test(ctx context.Context, resources []string, setters ...Option) error {
opts := newOptions(setters)
var buff bytes.Buffer
output := r.testAllInternal(ctx, resources, *opts)
for err := range output {
if err != nil {
buff.WriteString(err.Error() + ";")
}
}
if buff.Len() != 0 {
return fmt.Errorf("%s: %s", ErrWait, buff.String())
}
return nil
}
// testAllInternal concurrently tests all provided resources and returns a channel
// of errors. Each resource is tested in its own goroutine with the specified options.
// The channel is closed when all tests complete.
func (r *Runner) testAllInternal(ctx context.Context, resources []string, opts options) <-chan error {
var wg sync.WaitGroup
wg.Add(len(resources))
output := make(chan error, len(resources))
for _, resource := range resources {
resource := resource
go func() {
defer wg.Done()
output <- r.testInternal(ctx, resource, opts)
}()
}
go func() {
wg.Wait()
close(output)
}()
return output
}
// testInternal tests a single resource with retry logic using exponential backoff.
// It resolves the resource from the registry and applies the configured retry
// strategy until the resource test passes or max attempts are reached.
func (r *Runner) testInternal(ctx context.Context, resource string, opts options) error {
rsc, err := r.registry.Resolve(resource)
if err != nil {
return err
}
b := backoff.NewExponentialBackOff()
b.InitialInterval = opts.interval
b.MaxInterval = opts.maxInterval
b.Multiplier = opts.multiplier
b.RandomizationFactor = opts.randomizationFactor
_, err = backoff.Retry(ctx, func() (bool, error) {
// The return value doesn't matter to us
return false, rsc.Test(ctx)
}, backoff.WithMaxTries(uint(opts.attempts)))
return err
}