feat: distribute new local posts to followers via websocket

This commit is contained in:
Sam 2023-10-15 21:34:13 +02:00
parent 5c6da51234
commit 74614ed0e3
6 changed files with 107 additions and 75 deletions

View file

@ -5,10 +5,20 @@ import "encoding/json"
type EventType int8
const (
// Sent when an error occurs
// Payload: {code:int, message:string}
EventTypeError EventType = 1
EventTypePost EventType = 2
// Sent when echoing back received messages
// Payload: <received message>
EventTypeEcho EventType = 2
// Sent on a new post being created
// Payload: <post object>
EventTypePost EventType = 3
EventTypeSubscribe EventType = 126
// Receive events
// Subscribe to a new event
EventTypeSubscribe EventType = 126
// Unsubscribe from an event
EventTypeUnsubscribe EventType = 127
)
@ -16,6 +26,8 @@ func (et EventType) Valid() bool {
switch et {
case EventTypeError:
return true
case EventTypeEcho:
return true
case EventTypePost:
return true
case EventTypeSubscribe:

View file

@ -13,6 +13,12 @@ type SocketHolder struct {
mu sync.Mutex
}
func NewSocketHolder() *SocketHolder {
return &SocketHolder{
sockets: make(map[ulid.ULID]*userSockets),
}
}
func (sh *SocketHolder) Send(acctID ulid.ULID, et EventType, data any) {
userSockets := sh.SocketsFor(acctID)
@ -22,7 +28,7 @@ func (sh *SocketHolder) Send(acctID ulid.ULID, et EventType, data any) {
userSockets.mu.Unlock()
for _, s := range sockets {
if s.willAcceptEvent(et) {
if s.WillAcceptEvent(et) {
// the socket might block for a bit, so spin this off into a separate goroutine
go func(s *Socket) {
s.ch <- Event{Type: et, Data: data}
@ -71,7 +77,7 @@ type Socket struct {
mu sync.RWMutex
}
func (s *Socket) willAcceptEvent(mt EventType) bool {
func (s *Socket) WillAcceptEvent(mt EventType) bool {
if mt == EventTypeError {
return true
}
@ -109,6 +115,8 @@ func NewSocket(ctx context.Context, cancel context.CancelFunc) *Socket {
ctx: ctx,
cancel: cancel,
ch: make(chan Event),
types: make(map[EventType]struct{}),
types: map[EventType]struct{}{
EventTypeEcho: {},
},
}
}