Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http/longpoll: Fix bug and simplify implementation #404

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 10 additions & 32 deletions http/longpoll/longpoll.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,51 +42,29 @@ func Until(ctx context.Context, d time.Duration, fn LongPollFunc) (ok bool, err
// budget is communicated via the provided context. This is a defence measure to not have accidental
// long running routines. If no duration is given (0) the long poll will have exactly one execution.
func (c Config) LongPollUntil(ctx context.Context, d time.Duration, fn LongPollFunc) (ok bool, err error) {
until := time.Now()
var cancel context.CancelFunc

if d != 0 {
if d < c.MinWaitTime { // guard lower bound
until = until.Add(c.MinWaitTime)
} else if d > c.MaxWaitTime { // guard upper bound
until = until.Add(c.MaxWaitTime)
} else {
until = until.Add(d)
if d < c.MinWaitTime {
d = c.MinWaitTime
} else if d > c.MaxWaitTime {
d = c.MaxWaitTime
}
}

fnCtx, cancel := context.WithDeadline(ctx, until)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, d)
defer cancel()
}

loop:
for {
ok, err = fn(fnCtx)
if err != nil {
ok, err = fn(ctx)
if ok || err != nil || d == 0 {
return
}

// fn returns true, break the loop
if ok {
break
}

// no long polling
if d <= 0 {
break
}

// long pooling desired?
if !time.Now().Add(c.RetryTime).Before(until) {
break
}

select {
// handle context cancelation
case <-ctx.Done():
return false, ctx.Err()
case <-time.After(c.RetryTime):
continue loop
}
}

return
}
12 changes: 9 additions & 3 deletions http/longpoll/longpoll_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@ func TestLongPollUntilBounds(t *testing.T) {

func TestLongPollUntilNoTimeout(t *testing.T) {
called := 0
ok, err := Until(context.Background(), 0, func(context.Context) (bool, error) {
ok, err := Until(context.Background(), 0, func(ctx context.Context) (bool, error) {
f := func(ctx context.Context) {
assert.NoError(t, ctx.Err())
}

f(ctx)

called++
return false, nil
})
Expand Down Expand Up @@ -73,8 +79,8 @@ func TestLongPollUntilTimeout(t *testing.T) {
return false, nil
})
assert.False(t, ok)
assert.NoError(t, err)
assert.Equal(t, 2, called)
assert.Error(t, err)
assert.GreaterOrEqual(t, called, 2)
}

func TestLongPollUntilTimeoutWithContext(t *testing.T) {
Expand Down
Loading