MVP: IRC envelope format, long-polling, per-client queues, SPA rewrite

Major changes:
- Consolidated schema into single migration with IRC envelope format
- Messages table stores command/from/to/body(JSON)/meta(JSON) per spec
- Per-client delivery queues (client_queues table) with fan-out
- In-memory broker for long-poll notifications (no busy polling)
- GET /messages supports ?after=<queue_id>&timeout=15 long-polling
- All commands (JOIN/PART/NICK/TOPIC/QUIT/PING) broadcast events
- Channels are ephemeral (deleted when last member leaves)
- PRIVMSG to nicks (DMs) fan out to both sender and recipient
- SPA rewritten in vanilla JS (no build step needed):
  - Long-poll via recursive fetch (not setInterval)
  - IRC envelope parsing with system message display
  - /nick, /join, /part, /msg, /quit commands
  - Unread indicators on inactive tabs
  - DM tabs from user list clicks
- Removed unused models package (was for UUID-based schema)
- Removed conflicting UUID-based db methods
- Increased HTTP write timeout to 60s for long-poll support
This commit is contained in:
clawbot
2026-02-10 18:09:10 -08:00
parent df2217a38b
commit 1f54b281fd
20 changed files with 974 additions and 1829 deletions

View File

@@ -6,8 +6,8 @@ import (
"net/http"
"strconv"
"strings"
"time"
"git.eeqj.de/sneak/chat/internal/db"
"github.com/go-chi/chi"
)
@@ -30,6 +30,48 @@ func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, s
return uid, nick, true
}
// fanOut stores a message and enqueues it to all specified user IDs, then notifies them.
func (s *Handlers) fanOut(ctx *http.Request, command, from, to string, body json.RawMessage, userIDs []int64) error {
dbID, _, err := s.params.Database.InsertMessage(ctx.Context(), command, from, to, body, nil)
if err != nil {
return err
}
for _, uid := range userIDs {
if err := s.params.Database.EnqueueMessage(ctx.Context(), uid, dbID); err != nil {
s.log.Error("enqueue failed", "error", err, "user_id", uid)
}
s.broker.Notify(uid)
}
return nil
}
// fanOutRaw stores and fans out, returning the message DB ID.
func (s *Handlers) fanOutDirect(ctx *http.Request, command, from, to string, body json.RawMessage, userIDs []int64) (int64, string, error) {
dbID, msgUUID, err := s.params.Database.InsertMessage(ctx.Context(), command, from, to, body, nil)
if err != nil {
return 0, "", err
}
for _, uid := range userIDs {
if err := s.params.Database.EnqueueMessage(ctx.Context(), uid, dbID); err != nil {
s.log.Error("enqueue failed", "error", err, "user_id", uid)
}
s.broker.Notify(uid)
}
return dbID, msgUUID, nil
}
// getChannelMembers gets all member IDs for a channel by name.
func (s *Handlers) getChannelMemberIDs(r *http.Request, channelName string) (int64, []int64, error) {
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", channelName).Scan(&chID)
if err != nil {
return 0, nil, err
}
ids, err := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
return chID, ids, err
}
// HandleCreateSession creates a new user session and returns the auth token.
func (s *Handlers) HandleCreateSession() http.HandlerFunc {
type request struct {
@@ -67,11 +109,6 @@ func (s *Handlers) HandleCreateSession() http.HandlerFunc {
// HandleState returns the current user's info and joined channels.
func (s *Handlers) HandleState() http.HandlerFunc {
type response struct {
ID int64 `json:"id"`
Nick string `json:"nick"`
Channels []db.ChannelInfo `json:"channels"`
}
return func(w http.ResponseWriter, r *http.Request) {
uid, nick, ok := s.requireAuth(w, r)
if !ok {
@@ -83,7 +120,11 @@ func (s *Handlers) HandleState() http.HandlerFunc {
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, &response{ID: uid, Nick: nick, Channels: channels}, http.StatusOK)
s.respondJSON(w, r, map[string]any{
"id": uid,
"nick": nick,
"channels": channels,
}, http.StatusOK)
}
}
@@ -129,8 +170,7 @@ func (s *Handlers) HandleChannelMembers() http.HandlerFunc {
}
}
// HandleGetMessages returns all new messages (channel + DM) for the user via long-polling.
// This is the single unified message stream — replaces separate channel/DM/poll endpoints.
// HandleGetMessages returns messages via long-polling from the client's queue.
func (s *Handlers) HandleGetMessages() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid, _, ok := s.requireAuth(w, r)
@@ -138,25 +178,65 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc {
return
}
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit)
timeout, _ := strconv.Atoi(r.URL.Query().Get("timeout"))
if timeout <= 0 {
timeout = 0
}
if timeout > 30 {
timeout = 30
}
// First check for existing messages.
msgs, lastQID, err := s.params.Database.PollMessages(r.Context(), uid, afterID, 100)
if err != nil {
s.log.Error("get messages failed", "error", err)
s.log.Error("poll messages failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
if len(msgs) > 0 || timeout == 0 {
s.respondJSON(w, r, map[string]any{
"messages": msgs,
"last_id": lastQID,
}, http.StatusOK)
return
}
// Long-poll: wait for notification or timeout.
waitCh := s.broker.Wait(uid)
timer := time.NewTimer(time.Duration(timeout) * time.Second)
defer timer.Stop()
select {
case <-waitCh:
case <-timer.C:
case <-r.Context().Done():
s.broker.Remove(uid, waitCh)
return
}
s.broker.Remove(uid, waitCh)
// Check again after notification.
msgs, lastQID, err = s.params.Database.PollMessages(r.Context(), uid, afterID, 100)
if err != nil {
s.log.Error("poll messages failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]any{
"messages": msgs,
"last_id": lastQID,
}, http.StatusOK)
}
}
// HandleSendCommand handles all C2S commands via POST /messages.
// The "command" field dispatches to the appropriate logic.
func (s *Handlers) HandleSendCommand() http.HandlerFunc {
type request struct {
Command string `json:"command"`
To string `json:"to"`
Params []string `json:"params,omitempty"`
Body interface{} `json:"body,omitempty"`
Command string `json:"command"`
To string `json:"to"`
Body json.RawMessage `json:"body,omitempty"`
Meta json.RawMessage `json:"meta,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
uid, nick, ok := s.requireAuth(w, r)
@@ -171,22 +251,15 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
req.Command = strings.ToUpper(strings.TrimSpace(req.Command))
req.To = strings.TrimSpace(req.To)
// Helper to extract body as string lines.
bodyLines := func() []string {
switch v := req.Body.(type) {
case []interface{}:
lines := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok {
lines = append(lines, s)
}
}
return lines
case []string:
return v
default:
if req.Body == nil {
return nil
}
var lines []string
if err := json.Unmarshal(req.Body, &lines); err != nil {
return nil
}
return lines
}
switch req.Command {
@@ -200,38 +273,39 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest)
return
}
content := strings.Join(lines, "\n")
if strings.HasPrefix(req.To, "#") {
// Channel message
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", req.To).Scan(&chID)
// Channel message — fan out to all channel members.
_, memberIDs, err := s.getChannelMemberIDs(r, req.To)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, content)
_, msgUUID, err := s.fanOutDirect(r, req.Command, nick, req.To, req.Body, memberIDs)
if err != nil {
s.log.Error("send message failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
s.respondJSON(w, r, map[string]string{"id": msgUUID, "status": "sent"}, http.StatusCreated)
} else {
// DM
targetID, err := s.params.Database.GetUserByNick(r.Context(), req.To)
// DM — fan out to recipient + sender.
targetUID, err := s.params.Database.GetUserByNick(r.Context(), req.To)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
return
}
msgID, err := s.params.Database.SendDM(r.Context(), uid, targetID, content)
recipients := []int64{targetUID}
if targetUID != uid {
recipients = append(recipients, uid) // echo to sender
}
_, msgUUID, err := s.fanOutDirect(r, req.Command, nick, req.To, req.Body, recipients)
if err != nil {
s.log.Error("send dm failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
s.respondJSON(w, r, map[string]string{"id": msgUUID, "status": "sent"}, http.StatusCreated)
}
case "JOIN":
@@ -254,6 +328,9 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
// Broadcast JOIN to all channel members (including the joiner).
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
_ = s.fanOut(r, "JOIN", nick, channel, nil, memberIDs)
s.respondJSON(w, r, map[string]string{"status": "joined", "channel": channel}, http.StatusOK)
case "PART":
@@ -272,11 +349,17 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
// Broadcast PART before removing the member.
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
_ = s.fanOut(r, "PART", nick, channel, req.Body, memberIDs)
if err := s.params.Database.PartChannel(r.Context(), chID, uid); err != nil {
s.log.Error("part channel failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
// Delete channel if empty (ephemeral).
_ = s.params.Database.DeleteChannelIfEmpty(r.Context(), chID)
s.respondJSON(w, r, map[string]string{"status": "parted", "channel": channel}, http.StatusOK)
case "NICK":
@@ -299,6 +382,25 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
// Broadcast NICK to all channels the user is in.
channels, _ := s.params.Database.GetAllChannelMembershipsForUser(r.Context(), uid)
notified := map[int64]bool{uid: true}
body, _ := json.Marshal([]string{newNick})
// Notify self.
dbID, _, _ := s.params.Database.InsertMessage(r.Context(), "NICK", nick, "", json.RawMessage(body), nil)
_ = s.params.Database.EnqueueMessage(r.Context(), uid, dbID)
s.broker.Notify(uid)
for _, ch := range channels {
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), ch.ID)
for _, mid := range memberIDs {
if !notified[mid] {
notified[mid] = true
_ = s.params.Database.EnqueueMessage(r.Context(), mid, dbID)
s.broker.Notify(mid)
}
}
}
s.respondJSON(w, r, map[string]string{"status": "ok", "nick": newNick}, http.StatusOK)
case "TOPIC":
@@ -316,27 +418,52 @@ func (s *Handlers) HandleSendCommand() http.HandlerFunc {
if !strings.HasPrefix(channel, "#") {
channel = "#" + channel
}
if err := s.params.Database.SetTopic(r.Context(), channel, uid, topic); err != nil {
if err := s.params.Database.SetTopic(r.Context(), channel, topic); err != nil {
s.log.Error("set topic failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
// Broadcast TOPIC to channel members.
_, memberIDs, _ := s.getChannelMemberIDs(r, channel)
_ = s.fanOut(r, "TOPIC", nick, channel, req.Body, memberIDs)
s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK)
case "QUIT":
// Broadcast QUIT to all channels, then remove user.
channels, _ := s.params.Database.GetAllChannelMembershipsForUser(r.Context(), uid)
notified := map[int64]bool{}
var dbID int64
if len(channels) > 0 {
dbID, _, _ = s.params.Database.InsertMessage(r.Context(), "QUIT", nick, "", req.Body, nil)
}
for _, ch := range channels {
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), ch.ID)
for _, mid := range memberIDs {
if mid != uid && !notified[mid] {
notified[mid] = true
_ = s.params.Database.EnqueueMessage(r.Context(), mid, dbID)
s.broker.Notify(mid)
}
}
_ = s.params.Database.PartChannel(r.Context(), ch.ID, uid)
_ = s.params.Database.DeleteChannelIfEmpty(r.Context(), ch.ID)
}
_ = s.params.Database.DeleteUser(r.Context(), uid)
s.respondJSON(w, r, map[string]string{"status": "quit"}, http.StatusOK)
case "PING":
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
default:
_ = nick // suppress unused warning
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest)
}
}
}
// HandleGetHistory returns message history for a specific target (channel or DM).
// HandleGetHistory returns message history for a specific target.
func (s *Handlers) HandleGetHistory() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid, _, ok := s.requireAuth(w, r)
_, _, ok := s.requireAuth(w, r)
if !ok {
return
}
@@ -350,42 +477,17 @@ func (s *Handlers) HandleGetHistory() http.HandlerFunc {
if limit <= 0 {
limit = 50
}
if strings.HasPrefix(target, "#") {
// Channel history
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", target).Scan(&chID)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
msgs, err := s.params.Database.GetMessagesBefore(r.Context(), chID, beforeID, limit)
if err != nil {
s.log.Error("get history failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
} else {
// DM history
targetID, err := s.params.Database.GetUserByNick(r.Context(), target)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
return
}
msgs, err := s.params.Database.GetDMsBefore(r.Context(), uid, targetID, beforeID, limit)
if err != nil {
s.log.Error("get dm history failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
msgs, err := s.params.Database.GetHistory(r.Context(), target, beforeID, limit)
if err != nil {
s.log.Error("get history failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
}
}
// HandleServerInfo returns server metadata (MOTD, name).
// HandleServerInfo returns server metadata.
func (s *Handlers) HandleServerInfo() http.HandlerFunc {
type response struct {
Name string `json:"name"`