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

feat: add RequestContext to PubSubConn #603

Merged
merged 1 commit into from Mar 23, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions redis/pubsub.go
Expand Up @@ -15,6 +15,7 @@
package redis

import (
"context"
"errors"
"time"
)
Expand Down Expand Up @@ -116,6 +117,13 @@ func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{} {
return c.receiveInternal(ReceiveWithTimeout(c.Conn, timeout))
}

// ReceiveContext is like Receive, but it allows termination of the receive
// via a Context. If the call returns due to closure of the context's Done
// channel the underlying Conn will have been closed.
func (c PubSubConn) ReceiveContext(ctx context.Context) interface{} {
return c.receiveInternal(ReceiveContext(c.Conn, ctx))
}

func (c PubSubConn) receiveInternal(replyArg interface{}, errArg error) interface{} {
reply, err := Values(replyArg, errArg)
if err != nil {
Expand Down
24 changes: 24 additions & 0 deletions redis/pubsub_test.go
Expand Up @@ -15,6 +15,8 @@
package redis_test

import (
"context"
"errors"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -74,3 +76,25 @@ func TestPushed(t *testing.T) {
t.Errorf("recv /w timeout got %v, want %v", got, want)
}
}

func TestPubSubReceiveContext(t *testing.T) {
sc, err := redis.DialDefaultServer()
if err != nil {
t.Fatalf("error connection to database, %v", err)
}
defer sc.Close()

c := redis.PubSubConn{Conn: sc}

require.NoError(t, c.Subscribe("c1"))
expectPushed(t, c, "Subscribe(c1)", redis.Subscription{Kind: "subscribe", Channel: "c1", Count: 1})

ctx, cancel := context.WithCancel(context.Background())
cancel()
got := c.ReceiveContext(ctx)
if err, ok := got.(error); !ok {
t.Errorf("recv w/canceled expected Canceled got non-error type %T", got)
} else if !errors.Is(err, context.Canceled) {
t.Errorf("recv w/canceled expected Canceled got %v", err)
}
}