1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2026-10-29 13:42:30 +00:00
Files
go-inbucket/pkg/rest/socketv1_controller.go
T
James Hillyerd 47239c08eb refactor(rest): deduplicate WebSocket monitor controllers (#622)
The black-box monitor tests showed socketv1_controller.go and
socketv2_controller.go were near-identical: same constants (identical
values), upgrader, read/write pumps, Close, and handler bodies, differing
only in the event payload shape and v1 dropping deletions.

Extract the shared machinery into socket_controller.go:

- msgListener[T] generic listener with toStored/toDeleted payload
  transforms; a nil toDeleted preserves the socketv1 behavior of ignoring
  deletions
- socketReadPump / socketWritePump free functions (WriteJSON is
  payload-type agnostic)
- serveMonitor shared handler body (upgrade, gauge tracking, listener
  registration, pump wiring)

The version files shrink to their listener constructors and the four
exported handlers, whose signatures are unchanged.  v1 payloads are now
shaped at enqueue time rather than write time; the JSON on the wire is
identical, pinned by the commit-1 tests, which pass unmodified.

Adds direct unit tests for the extracted listener logic: watches()
filtering, Receive/Delete filtering + payload shaping, nil-toDeleted
deletion dropping, and sequential Close idempotency.
2026-09-17 18:43:34 -07:00

39 lines
1.3 KiB
Go

package rest
import (
"net/http"
"github.com/inbucket/inbucket/v3/pkg/extension/event"
"github.com/inbucket/inbucket/v3/pkg/msghub"
"github.com/inbucket/inbucket/v3/pkg/rest/model"
"github.com/inbucket/inbucket/v3/pkg/server/web"
)
// newMsgListenerV1 creates a v1 API listener which relays message headers only; deletions are
// ignored by the socketv1 API.
func newMsgListenerV1(hub *msghub.Hub, mailbox string) *msgListener[*model.JSONMessageHeaderV1] {
return newMsgListener(hub, mailbox,
func(msg event.MessageMetadata) *model.JSONMessageHeaderV1 {
return metadataToHeader(&msg)
},
nil)
}
// MonitorAllMessagesV1 is a web handler which upgrades the connection to a websocket and notifies
// the client of all messages received.
func MonitorAllMessagesV1(
w http.ResponseWriter, req *http.Request, ctx *web.Context) error {
return serveMonitor(w, req, ctx.MsgHub, "", newMsgListenerV1)
}
// MonitorMailboxMessagesV1 is a web handler which upgrades the connection to a websocket and
// notifies the client of messages received by a particular mailbox.
func MonitorMailboxMessagesV1(
w http.ResponseWriter, req *http.Request, ctx *web.Context) error {
name, err := ctx.Manager.MailboxForAddress(ctx.Vars["name"])
if err != nil {
return err
}
return serveMonitor(w, req, ctx.MsgHub, name, newMsgListenerV1)
}