···
"Coves/internal/core/communityFeeds"
-
"Coves/internal/core/posts"
type postgresFeedRepo struct {
// sortClauses maps sort types to safe SQL ORDER BY clauses
// This whitelist prevents SQL injection via dynamic ORDER BY construction
-
var sortClauses = map[string]string{
"hot": `(p.score / POWER(EXTRACT(EPOCH FROM (NOW() - p.created_at))/3600 + 2, 1.5)) DESC, p.created_at DESC, p.uri DESC`,
"top": `p.score DESC, p.created_at DESC, p.uri DESC`,
"new": `p.created_at DESC, p.uri DESC`,
···
// NOTE: Uses NOW() which means hot_rank changes over time - this is expected behavior
// for hot sorting (posts naturally age out). Slight time drift between cursor creation
// and usage may cause minor reordering but won't drop posts entirely (unlike using raw score).
-
const hotRankExpression = `(p.score / POWER(EXTRACT(EPOCH FROM (NOW() - p.created_at))/3600 + 2, 1.5))`
// NewCommunityFeedRepository creates a new PostgreSQL feed repository
-
func NewCommunityFeedRepository(db *sql.DB) communityFeeds.Repository {
-
return &postgresFeedRepo{db: db}
// GetCommunityFeed retrieves posts from a community with sorting and pagination
// Single query with JOINs for optimal performance
func (r *postgresFeedRepo) GetCommunityFeed(ctx context.Context, req communityFeeds.GetCommunityFeedRequest) ([]*communityFeeds.FeedViewPost, *string, error) {
// Build ORDER BY clause based on sort type
-
orderBy, timeFilter := r.buildSortClause(req.Sort, req.Timeframe)
// Build cursor filter for pagination
-
cursorFilter, cursorValues, err := r.parseCursor(req.Cursor, req.Sort)
return nil, nil, communityFeeds.ErrInvalidCursor
···
p.author_did, u.handle as author_handle,
-
p.community_did, c.name as community_name, c.avatar_cid as community_avatar,
p.title, p.content, p.content_facets, p.embed, p.content_labels,
p.created_at, p.edited_at, p.indexed_at,
p.upvote_count, p.downvote_count, p.score, p.comment_count,
-
FROM posts p`, hotRankExpression)
p.author_did, u.handle as author_handle,
-
p.community_did, c.name as community_name, c.avatar_cid as community_avatar,
p.title, p.content, p.content_facets, p.embed, p.content_labels,
p.created_at, p.edited_at, p.indexed_at,
p.upvote_count, p.downvote_count, p.score, p.comment_count,
···
var feedPosts []*communityFeeds.FeedViewPost
var hotRanks []float64 // Store hot ranks for cursor building
-
feedPost, hotRank, err := r.scanFeedViewPost(rows)
return nil, nil, fmt.Errorf("failed to scan feed post: %w", err)
-
feedPosts = append(feedPosts, feedPost)
hotRanks = append(hotRanks, hotRank)
···
hotRanks = hotRanks[:req.Limit]
lastPost := feedPosts[len(feedPosts)-1].Post
lastHotRank := hotRanks[len(hotRanks)-1]
-
cursorStr := r.buildCursor(lastPost, req.Sort, lastHotRank)
return feedPosts, cursor, nil
-
// buildSortClause returns the ORDER BY SQL and optional time filter
-
func (r *postgresFeedRepo) buildSortClause(sort, timeframe string) (string, string) {
-
// Use whitelist map for ORDER BY clause (defense-in-depth against SQL injection)
-
orderBy := sortClauses[sort]
-
orderBy = sortClauses["hot"] // safe default
-
// Add time filter for "top" sort
-
timeFilter = r.buildTimeFilter(timeframe)
-
return orderBy, timeFilter
-
// buildTimeFilter returns SQL filter for timeframe
-
func (r *postgresFeedRepo) buildTimeFilter(timeframe string) string {
-
if timeframe == "" || timeframe == "all" {
-
return fmt.Sprintf("AND p.created_at > NOW() - INTERVAL '%s'", interval)
-
// parseCursor decodes pagination cursor
-
func (r *postgresFeedRepo) parseCursor(cursor *string, sort string) (string, []interface{}, error) {
-
if cursor == nil || *cursor == "" {
-
// Decode base64 cursor
-
decoded, err := base64.StdEncoding.DecodeString(*cursor)
-
return "", nil, fmt.Errorf("invalid cursor encoding")
-
// Parse cursor based on sort type using :: delimiter (Bluesky convention)
-
parts := strings.Split(string(decoded), "::")
-
// Cursor format: timestamp::uri
-
return "", nil, fmt.Errorf("invalid cursor format")
-
// Validate timestamp format
-
if _, err := time.Parse(time.RFC3339Nano, createdAt); err != nil {
-
return "", nil, fmt.Errorf("invalid cursor timestamp")
-
// Validate URI format (must be AT-URI)
-
if !strings.HasPrefix(uri, "at://") {
-
return "", nil, fmt.Errorf("invalid cursor URI")
-
filter := `AND (p.created_at < $3 OR (p.created_at = $3 AND p.uri < $4))`
-
return filter, []interface{}{createdAt, uri}, nil
-
// Cursor format: score::timestamp::uri
-
return "", nil, fmt.Errorf("invalid cursor format for %s sort", sort)
-
// Validate score is numeric
-
if _, err := fmt.Sscanf(scoreStr, "%d", &score); err != nil {
-
return "", nil, fmt.Errorf("invalid cursor score")
-
// Validate timestamp format
-
if _, err := time.Parse(time.RFC3339Nano, createdAt); err != nil {
-
return "", nil, fmt.Errorf("invalid cursor timestamp")
-
// Validate URI format (must be AT-URI)
-
if !strings.HasPrefix(uri, "at://") {
-
return "", nil, fmt.Errorf("invalid cursor URI")
-
filter := `AND (p.score < $3 OR (p.score = $3 AND p.created_at < $4) OR (p.score = $3 AND p.created_at = $4 AND p.uri < $5))`
-
return filter, []interface{}{score, createdAt, uri}, nil
-
// Cursor format: hot_rank::timestamp::uri
-
// CRITICAL: Must use computed hot_rank, not raw score, to prevent pagination bugs
-
return "", nil, fmt.Errorf("invalid cursor format for hot sort")
-
// Validate hot_rank is numeric (float)
-
if _, err := fmt.Sscanf(hotRankStr, "%f", &hotRank); err != nil {
-
return "", nil, fmt.Errorf("invalid cursor hot rank")
-
// Validate timestamp format
-
if _, err := time.Parse(time.RFC3339Nano, createdAt); err != nil {
-
return "", nil, fmt.Errorf("invalid cursor timestamp")
-
// Validate URI format (must be AT-URI)
-
if !strings.HasPrefix(uri, "at://") {
-
return "", nil, fmt.Errorf("invalid cursor URI")
-
// CRITICAL: Compare against the computed hot_rank expression, not p.score
-
// This prevents dropping posts with higher raw scores but lower hot ranks
-
// NOTE: We exclude the exact cursor post by URI to handle time drift in hot_rank
-
// (hot_rank changes with NOW(), so the same post may have different ranks over time)
-
filter := fmt.Sprintf(`AND ((%s < $3 OR (%s = $3 AND p.created_at < $4) OR (%s = $3 AND p.created_at = $4 AND p.uri < $5)) AND p.uri != $6)`,
-
hotRankExpression, hotRankExpression, hotRankExpression)
-
return filter, []interface{}{hotRank, createdAt, uri, uri}, nil
-
// buildCursor creates pagination cursor from last post
-
func (r *postgresFeedRepo) buildCursor(post *posts.PostView, sort string, hotRank float64) string {
-
// Use :: as delimiter following Bluesky convention
-
// Safe because :: doesn't appear in ISO timestamps or AT-URIs
-
// Format: timestamp::uri (following Bluesky pattern)
-
cursorStr = fmt.Sprintf("%s%s%s", post.CreatedAt.Format(time.RFC3339Nano), delimiter, post.URI)
-
// Format: score::timestamp::uri
-
score = post.Stats.Score
-
cursorStr = fmt.Sprintf("%d%s%s%s%s", score, delimiter, post.CreatedAt.Format(time.RFC3339Nano), delimiter, post.URI)
-
// Format: hot_rank::timestamp::uri
-
// CRITICAL: Use computed hot_rank with full precision to prevent pagination bugs
-
// Using 'g' format with -1 precision gives us full float64 precision without trailing zeros
-
// This prevents posts being dropped when hot ranks differ by <1e-6
-
hotRankStr := strconv.FormatFloat(hotRank, 'g', -1, 64)
-
cursorStr = fmt.Sprintf("%s%s%s%s%s", hotRankStr, delimiter, post.CreatedAt.Format(time.RFC3339Nano), delimiter, post.URI)
-
return base64.StdEncoding.EncodeToString([]byte(cursorStr))
-
// scanFeedViewPost scans a row into FeedViewPost
-
// Alpha: No viewer state - basic community feed only
-
func (r *postgresFeedRepo) scanFeedViewPost(rows *sql.Rows) (*communityFeeds.FeedViewPost, float64, error) {
-
postView posts.PostView
-
authorView posts.AuthorView
-
communityRef posts.CommunityRef
-
title, content sql.NullString
-
facets, embed sql.NullString
-
labelsJSON sql.NullString
-
communityAvatar sql.NullString
-
hotRank sql.NullFloat64
-
&postView.URI, &postView.CID, &postView.RKey,
-
&authorView.DID, &authorView.Handle,
-
&communityRef.DID, &communityRef.Name, &communityAvatar,
-
&title, &content, &facets, &embed, &labelsJSON,
-
&postView.CreatedAt, &editedAt, &postView.IndexedAt,
-
&postView.UpvoteCount, &postView.DownvoteCount, &postView.Score, &postView.CommentCount,
-
// Build author view (no display_name or avatar in users table yet)
-
postView.Author = &authorView
-
communityRef.Avatar = nullStringPtr(communityAvatar)
-
postView.Community = &communityRef
-
postView.Title = nullStringPtr(title)
-
postView.Text = nullStringPtr(content)
-
var facetArray []interface{}
-
if err := json.Unmarshal([]byte(facets.String), &facetArray); err == nil {
-
postView.TextFacets = facetArray
-
var embedData interface{}
-
if err := json.Unmarshal([]byte(embed.String), &embedData); err == nil {
-
postView.Embed = embedData
-
postView.Stats = &posts.PostStats{
-
Upvotes: postView.UpvoteCount,
-
Downvotes: postView.DownvoteCount,
-
CommentCount: postView.CommentCount,
-
// Alpha: No viewer state for basic feed
-
// TODO(feed-generator): Implement viewer state (saved, voted, blocked) in feed generator skeleton
-
// Build the record (required by lexicon - social.coves.community.post structure)
-
record := map[string]interface{}{
-
"$type": "social.coves.community.post",
-
"community": communityRef.DID,
-
"author": authorView.DID,
-
"createdAt": postView.CreatedAt.Format(time.RFC3339),
-
// Add optional fields to record if present
-
record["title"] = title.String
-
record["content"] = content.String
-
var facetArray []interface{}
-
if err := json.Unmarshal([]byte(facets.String), &facetArray); err == nil {
-
record["facets"] = facetArray
-
var embedData interface{}
-
if err := json.Unmarshal([]byte(embed.String), &embedData); err == nil {
-
record["embed"] = embedData
-
// Labels are stored as JSONB containing full com.atproto.label.defs#selfLabels structure
-
// Deserialize and include in record
-
var selfLabels posts.SelfLabels
-
if err := json.Unmarshal([]byte(labelsJSON.String), &selfLabels); err == nil {
-
record["labels"] = selfLabels
-
postView.Record = record
-
// Wrap in FeedViewPost
-
feedPost := &communityFeeds.FeedViewPost{
-
// Reason: nil, // TODO(feed-generator): Implement pinned posts
-
// Reply: nil, // TODO(feed-generator): Implement reply context
-
// Return the computed hot_rank (0.0 if NULL for non-hot sorts)
-
hotRankValue = hotRank.Float64
-
return feedPost, hotRankValue, nil
-
// Helper function to convert sql.NullString to *string
-
func nullStringPtr(ns sql.NullString) *string {