393 lines
13 KiB
Markdown
393 lines
13 KiB
Markdown
# Subtask: Message Delivery and Persistence
|
|
|
|
**Parent Task**: Decomp/002
|
|
**Subtask ID**: Decomp/002-03
|
|
**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager)
|
|
|
|
## Description
|
|
|
|
Implement message delivery pipeline with persistence to database. Handle message ordering, ACKs for delivery confirmation, and offline message queue. Support different message types (text, embed, system).
|
|
|
|
## Requirements
|
|
|
|
- Persist messages to database on receipt
|
|
- Broadcast messages to channel subscribers
|
|
- Track message delivery status (sent, delivered, read)
|
|
- Handle message ordering (per-channel sequence)
|
|
- Support message editing and deletion
|
|
- Offline message queue (deliver on reconnect)
|
|
- Message validation and sanitization
|
|
|
|
## Technical Specifications
|
|
|
|
**Message pipeline flow**:
|
|
```
|
|
Client → WebSocket → Validate → Persist → Broadcast → ACK
|
|
```
|
|
|
|
**Message handler**:
|
|
```python
|
|
import asyncio
|
|
from datetime import datetime, timezone
|
|
from typing import Optional, Dict, Any
|
|
import html
|
|
import re
|
|
|
|
class MessageHandler:
|
|
"""Handle message lifecycle from receipt to delivery."""
|
|
|
|
def __init__(self, ws_manager: WebSocketManager, db_pool):
|
|
self.ws_manager = ws_manager
|
|
self.db = db_pool
|
|
self.message_queue = asyncio.Queue(maxsize=10000)
|
|
self._worker_task: Optional[asyncio.Task] = None
|
|
|
|
async def start(self):
|
|
"""Start message processing worker."""
|
|
self._worker_task = asyncio.create_task(self._process_messages())
|
|
|
|
async def handle_incoming_message(
|
|
self,
|
|
connection_id: str,
|
|
data: dict
|
|
) -> Optional[dict]:
|
|
"""
|
|
Handle incoming message from client.
|
|
|
|
Returns message dict if successful, None if failed.
|
|
"""
|
|
# Validate
|
|
validation_error = self._validate_message(data)
|
|
if validation_error:
|
|
await self.ws_manager.send_to_connection(connection_id, {
|
|
"type": "ERROR",
|
|
"error": validation_error
|
|
})
|
|
return None
|
|
|
|
# Extract fields
|
|
channel_id = data["channel_id"]
|
|
author_id = self.ws_manager.connections[connection_id].user_id
|
|
content = data["content"]
|
|
nonce = data.get("nonce") # Client-provided deduplication ID
|
|
reply_to_id = data.get("reply_to_id")
|
|
|
|
# Check permissions
|
|
if not await self._can_send_to_channel(author_id, channel_id):
|
|
await self.ws_manager.send_to_connection(connection_id, {
|
|
"type": "ERROR",
|
|
"error": "No permission to send to this channel"
|
|
})
|
|
return None
|
|
|
|
# Handle rate limiting (slowmode)
|
|
if not await self._check_slowmode(author_id, channel_id):
|
|
await self.ws_manager.send_to_connection(connection_id, {
|
|
"type": "ERROR",
|
|
"error": "Slowmode active"
|
|
})
|
|
return None
|
|
|
|
# Deduplication check (if nonce provided)
|
|
if nonce and await self._is_duplicate(nonce):
|
|
return None
|
|
|
|
# Process message
|
|
message_data = await self._create_message(
|
|
channel_id=channel_id,
|
|
author_id=author_id,
|
|
content=content,
|
|
nonce=nonce,
|
|
reply_to_id=reply_to_id,
|
|
type=data.get("type", "default"),
|
|
metadata=data.get("metadata", {}),
|
|
mentions=data.get("mentions", [])
|
|
)
|
|
|
|
# Queue for broadcast
|
|
await self.message_queue.put(message_data)
|
|
|
|
return message_data
|
|
|
|
async def _create_message(
|
|
self,
|
|
channel_id: int,
|
|
author_id: int,
|
|
content: str,
|
|
nonce: Optional[str] = None,
|
|
reply_to_id: Optional[int] = None,
|
|
type: str = "default",
|
|
metadata: dict = None,
|
|
mentions: list = None
|
|
) -> dict:
|
|
"""Persist message to database."""
|
|
async with self.db.acquire() as conn:
|
|
# Get next channel position for ordering
|
|
channel_position = await conn.fetchval(
|
|
"""SELECT COALESCE(MAX(channel_position), 0) + 1
|
|
FROM messages WHERE channel_id = $1""",
|
|
channel_id
|
|
)
|
|
|
|
# Insert message
|
|
message_id = await conn.fetchval(
|
|
"""INSERT INTO messages
|
|
(channel_id, author_id, content, type, reply_to_id,
|
|
channel_position, metadata, mentions, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())
|
|
RETURNING id""",
|
|
channel_id, author_id, content, type, reply_to_id,
|
|
channel_position, metadata or {}, mentions or []
|
|
)
|
|
|
|
# Get full message data
|
|
message = await conn.fetchrow(
|
|
"""SELECT m.*, u.username, u.display_name, u.avatar_url
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
WHERE m.id = $1""",
|
|
message_id
|
|
)
|
|
|
|
return {
|
|
"id": str(message["id"]),
|
|
"channel_id": str(channel_id),
|
|
"author": {
|
|
"id": str(message["author_id"]),
|
|
"username": message["username"],
|
|
"display_name": message["display_name"],
|
|
"avatar_url": message["avatar_url"]
|
|
},
|
|
"content": message["content"],
|
|
"type": message["type"],
|
|
"reply_to_id": str(message["reply_to_id"]) if message["reply_to_id"] else None,
|
|
"created_at": message["created_at"].isoformat(),
|
|
"edited_at": message["edited_at"].isoformat() if message["edited_at"] else None,
|
|
"channel_position": message["channel_position"],
|
|
"nonce": nonce
|
|
}
|
|
|
|
async def _process_messages(self):
|
|
"""Background worker to broadcast messages."""
|
|
while True:
|
|
try:
|
|
message_data = await self.message_queue.get()
|
|
|
|
# Broadcast to channel subscribers
|
|
await self.ws_manager.broadcast_to_channel(
|
|
int(message_data["channel_id"]),
|
|
{
|
|
"type": "MESSAGE_CREATE",
|
|
"data": message_data
|
|
}
|
|
)
|
|
|
|
# Send to offline users (store in offline queue)
|
|
await self._queue_for_offline_users(message_data)
|
|
|
|
# Update read receipts for mentions
|
|
if message_data.get("mentions"):
|
|
await self._notify_mentioned_users(message_data)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error processing message: {e}")
|
|
|
|
def _validate_message(self, data: dict) -> Optional[str]:
|
|
"""Validate incoming message."""
|
|
required_fields = ["channel_id", "content"]
|
|
for field in required_fields:
|
|
if field not in data:
|
|
return f"Missing required field: {field}"
|
|
|
|
content = data["content"]
|
|
|
|
# Length validation
|
|
if len(content) > 4000:
|
|
return "Message too long (max 4000 characters)"
|
|
|
|
if len(content) == 0:
|
|
return "Message cannot be empty"
|
|
|
|
# Sanitize content (prevent XSS)
|
|
# Keep simple: HTML escape, remove script tags
|
|
if "<script" in content.lower():
|
|
return "Invalid content"
|
|
|
|
return None
|
|
|
|
async def _can_send_to_channel(self, user_id: int, channel_id: int) -> bool:
|
|
"""Check if user can send to channel."""
|
|
async with self.db.acquire() as conn:
|
|
# Check if user is member of server (for server channels)
|
|
server_id = await conn.fetchval(
|
|
"""SELECT server_id FROM channels WHERE id = $1""",
|
|
channel_id
|
|
)
|
|
|
|
if server_id:
|
|
# Server channel - check membership
|
|
return await conn.fetchval(
|
|
"""SELECT 1 FROM server_members
|
|
WHERE server_id = $1 AND user_id = $2""",
|
|
server_id, user_id
|
|
) is not None
|
|
else:
|
|
# DM channel - check if user is member
|
|
return await conn.fetchval(
|
|
"""SELECT 1 FROM dm_channel_members
|
|
WHERE channel_id = $1 AND user_id = $2""",
|
|
channel_id, user_id
|
|
) is not None
|
|
|
|
async def _check_slowmode(self, user_id: int, channel_id: int) -> bool:
|
|
"""Check slowmode restriction."""
|
|
async with self.db.acquire() as conn:
|
|
slowmode_seconds = await conn.fetchval(
|
|
"""SELECT slowmode_seconds FROM channels WHERE id = $1""",
|
|
channel_id
|
|
)
|
|
|
|
if not slowmode_seconds or slowmode_seconds == 0:
|
|
return True
|
|
|
|
# Check last message time
|
|
last_message_time = await conn.fetchval(
|
|
"""SELECT MAX(created_at) FROM messages
|
|
WHERE channel_id = $1 AND author_id = $2""",
|
|
channel_id, user_id
|
|
)
|
|
|
|
if not last_message_time:
|
|
return True
|
|
|
|
elapsed = (datetime.now(timezone.utc) - last_message_time).total_seconds()
|
|
return elapsed >= slowmode_seconds
|
|
|
|
async def _is_duplicate(self, nonce: str) -> bool:
|
|
"""Check if message with this nonce was already processed."""
|
|
# Could use Redis for this
|
|
return False
|
|
|
|
async def _queue_for_offline_users(self, message_data: dict):
|
|
"""Store message for offline delivery to mentioned users."""
|
|
# Implementation: store in Redis or DB
|
|
pass
|
|
|
|
async def _notify_mentioned_users(self, message_data: dict):
|
|
"""Send notification to mentioned users."""
|
|
# Increment mention count in read_state
|
|
pass
|
|
|
|
async def edit_message(
|
|
self,
|
|
message_id: int,
|
|
author_id: int,
|
|
new_content: str
|
|
) -> Optional[dict]:
|
|
"""Edit an existing message."""
|
|
async with self.db.acquire() as conn:
|
|
# Verify ownership
|
|
message = await conn.fetchrow(
|
|
"SELECT * FROM messages WHERE id = $1", message_id
|
|
)
|
|
|
|
if not message or message["author_id"] != author_id:
|
|
return None
|
|
|
|
# Update (with time limit: can only edit messages < 1 hour old)
|
|
if message["created_at"] < datetime.now(timezone.utc) - timedelta(hours=1):
|
|
return None
|
|
|
|
updated = await conn.fetchrow(
|
|
"""UPDATE messages
|
|
SET content = $1, edited_at = NOW()
|
|
WHERE id = $2
|
|
RETURNING *""",
|
|
new_content, message_id
|
|
)
|
|
|
|
# Broadcast update
|
|
await self.ws_manager.broadcast_to_channel(
|
|
message["channel_id"],
|
|
{
|
|
"type": "MESSAGE_UPDATE",
|
|
"data": {
|
|
"id": str(updated["id"]),
|
|
"content": updated["content"],
|
|
"edited_at": updated["edited_at"].isoformat()
|
|
}
|
|
}
|
|
)
|
|
|
|
return {"id": str(updated["id"])}
|
|
|
|
async def delete_message(
|
|
self,
|
|
message_id: int,
|
|
user_id: int
|
|
) -> bool:
|
|
"""Delete a message."""
|
|
async with self.db.acquire() as conn:
|
|
# Get message and check permissions
|
|
message = await conn.fetchrow(
|
|
"""SELECT m.*, s.owner_id
|
|
FROM messages m
|
|
LEFT JOIN channels c ON m.channel_id = c.id
|
|
LEFT JOIN servers s ON c.server_id = s.id
|
|
WHERE m.id = $1""",
|
|
message_id
|
|
)
|
|
|
|
if not message:
|
|
return False
|
|
|
|
# Can delete if author or server owner
|
|
if message["author_id"] != user_id and message["owner_id"] != user_id:
|
|
return False
|
|
|
|
# Soft delete (or hard delete)
|
|
await conn.execute("DELETE FROM messages WHERE id = $1", message_id)
|
|
|
|
# Broadcast deletion
|
|
await self.ws_manager.broadcast_to_channel(
|
|
message["channel_id"],
|
|
{
|
|
"type": "MESSAGE_DELETE",
|
|
"data": {"id": str(message_id)}
|
|
}
|
|
)
|
|
|
|
return True
|
|
```
|
|
|
|
**Integration with WebSocket manager**:
|
|
```python
|
|
# In WebSocketManager._handle_chat_message
|
|
async def _handle_chat_message(self, connection_id: str, data: dict):
|
|
await message_handler.handle_incoming_message(connection_id, data)
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Messages persisted to database
|
|
- [ ] Messages broadcast to all channel subscribers
|
|
- [ ] Message ordering preserved per channel
|
|
- [ ] Edit and delete work correctly
|
|
- [ ] Slowmode restriction enforced
|
|
- [ ] Permission checks prevent unauthorized messages
|
|
- [ ] Non-author users cannot edit/delete messages
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Queue vs direct broadcast: Queue smooths bursts, adds latency
|
|
- Soft delete vs hard delete: Hard delete for privacy
|
|
|
|
**Performance**:
|
|
- Message queue prevents blocking on slow broadcasts
|
|
- Channel position maintains ordering without locks
|
|
|
|
**Alternatives considered**:
|
|
- Event sourcing: Rejected, too complex for MVP
|
|
- Message broker (Kafka): Rejected, adds infrastructure
|