fix: panic stack without sender, log service error frames, refresh account on reconnect
- 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>
This commit is contained in:
1 parent
788dd0b968
commit
b54aab1534
5 files changed
+162
-3
No files matched your search
@@ -57,7 +57,17 @@ err = client.Listen(ctx, func(ctx context.Context, m signalbot.Message) {
|
|||||||
`Listen` reconnects automatically (backoff 1s → 30s) and calls the handler
|
`Listen` reconnects automatically (backoff 1s → 30s) and calls the handler
|
||||||
for one message at a time, in arrival order. It ignores everything that is
|
for one message at a time, in arrival order. It ignores everything that is
|
||||||
not a text message (receipts, typing, reactions, attachments, messages sent
|
not a text message (receipts, typing, reactions, attachments, messages sent
|
||||||
from the bot's own phone). A panic in the handler is recovered and logged.
|
from the bot's own phone). A panic in the handler is recovered and logged
|
||||||
|
with its stack trace; errors reported by the service (e.g. a message that
|
||||||
|
could not be decrypted) are logged at Warn level.
|
||||||
|
|
||||||
|
Messages are acknowledged to Signal as soon as the service receives them:
|
||||||
|
those already received but not yet handled when the context is cancelled
|
||||||
|
are lost. Keep handlers short, or hand work off to your own queue.
|
||||||
|
|
||||||
|
The linked account is looked up once and cached. `Listen` looks it up again
|
||||||
|
after each connection loss; for `Send` and `Groups`, create a new `Client`
|
||||||
|
after linking a different account.
|
||||||
|
|
||||||
Options: `WithNumber` (choose an account when several are linked),
|
Options: `WithNumber` (choose an account when several are linked),
|
||||||
`WithHTTPClient`, `WithLogger` (`*slog.Logger`, default `slog.Default()`).
|
`WithHTTPClient`, `WithLogger` (`*slog.Logger`, default `slog.Default()`).
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Client talks to a signal-cli-rest-api service. It is safe for concurrent use.
|
// Client talks to a signal-cli-rest-api service. It is safe for concurrent use.
|
||||||
|
//
|
||||||
|
// The linked account is looked up on first use and cached. Listen looks it
|
||||||
|
// up again after each connection loss; create a new Client to make Send and
|
||||||
|
// Groups use a newly linked account.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
base *url.URL
|
base *url.URL
|
||||||
number string
|
number string
|
||||||
@@ -177,6 +181,13 @@ func (c *Client) Accounts(ctx context.Context) ([]Account, error) {
|
|||||||
return accts, nil
|
return accts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// forgetAccount drops the cached account so the next call looks it up again.
|
||||||
|
func (c *Client) forgetAccount() {
|
||||||
|
c.mu.Lock()
|
||||||
|
c.acct = nil
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
// account resolves the account to use and caches it after the first success.
|
// account resolves the account to use and caches it after the first success.
|
||||||
// The lock is not held during the lookup, so each caller's ctx applies; a
|
// The lock is not held during the lookup, so each caller's ctx applies; a
|
||||||
// concurrent duplicate lookup is harmless.
|
// concurrent duplicate lookup is harmless.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/coder/websocket"
|
"github.com/coder/websocket"
|
||||||
@@ -21,7 +22,13 @@ type Handler func(ctx context.Context, m Message)
|
|||||||
// exponential backoff (1s to 30s), logged at Warn level. Listen returns
|
// exponential backoff (1s to 30s), logged at Warn level. Listen returns
|
||||||
// early only for errors that retrying cannot fix: ErrNotLinked,
|
// early only for errors that retrying cannot fix: ErrNotLinked,
|
||||||
// ErrMultipleAccounts, ErrNotJSONRPC, or a 4xx answer (*APIError) to the websocket
|
// ErrMultipleAccounts, ErrNotJSONRPC, or a 4xx answer (*APIError) to the websocket
|
||||||
// handshake. A panic in h is recovered and logged at Error level.
|
// 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.
|
// Only one Listen per account should run at a time.
|
||||||
func (c *Client) Listen(ctx context.Context, h Handler) error {
|
func (c *Client) Listen(ctx context.Context, h Handler) error {
|
||||||
@@ -37,6 +44,8 @@ func (c *Client) Listen(ctx context.Context, h Handler) error {
|
|||||||
if connected {
|
if connected {
|
||||||
backoff = c.minBackoff
|
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)
|
c.log.Warn("signalbot: receive connection lost, retrying", "error", err, "retry_in", backoff)
|
||||||
t := time.NewTimer(backoff)
|
t := time.NewTimer(backoff)
|
||||||
select {
|
select {
|
||||||
@@ -106,6 +115,10 @@ func (c *Client) listenOnce(ctx context.Context, h Handler) (connected bool, err
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
for data := range frames {
|
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)
|
m, ok := parseEnvelope(data, acct)
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@@ -123,7 +136,7 @@ func (c *Client) listenOnce(ctx context.Context, h Handler) (connected bool, err
|
|||||||
func (c *Client) handle(ctx context.Context, h Handler, m Message) {
|
func (c *Client) handle(ctx context.Context, h Handler, m Message) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
c.log.Error("signalbot: handler panic", "panic", r, "from", m.From, "group", m.GroupID)
|
c.log.Error("signalbot: handler panic", "panic", r, "group", m.GroupID, "stack", string(debug.Stack()))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
h(ctx, m)
|
h(ctx, m)
|
||||||
|
|||||||
@@ -291,3 +291,92 @@ func TestListenServiceNotInJSONRPCMode(t *testing.T) {
|
|||||||
t.Fatalf("handshakes = %d, want 1 (no retry)", n)
|
t.Fatalf("handshakes = %d, want 1 (no retry)", n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestListenHandlerPanicLogsStackNotSender(t *testing.T) {
|
||||||
|
f := newFakeAPI(t)
|
||||||
|
f.accounts(`[{"number":"+331"}]`)
|
||||||
|
f.receive(t, func(_ int, conn *websocket.Conn) {
|
||||||
|
write(t, conn, textEnvelope("boom"))
|
||||||
|
waitClosed(conn)
|
||||||
|
})
|
||||||
|
var logs bytes.Buffer
|
||||||
|
var mu sync.Mutex
|
||||||
|
logger := slog.New(slog.NewTextHandler(&lockedWriter{w: &logs, mu: &mu}, nil))
|
||||||
|
c := fastClient(t, f.URL, WithLogger(logger))
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = c.Listen(ctx, func(context.Context, Message) {
|
||||||
|
defer cancel()
|
||||||
|
panic("handler exploded")
|
||||||
|
})
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
out := logs.String()
|
||||||
|
if !strings.Contains(out, "stack=") || !strings.Contains(out, "listen_test.go") {
|
||||||
|
t.Errorf("panic log has no stack trace: %q", out)
|
||||||
|
}
|
||||||
|
if strings.Contains(out, "+33600000001") {
|
||||||
|
t.Errorf("panic log contains the sender number: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListenLogsServiceErrorFrames(t *testing.T) {
|
||||||
|
f := newFakeAPI(t)
|
||||||
|
f.accounts(`[{"number":"+331"}]`)
|
||||||
|
f.receive(t, func(_ int, conn *websocket.Conn) {
|
||||||
|
write(t, conn,
|
||||||
|
`{"error":"receive failed: boom-1"}`,
|
||||||
|
`{"error":{"code":-1,"message":"boom-2"}}`,
|
||||||
|
`{"envelope":{"sourceNumber":"+33600000001","timestamp":1},"account":"+331","exception":{"message":"boom-3","type":"ProtocolInvalidMessageException"}}`,
|
||||||
|
textEnvelope("after"))
|
||||||
|
waitClosed(conn)
|
||||||
|
})
|
||||||
|
var logs bytes.Buffer
|
||||||
|
var mu sync.Mutex
|
||||||
|
logger := slog.New(slog.NewTextHandler(&lockedWriter{w: &logs, mu: &mu}, nil))
|
||||||
|
got := collect(t, fastClient(t, f.URL, WithLogger(logger)), 1)
|
||||||
|
if len(got) != 1 || got[0] != "after" {
|
||||||
|
t.Fatalf("got %v, want [after]", got)
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
for _, want := range []string{"boom-1", "boom-2", "boom-3"} {
|
||||||
|
if !strings.Contains(logs.String(), want) {
|
||||||
|
t.Errorf("logs miss %q: %q", want, logs.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(logs.String(), "after") {
|
||||||
|
t.Errorf("message text logged: %q", logs.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListenRefreshesAccountAfterConnectionLoss(t *testing.T) {
|
||||||
|
f := newFakeAPI(t)
|
||||||
|
var mu sync.Mutex
|
||||||
|
number := "+331"
|
||||||
|
f.mux.HandleFunc("GET /v1/accounts", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
writeJSON(w, 200, []map[string]string{{"number": number}})
|
||||||
|
})
|
||||||
|
f.mux.HandleFunc("GET /v1/receive/{acct}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
conn, err := websocket.Accept(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.CloseNow()
|
||||||
|
if r.PathValue("acct") == "+331" {
|
||||||
|
mu.Lock()
|
||||||
|
number = "+332" // re-linked while connected
|
||||||
|
mu.Unlock()
|
||||||
|
return // drop the connection
|
||||||
|
}
|
||||||
|
write(t, conn, strings.Replace(textEnvelope("relinked"), `"+331"`, `"+332"`, 1))
|
||||||
|
waitClosed(conn)
|
||||||
|
})
|
||||||
|
got := collect(t, fastClient(t, f.URL), 1)
|
||||||
|
if len(got) != 1 || got[0] != "relinked" {
|
||||||
|
t.Fatalf("got %v, want [relinked]", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -82,3 +82,39 @@ func parseEnvelope(data []byte, self Account) (Message, bool) {
|
|||||||
}
|
}
|
||||||
return m, true
|
return m, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// serviceError extracts an error reported by the service on the receive
|
||||||
|
// websocket: a top-level "error" (string or {"message"}), or a signal-cli
|
||||||
|
// "exception" (e.g. a message that could not be decrypted).
|
||||||
|
func serviceError(data []byte) (string, bool) {
|
||||||
|
var f struct {
|
||||||
|
Error json.RawMessage `json:"error"`
|
||||||
|
Exception *struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
} `json:"exception"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(data, &f) != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if len(f.Error) > 0 && string(f.Error) != "null" {
|
||||||
|
var s string
|
||||||
|
if json.Unmarshal(f.Error, &s) == nil {
|
||||||
|
return s, true
|
||||||
|
}
|
||||||
|
var o struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(f.Error, &o) == nil && o.Message != "" {
|
||||||
|
return o.Message, true
|
||||||
|
}
|
||||||
|
return string(f.Error), true
|
||||||
|
}
|
||||||
|
if f.Exception != nil {
|
||||||
|
if f.Exception.Type != "" {
|
||||||
|
return f.Exception.Type + ": " + f.Exception.Message, true
|
||||||
|
}
|
||||||
|
return f.Exception.Message, true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
Reference in new issue
Block a user