Documentation
¶
Overview ¶
Package wsutil holds small shared helpers for the provider WebSocket clients. The streaming STT and TTS providers each dial a vendor WebSocket the same way; this package factors out that dial boilerplate so a provider only writes the request and reads the vendor's message frames.
Every call that waits on the network (dialing, reading, writing, pinging, closing) lets go of the session's loop while it waits (see package tasks), so a provider calling it from a task of its session holds no other part of the session up. Called from a goroutine that is not a task, or from inside tasks.Await, it simply blocks.
A read is safe to give up on: when the context of a Read ends, only that wait ends. The connection stays open and the message the read was waiting for goes to the next Read. A service can therefore cancel the task that receives its messages and then go on talking on the connection, to send a last message or close it with the closing handshake.
Index ¶
- Constants
- Variables
- func Permanent(err error) bool
- type Conn
- func (c *Conn) Close(code websocket.StatusCode, reason string) (err error)
- func (c *Conn) CloseNow() error
- func (c *Conn) Closed() bool
- func (c *Conn) Ping(ctx context.Context) (err error)
- func (c *Conn) Read(ctx context.Context) (typ websocket.MessageType, p []byte, err error)
- func (c *Conn) ResponseHeader() http.Header
- func (c *Conn) SetCloseTimeout(d time.Duration)
- func (c *Conn) SetSendTimeout(d time.Duration)
- func (c *Conn) Write(ctx context.Context, typ websocket.MessageType, p []byte) (err error)
- type HandshakeError
Constants ¶
const ( DefaultPingInterval = 20 * time.Second DefaultPingTimeout = 20 * time.Second )
DefaultPingInterval is how often a dialed connection pings its peer, and DefaultPingTimeout how long it waits for the answer before dropping the connection. The pings keep an idle connection alive through a NAT or proxy that expires quiet flows, and a peer that stopped answering is found within about the two together rather than when TCP gives up, minutes later.
const DefaultCloseTimeout = 2 * time.Second
DefaultCloseTimeout bounds how long a close waits for the peer to answer. Disconnecting happens while a service handles the EndFrame, before the frame carries on downstream, so a close the peer never acknowledges holds up the end of the pipeline for that long. The library waits 5s, which is long enough to be felt once several WebSocket services tear down one after another.
const DefaultReadLimit = 16 << 20
DefaultReadLimit bounds a single inbound WebSocket message. It guards against a server that streams without end, not against large messages: a TTS provider generating a long sentence in one go sends base64 audio well past a megabyte, and a limit tight enough to cut that off fails the synthesis mid-reply.
const DefaultSendTimeout = 5 * time.Second
DefaultSendTimeout is the default ceiling on a single send. A send only waits once the peer has stopped taking data and the write buffers are full, so on a working connection it returns at once.
Variables ¶
var ErrSendTimeout = errors.New("wsutil: websocket send did not complete")
ErrSendTimeout is wrapped by the error of a send that outlasted the send timeout, which dropped the connection.
Functions ¶
Types ¶
type Conn ¶ added in v0.1.0
Conn is a WebSocket connection whose closing handshake and sends are bounded, so a peer that never answers, or stops reading, cannot hold up a teardown or the service writing to it. A dialed one also pings its peer, and drops the connection when the peer stops answering. Everything else is the underlying connection's.
func Adopt ¶ added in v0.1.0
Adopt wraps a connection that was accepted rather than dialed, so a server side gets the same bounded close a dialed one has. It applies readLimit when that is positive.
The caller owns the connection either way: Accept hands it over, and this only takes over how it is closed.
func Dial ¶
Dial opens a WebSocket to url with the given headers, closes the handshake response body, and applies readLimit when it is positive. The caller owns the returned connection and must Close it. A handshake the server refused comes back as a *HandshakeError carrying the status.
The connection pings the peer every DefaultPingInterval while it is being read, and drops itself when a ping goes unanswered for DefaultPingTimeout.
A dial that fails reports the host it tried and why, but never the query: a provider may carry its credential there, and the error ends up in the log.
func DialSubprotocols ¶ added in v0.7.0
func DialSubprotocols( ctx context.Context, url string, header http.Header, readLimit int64, subprotocols []string, ) (*Conn, error)
DialSubprotocols is Dial offering subprotocols in the handshake, most preferred first, for a provider that selects its message format by subprotocol. The one the server selected is the connection's Subprotocol, empty when it selected none: a caller that needs one checks it.
func (*Conn) Close ¶ added in v0.1.0
func (c *Conn) Close(code websocket.StatusCode, reason string) (err error)
Close closes the connection, giving up on the closing handshake once the timeout passes rather than waiting the library's own deadline out. The peer not answering is logged, since a teardown that quietly cost the full timeout would otherwise go unnoticed; the library drops the connection behind us.
A Read waiting meanwhile returns once the connection is closed, with the peer's close when it answered. A message read before the close and not yet taken by a Read is dropped, as every message the peer sends during the closing handshake is.
It lets go of the session's loop while it waits for the peer. Closing a connection that is already closed succeeds.
func (*Conn) CloseNow ¶ added in v0.5.0
CloseNow closes the connection without the closing handshake. A Read waiting meanwhile returns the error of reading a closed connection.
func (*Conn) Closed ¶ added in v1.1.0
Closed reports whether the connection is no longer open: it was closed, or reading it failed (the peer closed it, or it dropped). A connection that has not been read yet is open until it is closed: the peer closing it is only seen by reading.
func (*Conn) Ping ¶ added in v1.1.0
Ping sends a ping and waits for the pong, letting go of the session's loop while it waits. A pong is only taken in while a read is in progress.
func (*Conn) Read ¶ added in v0.5.0
Read reads the next message, letting go of the session's loop while it waits.
It is safe to give up on, as a read from a connection that is read in the background is: when ctx ends, Read returns ctx's error and the connection stays open. The message it was waiting for is returned by the next Read, and messages come back in the order they arrived, none lost and none twice. So a service may cancel the task that receives its messages and then still send a last message on the connection or close it with the closing handshake. A caller that wants the connection gone when it stops reading closes it.
The connection is read by one goroutine, started by the first Read, which reads one message ahead of the Reads at most. Once reading the connection fails (the peer closed it, it was closed, it dropped), every Read returns that error.
func (*Conn) ResponseHeader ¶ added in v1.2.0
ResponseHeader is the header of the response that accepted the handshake, where a provider may name the session it opened. It is nil for a connection that was not dialed.
func (*Conn) SetCloseTimeout ¶ added in v0.1.0
SetCloseTimeout sets how long Close waits for the peer to answer. Raise it for a peer that needs longer to close gracefully; zero sends the close and does not wait at all, for a peer that never acknowledges it. A negative value is ignored.
func (*Conn) SetSendTimeout ¶ added in v0.3.0
SetSendTimeout sets how long one Write may wait on a peer that has stopped reading before the connection is dropped. Zero or less waits indefinitely.
func (*Conn) Write ¶ added in v0.3.0
Write sends a message, dropping the connection if the send stalls.
The library puts no bound of its own on a send: once the peer stops reading and the write buffer fills, the send waits until the connection drops, and TCP can take many minutes to notice, holding up the service writing and every processor after it. The send is bounded by the send timeout instead. A send that outlasts it closes the connection, as the library does whenever a write's context ends, so the send fails the way any dropped connection does and the service's reconnect handling takes over.
It lets go of the session's loop while it sends. Messages still go out in the order Write was called, as they would on a connection a single goroutine writes to.
type HandshakeError ¶ added in v0.1.0
type HandshakeError struct {
// StatusCode is the HTTP status the server refused the handshake with.
StatusCode int
// Header is the header of the response that refused the handshake, where a
// provider may explain the refusal.
Header http.Header
// Body is the start of the body of the response that refused the
// handshake, up to a kilobyte, where a provider may explain the refusal
// too. It is nil when the response had none.
Body []byte
// Err is the underlying dial failure.
Err error
}
HandshakeError is returned when the server refused the WebSocket handshake. It carries the status it refused with, so a caller can tell a request the server will go on refusing (a rejected key, a model the account cannot use) from a failure that may not repeat.
func (*HandshakeError) Error ¶ added in v0.1.0
func (e *HandshakeError) Error() string
Error implements error.
func (*HandshakeError) HTTPStatusCode ¶ added in v0.1.0
func (e *HandshakeError) HTTPStatusCode() int
HTTPStatusCode implements the interface the shared error classification looks for, so a refused handshake is classified by the status the server refused with: rejected credentials from a server that is merely unwell.
func (*HandshakeError) Permanent ¶ added in v0.1.0
func (e *HandshakeError) Permanent() bool
Permanent reports whether the server refused the request itself, rather than failing in a way that might not repeat. Retrying a refusal only spends the time before the caller learns of it.
func (*HandshakeError) Unwrap ¶ added in v0.1.0
func (e *HandshakeError) Unwrap() error
Unwrap returns the underlying dial failure.