~samwhited/xmpp

20430f4caf0a54d8418c35f18f2323aa9bae4a42 — Sam Whited 5 years ago 2ad79bf
Don't run lookup methods if ctx is already done
2 files changed, 31 insertions(+), 4 deletions(-)

M lookup.go
M lookup_test.go
M lookup.go => lookup.go +13 -1
@@ 109,6 109,11 @@ func lookupEndpoint(ctx context.Context, client *http.Client, addr *jid.JID, con

func lookupDNS(ctx context.Context, name, conntype string) (urls []string, err error) {
	validateConnTypeOrPanic(conntype)
	select {
	case <-ctx.Done():
		return urls, ctx.Err()
	default:
	}

	txts, err := net.LookupTXT(name)
	if err != nil {


@@ 117,8 122,10 @@ func lookupDNS(ctx context.Context, name, conntype string) (urls []string, err e

	var s string
	for _, txt := range txts {
		if _, ok := <-ctx.Done(); ok {
		select {
		case <-ctx.Done():
			return urls, ctx.Err()
		default:
		}
		switch conntype {
		case "ws":


@@ 139,6 146,11 @@ func lookupDNS(ctx context.Context, name, conntype string) (urls []string, err e

func lookupHostMeta(ctx context.Context, client *http.Client, name, conntype string) (urls []string, err error) {
	validateConnTypeOrPanic(conntype)
	select {
	case <-ctx.Done():
		return urls, ctx.Err()
	default:
	}

	url, err := url.Parse(name)
	if err != nil {

M lookup_test.go => lookup_test.go +18 -3
@@ 6,6 6,8 @@ package xmpp

import (
	"testing"

	"golang.org/x/net/context"
)

// If an invalid connection type is looked up, we should panic.


@@ 15,7 17,7 @@ func TestLookupEndpointPanicsOnInvalidType(t *testing.T) {
			t.Error("lookupEndpoint should panic if an invalid conntype is specified.")
		}
	}()
	lookupEndpoint(nil, nil, nil, "wssorbashorsomething")
	lookupEndpoint(context.Background(), nil, nil, "wssorbashorsomething")
}

// If an invalid connection type is looked up, we should panic.


@@ 25,7 27,7 @@ func TestLookupDNSPanicsOnInvalidType(t *testing.T) {
			t.Error("lookupDNS should panic if an invalid conntype is specified.")
		}
	}()
	lookupDNS(nil, "name", "wssorbashorsomething")
	lookupDNS(context.Background(), "name", "wssorbashorsomething")
}

// If an invalid connection type is looked up, we should panic.


@@ 35,5 37,18 @@ func TestLookupHostMetaPanicsOnInvalidType(t *testing.T) {
			t.Error("lookupHostMeta should panic if an invalid conntype is specified.")
		}
	}()
	lookupHostMeta(nil, nil, "name", "wssorbashorsomething")
	lookupHostMeta(context.Background(), nil, "name", "wssorbashorsomething")
}

// The lookup methods should not run if the context is canceled.
func TestLookupMethodsDoNotRunIfContextIsDone(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	if _, err := lookupDNS(ctx, "name", "ws"); err != context.Canceled {
		t.Error("lookupDNS should not run if the context is canceled.")
	}
	if _, err := lookupHostMeta(ctx, nil, "name", "ws"); err != context.Canceled {
		t.Error("lookupHostMeta should not run if the context is canceled.")
	}
}