377 lines
13 KiB
Markdown
377 lines
13 KiB
Markdown
# Subtask: Message History and Pagination
|
|
|
|
**Parent Task**: Decomp/002
|
|
**Subtask ID**: Decomp/002-04
|
|
**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-03 (Message Delivery)
|
|
|
|
## Description
|
|
|
|
Implement efficient message history retrieval with pagination. Support cursor-based pagination for performance, around-cursor fetching, and filtering options.
|
|
|
|
## Requirements
|
|
|
|
- Paginated message history per channel
|
|
- Cursor-based pagination (not offset-based)
|
|
- Fetch messages before/after a cursor
|
|
- Limit message count per request (max 100)
|
|
- Include message reactions in response
|
|
- Support filtering by author, date range
|
|
- Efficient queries at scale (billions of messages)
|
|
|
|
## Technical Specifications
|
|
|
|
**Cursor format**: Base64-encoded JSON with message_id and timestamp
|
|
|
|
```python
|
|
import base64
|
|
import json
|
|
from typing import List, Optional, Dict, Any
|
|
|
|
def encode_cursor(message_id: int, created_at: datetime) -> str:
|
|
"""Encode cursor from message data."""
|
|
data = {
|
|
"id": message_id,
|
|
"ts": created_at.isoformat()
|
|
}
|
|
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
|
|
|
def decode_cursor(cursor: str) -> Dict[str, Any]:
|
|
"""Decode cursor to message data."""
|
|
data = json.loads(base64.urlsafe_b64decode(cursor))
|
|
return {
|
|
"id": int(data["id"]),
|
|
"ts": datetime.fromisoformat(data["ts"])
|
|
}
|
|
|
|
class MessageHistoryHandler:
|
|
"""Handle message history queries."""
|
|
|
|
def __init__(self, db_pool):
|
|
self.db = db_pool
|
|
self.max_limit = 100
|
|
self.default_limit = 50
|
|
|
|
async def get_messages(
|
|
self,
|
|
channel_id: int,
|
|
limit: int = None,
|
|
before: str = None,
|
|
after: str = None,
|
|
around: str = None,
|
|
author_id: int = None,
|
|
include_reactions: bool = True
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Fetch messages with pagination.
|
|
|
|
Args:
|
|
channel_id: Channel to fetch from
|
|
limit: Max messages to return (default: 50, max: 100)
|
|
before: Cursor - fetch messages before this point
|
|
after: Cursor - fetch messages after this point
|
|
around: Cursor - fetch messages around this point (50/50 split)
|
|
author_id: Filter by author
|
|
include_reactions: Include reaction data
|
|
|
|
Returns:
|
|
{
|
|
"messages": [...],
|
|
"has_more_before": bool,
|
|
"has_more_after": bool,
|
|
"next_cursor": str or None,
|
|
"prev_cursor": str or None
|
|
}
|
|
"""
|
|
limit = min(limit or self.default_limit, self.max_limit)
|
|
|
|
if around:
|
|
return await self._get_around(channel_id, around, limit, author_id, include_reactions)
|
|
elif before:
|
|
return await self._get_before(channel_id, before, limit, author_id, include_reactions)
|
|
elif after:
|
|
return await self._get_after(channel_id, after, limit, author_id, include_reactions)
|
|
else:
|
|
return await self._get_latest(channel_id, limit, author_id, include_reactions)
|
|
|
|
async def _get_latest(
|
|
self,
|
|
channel_id: int,
|
|
limit: int,
|
|
author_id: Optional[int],
|
|
include_reactions: bool
|
|
) -> Dict[str, Any]:
|
|
"""Get latest messages from channel."""
|
|
async with self.db.acquire() as conn:
|
|
# Build query
|
|
author_filter = "AND author_id = $3" if author_id else ""
|
|
params = [channel_id, limit]
|
|
if author_id:
|
|
params.append(author_id)
|
|
|
|
query = f"""
|
|
SELECT
|
|
m.*,
|
|
u.username, u.display_name, u.avatar_url,
|
|
r.reactions
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(json_build_object(
|
|
'emoji', mr.emoji,
|
|
'emoji_type', mr.emoji_type,
|
|
'count', COUNT(*)
|
|
)) as reactions
|
|
FROM message_reactions mr
|
|
WHERE mr.message_id = m.id
|
|
GROUP BY mr.message_id
|
|
) r ON true
|
|
WHERE m.channel_id = $1
|
|
{author_filter}
|
|
ORDER BY m.channel_position DESC
|
|
LIMIT $2
|
|
"""
|
|
|
|
rows = await conn.fetch(query, *params)
|
|
messages = [self._format_message(row) for row in rows]
|
|
messages.reverse() # Return in chronological order
|
|
|
|
return {
|
|
"messages": messages,
|
|
"has_more_before": False,
|
|
"has_more_after": len(messages) == limit,
|
|
"next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None,
|
|
"prev_cursor": None
|
|
}
|
|
|
|
async def _get_before(
|
|
self,
|
|
channel_id: int,
|
|
cursor: str,
|
|
limit: int,
|
|
author_id: Optional[int],
|
|
include_reactions: bool
|
|
) -> Dict[str, Any]:
|
|
"""Get messages before the cursor (older messages)."""
|
|
cursor_data = decode_cursor(cursor)
|
|
|
|
async with self.db.acquire() as conn:
|
|
author_filter = "AND m.author_id = $4" if author_id else ""
|
|
params = [channel_id, cursor_data["id"], limit]
|
|
if author_id:
|
|
params.append(author_id)
|
|
|
|
query = f"""
|
|
SELECT
|
|
m.*,
|
|
u.username, u.display_name, u.avatar_url,
|
|
r.reactions
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(json_build_object(
|
|
'emoji', mr.emoji,
|
|
'emoji_type', mr.emoji_type,
|
|
'count', COUNT(*)
|
|
)) as reactions
|
|
FROM message_reactions mr
|
|
WHERE mr.message_id = m.id
|
|
GROUP BY mr.message_id
|
|
) r ON true
|
|
WHERE m.channel_id = $1
|
|
AND m.id < $2
|
|
{author_filter}
|
|
ORDER BY m.channel_position DESC
|
|
LIMIT $3
|
|
"""
|
|
|
|
rows = await conn.fetch(query, *params)
|
|
messages = [self._format_message(row) for row in rows]
|
|
messages.reverse()
|
|
|
|
return {
|
|
"messages": messages,
|
|
"has_more_before": len(messages) == limit,
|
|
"has_more_after": True,
|
|
"next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None,
|
|
"prev_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None
|
|
}
|
|
|
|
async def _get_after(
|
|
self,
|
|
channel_id: int,
|
|
cursor: str,
|
|
limit: int,
|
|
author_id: Optional[int],
|
|
include_reactions: bool
|
|
) -> Dict[str, Any]:
|
|
"""Get messages after the cursor (newer messages)."""
|
|
cursor_data = decode_cursor(cursor)
|
|
|
|
async with self.db.acquire() as conn:
|
|
author_filter = "AND m.author_id = $4" if author_id else ""
|
|
params = [channel_id, cursor_data["id"], limit]
|
|
if author_id:
|
|
params.append(author_id)
|
|
|
|
query = f"""
|
|
SELECT
|
|
m.*,
|
|
u.username, u.display_name, u.avatar_url,
|
|
r.reactions
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(json_build_object(
|
|
'emoji', mr.emoji,
|
|
'emoji_type', mr.emoji_type,
|
|
'count', COUNT(*)
|
|
)) as reactions
|
|
FROM message_reactions mr
|
|
WHERE mr.message_id = m.id
|
|
GROUP BY mr.message_id
|
|
) r ON true
|
|
WHERE m.channel_id = $1
|
|
AND m.id > $2
|
|
{author_filter}
|
|
ORDER BY m.channel_position ASC
|
|
LIMIT $3
|
|
"""
|
|
|
|
rows = await conn.fetch(query, *params)
|
|
messages = [self._format_message(row) for row in rows]
|
|
|
|
return {
|
|
"messages": messages,
|
|
"has_more_before": True,
|
|
"has_more_after": len(messages) == limit,
|
|
"next_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None,
|
|
"prev_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None
|
|
}
|
|
|
|
async def _get_around(
|
|
self,
|
|
channel_id: int,
|
|
cursor: str,
|
|
limit: int,
|
|
author_id: Optional[int],
|
|
include_reactions: bool
|
|
) -> Dict[str, Any]:
|
|
"""Get messages around the cursor (half before, half after)."""
|
|
cursor_data = decode_cursor(cursor)
|
|
half_limit = limit // 2
|
|
|
|
async with self.db.acquire() as conn:
|
|
# Get messages before
|
|
author_filter = "AND author_id = $4" if author_id else ""
|
|
params_before = [channel_id, cursor_data["id"], half_limit]
|
|
if author_id:
|
|
params_before.append(author_id)
|
|
|
|
query_before = f"""
|
|
SELECT m.*, u.username, u.display_name, u.avatar_url
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
WHERE m.channel_id = $1 AND m.id < $2 {author_filter}
|
|
ORDER BY m.channel_position DESC
|
|
LIMIT $3
|
|
"""
|
|
rows_before = await conn.fetch(query_before, *params_before)
|
|
before_messages = [self._format_message(row) for row in reversed(rows_before)]
|
|
|
|
# Get messages after (including cursor message)
|
|
params_after = [channel_id, cursor_data["id"], half_limit + 1]
|
|
if author_id:
|
|
params_after.append(author_id)
|
|
|
|
query_after = f"""
|
|
SELECT m.*, u.username, u.display_name, u.avatar_url
|
|
FROM messages m
|
|
JOIN users u ON m.author_id = u.id
|
|
WHERE m.channel_id = $1 AND m.id >= $2 {author_filter}
|
|
ORDER BY m.channel_position ASC
|
|
LIMIT $3
|
|
"""
|
|
rows_after = await conn.fetch(query_after, *params_after)
|
|
after_messages = [self._format_message(row) for row in rows_after]
|
|
|
|
messages = before_messages + after_messages
|
|
|
|
return {
|
|
"messages": messages,
|
|
"has_more_before": len(before_messages) == half_limit,
|
|
"has_more_after": len(after_messages) > half_limit,
|
|
"next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None,
|
|
"prev_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None
|
|
}
|
|
|
|
def _format_message(self, row) -> Dict[str, Any]:
|
|
"""Format database row into API response."""
|
|
return {
|
|
"id": str(row["id"]),
|
|
"channel_id": str(row["channel_id"]),
|
|
"author": {
|
|
"id": str(row["author_id"]),
|
|
"username": row["username"],
|
|
"display_name": row["display_name"],
|
|
"avatar_url": row["avatar_url"]
|
|
},
|
|
"content": row["content"],
|
|
"type": row["type"],
|
|
"reply_to_id": str(row["reply_to_id"]) if row["reply_to_id"] else None,
|
|
"created_at": row["created_at"].isoformat(),
|
|
"edited_at": row["edited_at"].isoformat() if row["edited_at"] else None,
|
|
"channel_position": row["channel_position"],
|
|
"reactions": row.get("reactions", [])
|
|
}
|
|
```
|
|
|
|
**HTTP API endpoint**:
|
|
```python
|
|
from fastapi import Query
|
|
|
|
@app.get("/api/v1/channels/{channel_id}/messages")
|
|
async def get_channel_messages(
|
|
channel_id: int,
|
|
limit: int = Query(50, le=100),
|
|
before: Optional[str] = None,
|
|
after: Optional[str] = None,
|
|
around: Optional[str] = None,
|
|
author_id: Optional[int] = None
|
|
):
|
|
"""Get message history for a channel."""
|
|
handler = MessageHistoryHandler(db_pool)
|
|
result = await handler.get_messages(
|
|
channel_id=channel_id,
|
|
limit=limit,
|
|
before=before,
|
|
after=after,
|
|
around=around,
|
|
author_id=author_id
|
|
)
|
|
return result
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Latest messages returned correctly
|
|
- [ ] Pagination works with before/after cursors
|
|
- [ ] Around cursor returns messages on both sides
|
|
- [ ] Author filter works correctly
|
|
- [ ] Reactions included in response
|
|
- [ ] Limit enforced (max 100)
|
|
- [ ] Queries use indexes (explain analyze confirms)
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Cursor vs offset: Cursor eliminates O(N) offset cost
|
|
- Reactions join: LATERAL join efficient for reaction counts
|
|
|
|
**Performance**:
|
|
- Index on (channel_id, channel_position) enables efficient pagination
|
|
- Partition by month prevents full table scans
|
|
|
|
**Alternatives considered**:
|
|
- OFFSET/LIMIT: Rejected, gets slower with larger offsets
|
|
- Materialized cache: Rejected, cache invalidation complexity
|