MCPcopy Index your code
hub / github.com/coder/agentapi / WaitFor

Function WaitFor

lib/util/util.go:28–87  ·  view source on GitHub ↗

WaitFor waits for a condition to be true or the timeout to expire. It will wait for the condition to be true with exponential backoff. A single sleep timer is reused across iterations via Reset so that mock-clock tests always have a pending timer to advance.

(ctx context.Context, timeout WaitTimeout, condition func() (bool, error))

Source from the content-addressed store, hash-verified

26// A single sleep timer is reused across iterations via Reset so that
27// mock-clock tests always have a pending timer to advance.
28func WaitFor(ctx context.Context, timeout WaitTimeout, condition func() (bool, error)) error {
29 clock := timeout.Clock
30 if clock == nil {
31 clock = quartz.NewReal()
32 }
33
34 minInterval := timeout.MinInterval
35 maxInterval := timeout.MaxInterval
36 timeoutDuration := timeout.Timeout
37 if minInterval == 0 {
38 minInterval = 10 * time.Millisecond
39 }
40 if maxInterval == 0 {
41 maxInterval = 500 * time.Millisecond
42 }
43 if timeoutDuration == 0 {
44 timeoutDuration = 10 * time.Second
45 }
46 if minInterval > maxInterval {
47 return xerrors.Errorf("minInterval is greater than maxInterval")
48 }
49
50 timeoutTimer := clock.NewTimer(timeoutDuration)
51 defer timeoutTimer.Stop()
52
53 interval := minInterval
54 sleepTimer := clock.NewTimer(interval)
55 defer sleepTimer.Stop()
56
57 waitForTimer := timeout.InitialWait
58 for {
59 if waitForTimer {
60 select {
61 case <-sleepTimer.C:
62 case <-ctx.Done():
63 return ctx.Err()
64 case <-timeoutTimer.C:
65 return WaitTimedOut
66 }
67 }
68 waitForTimer = true
69
70 ok, err := condition()
71 if err != nil {
72 return err
73 }
74 if ok {
75 return nil
76 }
77
78 interval = min(interval*2, maxInterval)
79 if !sleepTimer.Stop() {
80 select {
81 case <-sleepTimer.C:
82 default:
83 }
84 }
85 sleepTimer.Reset(interval)

Callers 1

writeStabilizeMethod · 0.92

Calls 1

StopMethod · 0.45

Tested by

no test coverage detected