Phase 1 MVP: gateway, CRUD handlers, frontend components
Backend: - WebSocket gateway (hub, client, events) with fanout broadcast - Server CRUD handlers (create, list, get, update, delete) - Channel CRUD handlers (create, list, get, update, delete) - Message CRUD handlers (list with cursor pagination, create, update, delete) - cmd/migrate standalone migration CLI (up/down) - cmd/server wired to all handlers + WebSocket + static file serving Frontend: - Zustand stores: auth, server, channel, message, websocket - API client with fetch wrapper - Terminal-styled components: Layout, LoginForm, ChatArea, ChannelList, ServerBar, MemberList - React Router with login and main routes - Gruvbox dark palette throughout Ops: - Docker Compose with app service (multi-stage build) - Caddyfile with WebSocket upgrade support - Makefile for common tasks
This commit is contained in:
@@ -0,0 +1,318 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Handler holds the database dependency for channel CRUD operations.
|
||||
type Handler struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// NewHandler creates a new channel Handler.
|
||||
func NewHandler(db *sql.DB) *Handler {
|
||||
return &Handler{db: db}
|
||||
}
|
||||
|
||||
// RegisterRoutes registers channel routes on the given chi.Router.
|
||||
// Expects to be mounted under /servers/{serverID}/channels.
|
||||
func (h *Handler) RegisterRoutes(r chi.Router) {
|
||||
r.Post("/", h.Create)
|
||||
r.Get("/", h.List)
|
||||
r.Get("/{channelID}", h.Get)
|
||||
r.Patch("/{channelID}", h.Update)
|
||||
r.Delete("/{channelID}", h.Delete)
|
||||
}
|
||||
|
||||
// Channel is the JSON representation of a channel.
|
||||
type Channel struct {
|
||||
ID string `json:"id"`
|
||||
ServerID string `json:"server_id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Category string `json:"category"`
|
||||
Position int `json:"position"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type createChannelRequest struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Category string `json:"category"`
|
||||
Position *int `json:"position,omitempty"`
|
||||
}
|
||||
|
||||
type updateChannelRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Type *string `json:"type,omitempty"`
|
||||
Category *string `json:"category,omitempty"`
|
||||
Position *int `json:"position,omitempty"`
|
||||
}
|
||||
|
||||
// Create handles POST / — creates a new channel in a server.
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
serverID := chi.URLParam(r, "serverID")
|
||||
if _, err := uuid.Parse(serverID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid server id")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify membership
|
||||
if !h.isMember(r, userID, serverID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
var req createChannelRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
if req.Name == "" {
|
||||
writeError(w, http.StatusBadRequest, "name is required")
|
||||
return
|
||||
}
|
||||
if req.Type == "" {
|
||||
req.Type = "text"
|
||||
}
|
||||
if req.Type != "text" && req.Type != "voice" {
|
||||
writeError(w, http.StatusBadRequest, "type must be text or voice")
|
||||
return
|
||||
}
|
||||
if req.Category == "" {
|
||||
req.Category = "General"
|
||||
}
|
||||
|
||||
position := 0
|
||||
if req.Position != nil {
|
||||
position = *req.Position
|
||||
}
|
||||
|
||||
var channelID string
|
||||
err := h.db.QueryRowContext(r.Context(), `
|
||||
INSERT INTO channels (server_id, name, type, category, position)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id
|
||||
`, serverID, req.Name, req.Type, req.Category, position).Scan(&channelID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create channel")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"id": channelID})
|
||||
}
|
||||
|
||||
// List handles GET / — returns all channels in a server.
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
serverID := chi.URLParam(r, "serverID")
|
||||
if _, err := uuid.Parse(serverID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid server id")
|
||||
return
|
||||
}
|
||||
|
||||
if !h.isMember(r, userID, serverID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := h.db.QueryContext(r.Context(), `
|
||||
SELECT id, server_id, name, type, category, position, created_at
|
||||
FROM channels
|
||||
WHERE server_id = $1
|
||||
ORDER BY position ASC, created_at ASC
|
||||
`, serverID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list channels")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
channels := []Channel{}
|
||||
for rows.Next() {
|
||||
var c Channel
|
||||
if err := rows.Scan(&c.ID, &c.ServerID, &c.Name, &c.Type, &c.Category, &c.Position, &c.CreatedAt); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "server error")
|
||||
return
|
||||
}
|
||||
channels = append(channels, c)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "server error")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(channels)
|
||||
}
|
||||
|
||||
// Get handles GET /{channelID} — returns a single channel.
|
||||
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
serverID := chi.URLParam(r, "serverID")
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
if _, err := uuid.Parse(channelID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid channel id")
|
||||
return
|
||||
}
|
||||
|
||||
if !h.isMember(r, userID, serverID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
var c Channel
|
||||
err := h.db.QueryRowContext(r.Context(), `
|
||||
SELECT id, server_id, name, type, category, position, created_at
|
||||
FROM channels
|
||||
WHERE id = $1 AND server_id = $2
|
||||
`, channelID, serverID).Scan(&c.ID, &c.ServerID, &c.Name, &c.Type, &c.Category, &c.Position, &c.CreatedAt)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "channel not found")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(c)
|
||||
}
|
||||
|
||||
// Update handles PATCH /{channelID} — updates a channel's properties.
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
serverID := chi.URLParam(r, "serverID")
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
if _, err := uuid.Parse(channelID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid channel id")
|
||||
return
|
||||
}
|
||||
|
||||
if !h.isMember(r, userID, serverID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
var req updateChannelRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate type if provided
|
||||
if req.Type != nil && *req.Type != "text" && *req.Type != "voice" {
|
||||
writeError(w, http.StatusBadRequest, "type must be text or voice")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.db.ExecContext(r.Context(), `
|
||||
UPDATE channels SET
|
||||
name = COALESCE($1, name),
|
||||
type = COALESCE($2, type),
|
||||
category = COALESCE($3, category),
|
||||
position = COALESCE($4, position)
|
||||
WHERE id = $5 AND server_id = $6
|
||||
`, req.Name, req.Type, req.Category, req.Position, channelID, serverID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update channel")
|
||||
return
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
writeError(w, http.StatusNotFound, "channel not found")
|
||||
return
|
||||
}
|
||||
|
||||
var c Channel
|
||||
h.db.QueryRowContext(r.Context(), `
|
||||
SELECT id, server_id, name, type, category, position, created_at
|
||||
FROM channels WHERE id = $1
|
||||
`, channelID).Scan(&c.ID, &c.ServerID, &c.Name, &c.Type, &c.Category, &c.Position, &c.CreatedAt)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(c)
|
||||
}
|
||||
|
||||
// Delete handles DELETE /{channelID} — deletes a channel.
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
serverID := chi.URLParam(r, "serverID")
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
if _, err := uuid.Parse(channelID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid channel id")
|
||||
return
|
||||
}
|
||||
|
||||
if !h.isMember(r, userID, serverID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.db.ExecContext(r.Context(),
|
||||
`DELETE FROM channels WHERE id = $1 AND server_id = $2`,
|
||||
channelID, serverID,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete channel")
|
||||
return
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
writeError(w, http.StatusNotFound, "channel not found")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// isMember checks if a user is a member of the given server.
|
||||
func (h *Handler) isMember(r *http.Request, userID, serverID string) bool {
|
||||
var exists bool
|
||||
h.db.QueryRowContext(r.Context(),
|
||||
`SELECT EXISTS(SELECT 1 FROM members WHERE user_id = $1 AND server_id = $2)`,
|
||||
userID, serverID,
|
||||
).Scan(&exists)
|
||||
return exists
|
||||
}
|
||||
|
||||
// writeError sends a JSON error response.
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": message})
|
||||
}
|
||||
@@ -87,6 +87,24 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
server_id UUID NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
color VARCHAR(7),
|
||||
permissions BIGINT NOT NULL DEFAULT 0,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS member_roles (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
server_id UUID NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, role_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_channel_created ON messages(channel_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
|
||||
CREATE INDEX IF NOT EXISTS idx_members_server_user ON members(server_id, user_id);
|
||||
`
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
pingPeriod = (pongWait * 9) / 10
|
||||
maxMessageSize = 4096
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
// Client is a middleman between the websocket connection and the hub.
|
||||
type Client struct {
|
||||
Hub *Hub
|
||||
Conn *websocket.Conn
|
||||
UserID string
|
||||
send chan []byte
|
||||
}
|
||||
|
||||
// readPump pumps messages from the websocket connection to the hub.
|
||||
func (c *Client) readPump() {
|
||||
defer func() {
|
||||
c.Hub.Unregister(c)
|
||||
c.Conn.Close()
|
||||
}()
|
||||
|
||||
c.Conn.SetReadLimit(maxMessageSize)
|
||||
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
c.Conn.SetPongHandler(func(string) error {
|
||||
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
return nil
|
||||
})
|
||||
|
||||
for {
|
||||
_, raw, err := c.Conn.ReadMessage()
|
||||
if err != nil {
|
||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
|
||||
c.Hub.logger.Warn("websocket read error", "error", err, "user_id", c.UserID)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
var event Event
|
||||
if err := json.Unmarshal(raw, &event); err != nil {
|
||||
c.Hub.logger.Warn("invalid event JSON", "error", err, "user_id", c.UserID)
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle client-sent events (e.g. TYPING_START, PRESENCE_UPDATE)
|
||||
// For now, broadcast them to all clients
|
||||
switch event.Type {
|
||||
case EventTypingStart, EventPresenceUpdate:
|
||||
c.Hub.BroadcastEvent(event)
|
||||
default:
|
||||
c.Hub.logger.Info("received event from client", "type", event.Type, "user_id", c.UserID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// writePump pumps messages from the hub to the websocket connection.
|
||||
func (c *Client) writePump() {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer func() {
|
||||
ticker.Stop()
|
||||
c.Conn.Close()
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||
return
|
||||
}
|
||||
|
||||
w, err := c.Conn.NextWriter(websocket.TextMessage)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
w.Write(message)
|
||||
|
||||
// Drain queued messages into the current write
|
||||
n := len(c.send)
|
||||
for i := 0; i < n; i++ {
|
||||
w.Write([]byte{'\n'})
|
||||
w.Write(<-c.send)
|
||||
}
|
||||
|
||||
if err := w.Close(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ServeWS handles websocket requests from the peer. It authenticates the
|
||||
// client via a session token passed as the "token" query parameter.
|
||||
func ServeWS(db *sql.DB, hub *Hub, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
|
||||
token := r.URL.Query().Get("token")
|
||||
if token == "" {
|
||||
http.Error(w, `{"error":"missing token"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var userID string
|
||||
err := db.QueryRowContext(context.Background(),
|
||||
`SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()`,
|
||||
token,
|
||||
).Scan(&userID)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"invalid or expired session"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logger.Error("websocket upgrade failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
Hub: hub,
|
||||
Conn: conn,
|
||||
UserID: userID,
|
||||
send: make(chan []byte, 256),
|
||||
}
|
||||
|
||||
hub.Register(client)
|
||||
|
||||
go client.writePump()
|
||||
go client.readPump()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package gateway
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Event type constants.
|
||||
const (
|
||||
EventMessageCreate = "MESSAGE_CREATE"
|
||||
EventMessageUpdate = "MESSAGE_UPDATE"
|
||||
EventMessageDelete = "MESSAGE_DELETE"
|
||||
EventChannelCreate = "CHANNEL_CREATE"
|
||||
EventChannelUpdate = "CHANNEL_UPDATE"
|
||||
EventChannelDelete = "CHANNEL_DELETE"
|
||||
EventMemberAdd = "SERVER_MEMBER_ADD"
|
||||
EventMemberRemove = "SERVER_MEMBER_REMOVE"
|
||||
EventPresenceUpdate = "PRESENCE_UPDATE"
|
||||
EventTypingStart = "TYPING_START"
|
||||
)
|
||||
|
||||
// Event represents a WebSocket event sent to clients.
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON implements custom JSON marshaling for Event.
|
||||
func (e Event) MarshalJSON() ([]byte, error) {
|
||||
type eventAlias struct {
|
||||
Type string `json:"type"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
return json.Marshal(eventAlias{
|
||||
Type: e.Type,
|
||||
Data: e.Data,
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements custom JSON unmarshaling for Event.
|
||||
func (e *Event) UnmarshalJSON(data []byte) error {
|
||||
type eventAlias struct {
|
||||
Type string `json:"type"`
|
||||
Data json.RawMessage `json:"data,omitempty"`
|
||||
}
|
||||
var raw eventAlias
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Type = raw.Type
|
||||
e.Data = raw.Data
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Hub maintains the set of active clients and broadcasts messages to them.
|
||||
type Hub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[*Client]struct{}
|
||||
register chan *Client
|
||||
unregister chan *Client
|
||||
broadcast chan []byte
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewHub creates a new Hub.
|
||||
func NewHub(logger *slog.Logger) *Hub {
|
||||
return &Hub{
|
||||
clients: make(map[*Client]struct{}),
|
||||
register: make(chan *Client),
|
||||
unregister: make(chan *Client),
|
||||
broadcast: make(chan []byte, 256),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Run starts the hub's main event loop. Call this in a goroutine.
|
||||
func (h *Hub) Run() {
|
||||
for {
|
||||
select {
|
||||
case client := <-h.register:
|
||||
h.mu.Lock()
|
||||
h.clients[client] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
h.logger.Info("client connected", "user_id", client.UserID)
|
||||
|
||||
case client := <-h.unregister:
|
||||
h.mu.Lock()
|
||||
if _, ok := h.clients[client]; ok {
|
||||
delete(h.clients, client)
|
||||
close(client.send)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
h.logger.Info("client disconnected", "user_id", client.UserID)
|
||||
|
||||
case message := <-h.broadcast:
|
||||
h.mu.RLock()
|
||||
for client := range h.clients {
|
||||
select {
|
||||
case client.send <- message:
|
||||
default:
|
||||
go func(c *Client) {
|
||||
h.unregister <- c
|
||||
}(client)
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Register queues a client for registration with the hub.
|
||||
func (h *Hub) Register(client *Client) {
|
||||
h.register <- client
|
||||
}
|
||||
|
||||
// Unregister queues a client for removal from the hub.
|
||||
func (h *Hub) Unregister(client *Client) {
|
||||
h.unregister <- client
|
||||
}
|
||||
|
||||
// BroadcastEvent serializes an Event and broadcasts it to all connected clients.
|
||||
func (h *Hub) BroadcastEvent(event Event) {
|
||||
data, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to marshal event", "type", event.Type, "error", err)
|
||||
return
|
||||
}
|
||||
h.broadcast <- data
|
||||
}
|
||||
|
||||
// ClientCount returns the number of connected clients.
|
||||
func (h *Hub) ClientCount() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return len(h.clients)
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/gateway"
|
||||
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Handler holds dependencies for message CRUD operations.
|
||||
type Handler struct {
|
||||
db *sql.DB
|
||||
hub *gateway.Hub
|
||||
}
|
||||
|
||||
// NewHandler creates a new message Handler.
|
||||
func NewHandler(db *sql.DB, hub *gateway.Hub) *Handler {
|
||||
return &Handler{db: db, hub: hub}
|
||||
}
|
||||
|
||||
// RegisterRoutes registers message routes on the given chi.Router.
|
||||
// Expects to be mounted under /channels/{channelID}/messages.
|
||||
func (h *Handler) RegisterRoutes(r chi.Router) {
|
||||
r.Get("/", h.List)
|
||||
r.Post("/", h.Create)
|
||||
r.Patch("/{messageID}", h.Update)
|
||||
r.Delete("/{messageID}", h.Delete)
|
||||
}
|
||||
|
||||
// Message is the JSON representation of a message.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
AuthorID string `json:"author_id"`
|
||||
Content string `json:"content"`
|
||||
EditedAt *string `json:"edited_at,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type updateMessageRequest struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// List handles GET / — returns messages in a channel with cursor-based pagination.
|
||||
// Query params: limit (default 50, max 100), before (message ID cursor).
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
if _, err := uuid.Parse(channelID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid channel id")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the user is a member of the server that owns this channel
|
||||
if !h.isChannelMember(r, userID, channelID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse pagination params
|
||||
limit := 50
|
||||
if l := r.URL.Query().Get("limit"); l != "" {
|
||||
if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 100 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
|
||||
before := r.URL.Query().Get("before")
|
||||
|
||||
var rows *sql.Rows
|
||||
var err error
|
||||
|
||||
if before != "" {
|
||||
if _, err := uuid.Parse(before); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid before cursor")
|
||||
return
|
||||
}
|
||||
rows, err = h.db.QueryContext(r.Context(), `
|
||||
SELECT id, channel_id, author_id, content, edited_at, created_at
|
||||
FROM messages
|
||||
WHERE channel_id = $1
|
||||
AND created_at < (SELECT created_at FROM messages WHERE id = $2)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $3
|
||||
`, channelID, before, limit)
|
||||
} else {
|
||||
rows, err = h.db.QueryContext(r.Context(), `
|
||||
SELECT id, channel_id, author_id, content, edited_at, created_at
|
||||
FROM messages
|
||||
WHERE channel_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2
|
||||
`, channelID, limit)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list messages")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := []Message{}
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChannelID, &m.AuthorID, &m.Content, &m.EditedAt, &m.CreatedAt); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "server error")
|
||||
return
|
||||
}
|
||||
messages = append(messages, m)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "server error")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(messages)
|
||||
}
|
||||
|
||||
// Create handles POST / — creates a new message and broadcasts MESSAGE_CREATE.
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
if _, err := uuid.Parse(channelID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid channel id")
|
||||
return
|
||||
}
|
||||
|
||||
if !h.isChannelMember(r, userID, channelID) {
|
||||
writeError(w, http.StatusForbidden, "not a member of this server")
|
||||
return
|
||||
}
|
||||
|
||||
var req createMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
if req.Content == "" {
|
||||
writeError(w, http.StatusBadRequest, "content is required")
|
||||
return
|
||||
}
|
||||
|
||||
var msg Message
|
||||
err := h.db.QueryRowContext(r.Context(), `
|
||||
INSERT INTO messages (channel_id, author_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, channel_id, author_id, content, edited_at, created_at
|
||||
`, channelID, userID, req.Content).Scan(
|
||||
&msg.ID, &msg.ChannelID, &msg.AuthorID, &msg.Content, &msg.EditedAt, &msg.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create message")
|
||||
return
|
||||
}
|
||||
|
||||
// Broadcast MESSAGE_CREATE event via the gateway hub
|
||||
h.hub.BroadcastEvent(gateway.Event{
|
||||
Type: gateway.EventMessageCreate,
|
||||
Data: msg,
|
||||
})
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(msg)
|
||||
}
|
||||
|
||||
// Update handles PATCH /{messageID} — updates a message (author only).
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
messageID := chi.URLParam(r, "messageID")
|
||||
if _, err := uuid.Parse(messageID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid message id")
|
||||
return
|
||||
}
|
||||
|
||||
var req updateMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
if req.Content == "" {
|
||||
writeError(w, http.StatusBadRequest, "content is required")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify authorship
|
||||
var authorID string
|
||||
err := h.db.QueryRowContext(r.Context(),
|
||||
`SELECT author_id FROM messages WHERE id = $1 AND channel_id = $2`,
|
||||
messageID, channelID,
|
||||
).Scan(&authorID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "message not found")
|
||||
return
|
||||
}
|
||||
if authorID != userID {
|
||||
writeError(w, http.StatusForbidden, "you can only edit your own messages")
|
||||
return
|
||||
}
|
||||
|
||||
var msg Message
|
||||
err = h.db.QueryRowContext(r.Context(), `
|
||||
UPDATE messages SET content = $1, edited_at = NOW()
|
||||
WHERE id = $2 AND channel_id = $3
|
||||
RETURNING id, channel_id, author_id, content, edited_at, created_at
|
||||
`, req.Content, messageID, channelID).Scan(
|
||||
&msg.ID, &msg.ChannelID, &msg.AuthorID, &msg.Content, &msg.EditedAt, &msg.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update message")
|
||||
return
|
||||
}
|
||||
|
||||
// Broadcast MESSAGE_UPDATE event
|
||||
h.hub.BroadcastEvent(gateway.Event{
|
||||
Type: gateway.EventMessageUpdate,
|
||||
Data: msg,
|
||||
})
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(msg)
|
||||
}
|
||||
|
||||
// Delete handles DELETE /{messageID} — deletes a message (author only).
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.UserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
channelID := chi.URLParam(r, "channelID")
|
||||
messageID := chi.URLParam(r, "messageID")
|
||||
if _, err := uuid.Parse(messageID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid message id")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify authorship
|
||||
var authorID string
|
||||
err := h.db.QueryRowContext(r.Context(),
|
||||
`SELECT author_id FROM messages WHERE id = $1 AND channel_id = $2`,
|
||||
messageID, channelID,
|
||||
).Scan(&authorID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "message not found")
|
||||
return
|
||||
}
|
||||
if authorID != userID {
|
||||
writeError(w, http.StatusForbidden, "you can only delete your own messages")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.db.ExecContext(r.Context(),
|
||||
`DELETE FROM messages WHERE id = $1 AND channel_id = $2`,
|
||||
messageID, channelID,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete message")
|
||||
return
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
writeError(w, http.StatusNotFound, "message not found")
|
||||
return
|
||||
}
|
||||
|
||||
// Broadcast MESSAGE_DELETE event
|
||||
h.hub.BroadcastEvent(gateway.Event{
|
||||
Type: gateway.EventMessageDelete,
|
||||
Data: map[string]string{
|
||||
"id": messageID,
|
||||
"channel_id": channelID,
|
||||
},
|
||||
})
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// isChannelMember checks if a user is a member of the server that owns the channel.
|
||||
func (h *Handler) isChannelMember(r *http.Request, userID, channelID string) bool {
|
||||
var exists bool
|
||||
h.db.QueryRowContext(r.Context(), `
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM members m
|
||||
INNER JOIN channels c ON c.server_id = m.server_id
|
||||
WHERE m.user_id = $1 AND c.id = $2
|
||||
)
|
||||
`, userID, channelID).Scan(&exists)
|
||||
return exists
|
||||
}
|
||||
|
||||
// writeError sends a JSON error response.
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": message})
|
||||
}
|
||||
Reference in New Issue
Block a user