relay: introduce ConnectContext for better control over network latency

A websocket dial may hand for an unreasonably long time and a nostr client
has no control over this when trying to connect to a relay.

Go started introducing context in networking since 2014 -
see https://go.dev/blog/context - and by now many net functions have
XxxContext equivalent, such as DialContext.

Example usage of the change introduced by this commit:

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    r, err := nostr.RelayConnectContext(ctx, "ws://relay.example.org")

The code above makes RelayConnectContext last at most 3 sec, returning
an error if a connection cannot be established in the given time.
This helps whenever a tight control over connection latency is required,
such as distributed systems.

The change is backwards-compatible except the case where RelayPool.Add
sent an error over the returned channel without actually closing said
channel. I believe it was a bug.
This commit is contained in:
alex
2022-12-17 19:39:10 +01:00
committed by fiatjaf
parent ad71e083d8
commit c327f622f3
5 changed files with 138 additions and 33 deletions

1
go.mod
View File

@@ -11,6 +11,7 @@ require (
github.com/tyler-smith/go-bip39 v1.1.0
github.com/valyala/fastjson v1.6.3
golang.org/x/exp v0.0.0-20221106115401-f9659909a136
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3
)
require (