-
Notifications
You must be signed in to change notification settings - Fork 11
/
wait.go
104 lines (86 loc) · 2.3 KB
/
wait.go
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
package replicate
import (
"context"
"time"
)
const (
defaultPollingInterval = 1 * time.Second
)
type waitOptions struct {
interval time.Duration
}
// WaitOption is a function that modifies an options struct.
type WaitOption func(*waitOptions) error
// WithPollingInterval sets the interval between attempts.
func WithPollingInterval(interval time.Duration) WaitOption {
return func(o *waitOptions) error {
o.interval = interval
return nil
}
}
// Wait for a prediction to finish.
//
// This function blocks until the prediction has finished, or the context is canceled.
// If the prediction has already finished, the function returns immediately.
// If polling interval is less than or equal to zero, an error is returned.
func (r *Client) Wait(ctx context.Context, prediction *Prediction, opts ...WaitOption) error {
predChan, errChan := r.WaitAsync(ctx, prediction, opts...)
go func() {
for range predChan { //nolint:all
// Drain the channel
}
}()
return <-errChan
}
// WaitAsync returns a channel that receives the prediction as it progresses.
//
// The channel is closed when the prediction has finished,
// or the context is canceled.
// If the prediction has already finished, the channel is closed immediately.
// If polling interval is less than or equal to zero,
// an error is sent to the error channel.
func (r *Client) WaitAsync(ctx context.Context, prediction *Prediction, opts ...WaitOption) (<-chan *Prediction, <-chan error) {
predChan := make(chan *Prediction)
errChan := make(chan error)
options := &waitOptions{
interval: defaultPollingInterval,
}
for _, option := range opts {
err := option(options)
if err != nil {
errChan <- err
close(predChan)
close(errChan)
return predChan, errChan
}
}
go func() {
defer close(predChan)
defer close(errChan)
ticker := time.NewTicker(options.interval)
defer ticker.Stop()
id := prediction.ID
attempts := 0
for {
select {
case <-ticker.C:
updatedPrediction, err := r.GetPrediction(ctx, id)
if err != nil {
errChan <- err
return
}
*prediction = *updatedPrediction
predChan <- updatedPrediction
if prediction.Status.Terminated() {
errChan <- nil
return
}
attempts++
case <-ctx.Done():
errChan <- ctx.Err()
return
}
}
}()
return predChan, errChan
}