- handler panic log includes the stack trace and no longer the sender number - error and exception frames from the service are logged at Warn level - Listen looks the account up again after a connection loss (re-link) - document that received but unhandled messages are lost at shutdown Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
158 lines
4.3 KiB
Go
158 lines
4.3 KiB
Go
package signalbot
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"runtime/debug"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
)
|
|
|
|
// Handler processes one incoming message. Handlers are called one at a
|
|
// time, in arrival order; start a goroutine to process messages in parallel.
|
|
type Handler func(ctx context.Context, m Message)
|
|
|
|
// Listen receives incoming text messages and calls h for each of them,
|
|
// until ctx is done, in which case it returns ctx.Err().
|
|
//
|
|
// Connection losses and an unavailable service are retried with an
|
|
// exponential backoff (1s to 30s), logged at Warn level. Listen returns
|
|
// early only for errors that retrying cannot fix: ErrNotLinked,
|
|
// ErrMultipleAccounts, ErrNotJSONRPC, or a 4xx answer (*APIError) to the websocket
|
|
// handshake. A panic in h is recovered and logged at Error level, with its
|
|
// stack trace. Errors reported by the service on the websocket are logged
|
|
// at Warn level.
|
|
//
|
|
// Messages are acknowledged to Signal as soon as the service receives
|
|
// them. Messages already received but not yet handled when ctx is done
|
|
// are lost.
|
|
//
|
|
// Only one Listen per account should run at a time.
|
|
func (c *Client) Listen(ctx context.Context, h Handler) error {
|
|
backoff := c.minBackoff
|
|
for {
|
|
connected, err := c.listenOnce(ctx, h)
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
if permanent(err) {
|
|
return err
|
|
}
|
|
if connected {
|
|
backoff = c.minBackoff
|
|
}
|
|
// The account may have been re-linked meanwhile: look it up again.
|
|
c.forgetAccount()
|
|
c.log.Warn("signalbot: receive connection lost, retrying", "error", err, "retry_in", backoff)
|
|
t := time.NewTimer(backoff)
|
|
select {
|
|
case <-ctx.Done():
|
|
t.Stop()
|
|
return ctx.Err()
|
|
case <-t.C:
|
|
}
|
|
backoff = min(backoff*2, c.maxBackoff)
|
|
}
|
|
}
|
|
|
|
// permanent reports whether retrying cannot fix err.
|
|
func permanent(err error) bool {
|
|
if errors.Is(err, ErrNotLinked) || errors.Is(err, ErrMultipleAccounts) || errors.Is(err, ErrNotJSONRPC) {
|
|
return true
|
|
}
|
|
var apiErr *APIError
|
|
return errors.As(err, &apiErr) &&
|
|
apiErr.StatusCode >= 400 && apiErr.StatusCode < 500 &&
|
|
apiErr.StatusCode != http.StatusTooManyRequests
|
|
}
|
|
|
|
// listenOnce runs one websocket connection until it fails or ctx is done.
|
|
// connected reports whether the handshake succeeded.
|
|
func (c *Client) listenOnce(ctx context.Context, h Handler) (connected bool, err error) {
|
|
acct, err := c.account(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
conn, resp, err := websocket.Dial(ctx, c.wsURL(acct), &websocket.DialOptions{HTTPClient: c.http})
|
|
if err != nil {
|
|
if resp != nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
|
// A plain HTTP answer: the service runs in normal/native mode,
|
|
// where each GET consumes messages. Retrying would lose them.
|
|
return false, ErrNotJSONRPC
|
|
}
|
|
if resp != nil && resp.StatusCode >= 300 {
|
|
return false, &APIError{StatusCode: resp.StatusCode, Message: err.Error()}
|
|
}
|
|
return false, unavailable(err)
|
|
}
|
|
defer conn.CloseNow()
|
|
conn.SetReadLimit(1 << 20)
|
|
|
|
// Read continuously in a separate goroutine so that pings are answered
|
|
// while a handler is busy.
|
|
rctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
frames := make(chan []byte, 64)
|
|
var readErr error
|
|
go func() {
|
|
defer close(frames)
|
|
for {
|
|
_, data, err := conn.Read(rctx)
|
|
if err != nil {
|
|
readErr = err
|
|
return
|
|
}
|
|
select {
|
|
case frames <- data:
|
|
case <-rctx.Done():
|
|
readErr = rctx.Err()
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
for data := range frames {
|
|
if msg, ok := serviceError(data); ok {
|
|
c.log.Warn("signalbot: receive error from service", "error", msg)
|
|
continue
|
|
}
|
|
m, ok := parseEnvelope(data, acct)
|
|
if !ok {
|
|
continue
|
|
}
|
|
m.client = c
|
|
c.handle(ctx, h, m)
|
|
if ctx.Err() != nil {
|
|
return true, ctx.Err()
|
|
}
|
|
}
|
|
// frames is closed: readErr was set before close and is safe to read.
|
|
return true, fmt.Errorf("signalbot: receive: %w", readErr)
|
|
}
|
|
|
|
func (c *Client) handle(ctx context.Context, h Handler, m Message) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
c.log.Error("signalbot: handler panic", "panic", r, "group", m.GroupID, "stack", string(debug.Stack()))
|
|
}
|
|
}()
|
|
h(ctx, m)
|
|
}
|
|
|
|
// wsURL is the receive websocket URL for acct.
|
|
func (c *Client) wsURL(acct Account) string {
|
|
u := *c.base
|
|
switch u.Scheme {
|
|
case "https":
|
|
u.Scheme = "wss"
|
|
default:
|
|
u.Scheme = "ws"
|
|
}
|
|
u.Path += "/v1/receive/" + acct.id()
|
|
u.RawPath = ""
|
|
return u.String()
|
|
}
|