interfaces

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 8, 2026 License: AGPL-3.0 Imports: 9 Imported by: 0

Documentation

Overview

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines repository interfaces for the Lesser application.

This package provides interface definitions for all repositories, enabling:

  • Mock implementations for unit testing
  • In-memory implementations for integration testing
  • Decoupling of business logic from storage implementation details

The interfaces follow the pattern where each repository interface mirrors the public methods of its concrete DynamoDB-backed implementation in pkg/storage/repositories/, allowing the concrete types to satisfy these interfaces through Go's implicit interface implementation.

Usage:

// In production code, use the concrete implementation
storage := adapters.NewDynamORMStorage(db, tableName, logger)
userRepo := storage.User() // Returns interfaces.UserRepository

// In tests, use mock or in-memory implementations
mockRepo := mocks.NewMockUserRepository()
mockRepo.On("GetUser", mock.Anything, "testuser").Return(user, nil)

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces provides comprehensive storage interfaces that bridge legacy storage patterns with the new repository-based DynamORM approach for the Lesser ActivityPub server.

This is the foundation interface for Phase 1 completion of the DynamORM migration initiative.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Package interfaces defines the repository interfaces for the Lesser application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AIRepository

type AIRepository interface {

	// SaveAnalysis stores an AI analysis result
	SaveAnalysis(ctx context.Context, analysis *ai.AIAnalysis) error

	// GetAnalysis retrieves the most recent AI analysis for an object
	GetAnalysis(ctx context.Context, objectID string) (*ai.AIAnalysis, error)

	// GetAnalysisByID retrieves a specific AI analysis by ID
	GetAnalysisByID(ctx context.Context, objectID, analysisID string) (*ai.AIAnalysis, error)

	// GetStats retrieves AI analysis statistics for a given period
	GetStats(ctx context.Context, period string) (*ai.AIStats, error)

	// QueueForAnalysis marks an object for AI analysis
	QueueForAnalysis(ctx context.Context, objectID string) error

	// AnalyzeContent performs comprehensive AI content analysis
	AnalyzeContent(ctx context.Context, content string, modelType string) (*ai.AIAnalysis, error)

	// GetContentClassifications retrieves AI-powered content categorization
	GetContentClassifications(ctx context.Context, contentID string) ([]string, error)

	// UpdateModelPerformance tracks AI model performance with accuracy metrics
	UpdateModelPerformance(ctx context.Context, modelID string, performanceMetrics map[string]float64) error

	// ProcessMLFeedback handles feedback for continuous learning systems
	ProcessMLFeedback(ctx context.Context, analysisID string, feedback map[string]interface{}) error

	// MonitorAIHealth performs health checks on AI processing systems
	MonitorAIHealth(ctx context.Context) error
}

AIRepository defines the interface for AI analysis operations. This handles AI content analysis, moderation, and ML model management.

type AccountRepository

type AccountRepository interface {
	// Core account operations
	CreateAccount(ctx context.Context, account *storage.Account) error
	GetAccount(ctx context.Context, username string) (*storage.Account, error)
	GetAccountByURL(ctx context.Context, actorURL string) (*storage.Account, error)
	GetAccountByEmail(ctx context.Context, email string) (*storage.Account, error)
	UpdateAccount(ctx context.Context, account *storage.Account) error
	DeleteAccount(ctx context.Context, username string) error

	// Account discovery and search
	SearchAccounts(ctx context.Context, query string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)
	GetSuggestedAccounts(ctx context.Context, forUserID string, opts PaginationOptions) (*PaginatedResult[*storage.AccountSuggestion], error)
	GetFeaturedAccounts(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)

	// Account verification and moderation
	ApproveAccount(ctx context.Context, username string) error
	SuspendAccount(ctx context.Context, username string, reason string) error
	UnsuspendAccount(ctx context.Context, username string) error
	SilenceAccount(ctx context.Context, username string, reason string) error
	UnsilenceAccount(ctx context.Context, username string) error

	// Account metadata and preferences
	UpdateAccountPreferences(ctx context.Context, username string, preferences map[string]interface{}) error
	GetAccountPreferences(ctx context.Context, username string) (map[string]interface{}, error)
	UpdateAccountFeatures(ctx context.Context, username string, features map[string]bool) error
	GetAccountFeatures(ctx context.Context, username string) (map[string]bool, error)

	// Authentication and session management
	ValidateCredentials(ctx context.Context, username, password string) (*storage.Account, error)
	UpdatePassword(ctx context.Context, username, newPasswordHash string) error
	CreatePasswordReset(ctx context.Context, reset *storage.PasswordReset) error
	GetPasswordReset(ctx context.Context, token string) (*storage.PasswordReset, error)
	UsePasswordReset(ctx context.Context, token string) error

	// Activity and usage tracking
	RecordLogin(ctx context.Context, attempt *storage.LoginAttempt) error
	GetLoginHistory(ctx context.Context, username string, opts PaginationOptions) (*PaginatedResult[*storage.LoginAttempt], error)
	UpdateLastActivity(ctx context.Context, username string, activity time.Time) error

	// Bookmark operations
	AddBookmark(ctx context.Context, username, objectID string) error
	RemoveBookmark(ctx context.Context, username, objectID string) error
	GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*storage.Bookmark, string, error)
	GetBookmarkedStatuses(ctx context.Context, username string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)

	// Batch operations
	GetAccountsByUsernames(ctx context.Context, usernames []string) ([]*storage.Account, error)
	GetAccountsCount(ctx context.Context) (int64, error)
}

AccountRepository defines the interface for user/actor operations This handles both local users and federated remote actors

type ActivityRepository

type ActivityRepository interface {

	// CreateActivity stores an activity in the database
	CreateActivity(ctx context.Context, activity *activitypub.Activity) error

	// GetActivity retrieves an activity by ID
	GetActivity(ctx context.Context, id string) (*activitypub.Activity, error)

	// GetInboxActivities retrieves inbox activities for a user with pagination
	GetInboxActivities(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Activity, string, error)

	// GetOutboxActivities retrieves activities created by a user with pagination
	GetOutboxActivities(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Activity, string, error)

	// GetCollection retrieves a collection for an actor (inbox, outbox, followers, following, liked)
	GetCollection(ctx context.Context, username, collectionType string, limit int, cursor string) (*activitypub.OrderedCollectionPage, error)

	// GetWeeklyActivity retrieves weekly activity statistics
	GetWeeklyActivity(ctx context.Context, weekTimestamp int64) (*storage.WeeklyActivity, error)

	// RecordActivity records general activity metrics
	RecordActivity(ctx context.Context, activityType string, actorID string, timestamp time.Time) error

	// GetHashtagActivity retrieves activities related to a hashtag since a given time
	GetHashtagActivity(ctx context.Context, hashtag string, since time.Time) ([]*storage.Activity, error)

	// RecordFederationActivity records federation activity metrics
	RecordFederationActivity(ctx context.Context, activity *storage.FederationActivity) error
}

ActivityRepository defines the interface for ActivityPub activity operations. This handles activity lifecycle, inbox/outbox management, collections, and federation tracking.

type ActorRepository

type ActorRepository interface {
	// Core actor operations
	CreateActor(ctx context.Context, actor *activitypub.Actor, privateKey string) error
	GetActor(ctx context.Context, username string) (*activitypub.Actor, error)
	GetActorByUsername(ctx context.Context, username string) (*activitypub.Actor, error)
	GetActorByNumericID(ctx context.Context, numericID string) (*activitypub.Actor, error)
	GetActorWithMetadata(ctx context.Context, username string) (*activitypub.Actor, *storage.ActorMetadata, error)
	GetActorPrivateKey(ctx context.Context, username string) (string, error)
	UpdateActor(ctx context.Context, actor *activitypub.Actor) error
	UpdateActorLastStatusTime(ctx context.Context, username string) error
	SetActorFields(ctx context.Context, username string, fields []storage.ActorField) error
	DeleteActor(ctx context.Context, username string) error

	// Search and discovery
	SearchAccounts(ctx context.Context, query string, limit int, resolve bool, offset int) ([]*activitypub.Actor, error)
	GetSearchSuggestions(ctx context.Context, prefix string) ([]storage.SearchSuggestion, error)
	GetAccountSuggestions(ctx context.Context, userID string, limit int) ([]*activitypub.Actor, error)
	RemoveAccountSuggestion(ctx context.Context, userID, targetID string) error

	// Remote actor caching
	GetCachedRemoteActor(ctx context.Context, handle string) (*activitypub.Actor, error)

	// Migration operations
	UpdateAlsoKnownAs(ctx context.Context, username string, alsoKnownAs []string) error
	UpdateMovedTo(ctx context.Context, username string, movedTo string) error
	CheckAlsoKnownAs(ctx context.Context, username string, targetActorID string) (bool, error)
	GetActorMigrationInfo(ctx context.Context, username string) (*MigrationInfo, error)
}

ActorRepository defines the interface for actor operations This handles ActivityPub actor management and federation

type AnnouncementRepository

type AnnouncementRepository interface {
	// CreateAnnouncement creates a new announcement
	CreateAnnouncement(ctx context.Context, announcement *storage.Announcement) error

	// GetAnnouncement retrieves a single announcement by ID
	GetAnnouncement(ctx context.Context, id string) (*storage.Announcement, error)

	// GetAnnouncements retrieves all announcements (for backward compatibility)
	GetAnnouncements(ctx context.Context, active bool) ([]*storage.Announcement, error)

	// GetAnnouncementsPaginated retrieves announcements with pagination
	GetAnnouncementsPaginated(ctx context.Context, active bool, limit int, cursor string) ([]*storage.Announcement, string, error)

	// GetAnnouncementsByAdmin retrieves announcements created by a specific admin
	GetAnnouncementsByAdmin(ctx context.Context, adminUsername string, limit int, cursor string) ([]*storage.Announcement, string, error)

	// UpdateAnnouncement updates an existing announcement
	UpdateAnnouncement(ctx context.Context, announcement *storage.Announcement) error

	// DeleteAnnouncement deletes an announcement
	DeleteAnnouncement(ctx context.Context, id string) error

	// DismissAnnouncement marks an announcement as dismissed by a user
	DismissAnnouncement(ctx context.Context, username, announcementID string) error

	// IsDismissed checks if a user has dismissed an announcement
	IsDismissed(ctx context.Context, username, announcementID string) (bool, error)

	// GetDismissedAnnouncements gets all announcement IDs dismissed by a user
	GetDismissedAnnouncements(ctx context.Context, username string) ([]string, error)

	// AddAnnouncementReaction adds a user's reaction to an announcement
	AddAnnouncementReaction(ctx context.Context, username, announcementID, emojiName string) error

	// RemoveAnnouncementReaction removes a user's reaction from an announcement
	RemoveAnnouncementReaction(ctx context.Context, username, announcementID, emojiName string) error

	// GetAnnouncementReactions gets all reactions for an announcement
	GetAnnouncementReactions(ctx context.Context, announcementID string) (map[string][]string, error)
}

AnnouncementRepository defines the interface for announcement operations. This handles instance-wide announcements and user interactions with them.

type ArticleRepository

type ArticleRepository interface {

	// GetDB returns the underlying DynamoDB connection for advanced operations
	GetDB() dynamormcore.DB

	// CreateArticle creates a new article
	CreateArticle(ctx context.Context, article *models.Article) error

	// GetArticle retrieves an article by ID
	GetArticle(ctx context.Context, id string) (*models.Article, error)

	// UpdateArticle updates an existing article
	UpdateArticle(ctx context.Context, article *models.Article) error

	// DeleteArticle deletes an article
	DeleteArticle(ctx context.Context, id string) error

	// ListArticles lists articles with a limit
	ListArticles(ctx context.Context, limit int) ([]*models.Article, error)

	// ListArticlesPaginated lists articles with cursor pagination
	ListArticlesPaginated(ctx context.Context, limit int, cursor string) ([]*models.Article, string, error)

	// ListArticlesByAuthorPaginated lists articles for a specific author with pagination
	ListArticlesByAuthorPaginated(ctx context.Context, authorActorID string, limit int, cursor string) ([]*models.Article, string, error)

	// ListArticlesBySeriesPaginated lists articles for a specific series with pagination
	ListArticlesBySeriesPaginated(ctx context.Context, seriesID string, limit int, cursor string) ([]*models.Article, string, error)

	// ListArticlesByCategoryPaginated lists articles for a specific category with pagination
	ListArticlesByCategoryPaginated(ctx context.Context, categoryID string, limit int, cursor string) ([]*models.Article, string, error)
}

ArticleRepository defines the interface for article operations. This handles CMS article management including CRUD operations and pagination.

type AuditRepository

type AuditRepository interface {

	// StoreAuditLog stores an audit log entry
	StoreAuditLog(ctx context.Context, log *models.AuthAuditLog) error

	// GetAuditLogByID retrieves an audit log by ID and date
	GetAuditLogByID(ctx context.Context, id string, date time.Time) (*models.AuthAuditLog, error)

	// GetUserAuditLogs retrieves audit logs for a specific user
	GetUserAuditLogs(ctx context.Context, username string, limit int, startTime, endTime time.Time) ([]*models.AuthAuditLog, error)

	// GetIPAuditLogs retrieves audit logs for a specific IP address
	GetIPAuditLogs(ctx context.Context, ipAddress string, limit int, startTime, endTime time.Time) ([]*models.AuthAuditLog, error)

	// GetSessionAuditLogs retrieves audit logs for a specific session
	GetSessionAuditLogs(ctx context.Context, sessionID string) ([]*models.AuthAuditLog, error)

	// GetSecurityEvents retrieves security events by severity within a time range
	GetSecurityEvents(ctx context.Context, severity string, startTime, endTime time.Time, limit int, cursor string) ([]*models.AuthAuditLog, string, error)

	// GetRecentFailedLogins gets recent failed login attempts for a user
	GetRecentFailedLogins(ctx context.Context, username string, duration time.Duration) (int, error)

	// GetRecentIPFailures gets recent failures from an IP address
	GetRecentIPFailures(ctx context.Context, ipAddress string, duration time.Duration) (int, error)

	// CleanupOldLogs removes audit logs older than retention period
	CleanupOldLogs(ctx context.Context, retentionDays int) error

	// StoreAuditEvent stores an audit event with full metadata
	StoreAuditEvent(ctx context.Context, eventType, severity, username, userID, ipAddress, userAgent, deviceName, sessionID, requestID string, success bool, failureReason string, metadata map[string]interface{}) error
}

AuditRepository defines the interface for audit log operations. This handles authentication audit logging with enhanced security features.

type BookmarkRepository

type BookmarkRepository interface {
	// CreateBookmark creates a new bookmark for a user
	CreateBookmark(ctx context.Context, username, objectID string) (*models.Bookmark, error)

	// DeleteBookmark removes a bookmark
	DeleteBookmark(ctx context.Context, username, objectID string) error

	// GetBookmark retrieves a specific bookmark
	GetBookmark(ctx context.Context, username, objectID string) (*models.Bookmark, error)

	// GetUserBookmarks retrieves all bookmarks for a user with pagination
	GetUserBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*models.Bookmark, string, error)

	// IsBookmarked checks if a user has bookmarked an object
	IsBookmarked(ctx context.Context, username, objectID string) (bool, error)

	// CountUserBookmarks returns the total number of bookmarks by a user
	CountUserBookmarks(ctx context.Context, username string) (int64, error)

	// CheckBookmarksForStatuses returns a map of statusID -> bookmarked for the provided IDs
	CheckBookmarksForStatuses(ctx context.Context, username string, statusIDs []string) (map[string]bool, error)

	// AddBookmark provides Storage interface compatibility
	AddBookmark(ctx context.Context, username, objectID string) error

	// RemoveBookmark provides Storage interface compatibility
	RemoveBookmark(ctx context.Context, username, objectID string) error

	// GetBookmarks provides Storage interface compatibility - returns storage.Bookmark format
	GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*storage.Bookmark, string, error)

	// CascadeDeleteUserBookmarks deletes all bookmarks for a user
	CascadeDeleteUserBookmarks(ctx context.Context, username string) error

	// CascadeDeleteObjectBookmarks deletes all bookmarks for an object
	CascadeDeleteObjectBookmarks(ctx context.Context, objectID string) error
}

BookmarkRepository defines the interface for bookmark operations. This handles user bookmarks for statuses and other content.

type BudgetPeriodStatus

type BudgetPeriodStatus struct {
	Period              string
	BudgetMicroCents    int64
	UsedMicroCents      int64
	UsagePercent        float64
	Status              string
	RemainingMicroCents int64
}

BudgetPeriodStatus represents budget status for a specific period

type BudgetStatus

type BudgetStatus struct {
	UserID          string
	Budgets         map[string]*BudgetPeriodStatus
	AllowConnection bool
	AllowMessages   bool
	ExceededBudgets []string
	WarningBudgets  []string
}

BudgetStatus represents the current budget status for a user

type CacheConfig

type CacheConfig struct {
	// EnableCache enables in-memory caching for frequently accessed data
	EnableCache bool

	// CacheTTL is the default time-to-live for cached items
	CacheTTL time.Duration

	// MaxCacheSize is the maximum number of items to store in cache
	MaxCacheSize int

	// CacheKeyPrefix is the prefix for all cache keys
	CacheKeyPrefix string
}

CacheConfig provides caching configuration options

type CategoryRepository

type CategoryRepository interface {

	// GetDB returns the underlying DynamoDB connection for advanced operations
	GetDB() dynamormcore.DB

	// CreateCategory creates a new category
	CreateCategory(ctx context.Context, category *models.Category) error

	// GetCategory retrieves a category by ID
	GetCategory(ctx context.Context, id string) (*models.Category, error)

	// Update updates an existing category
	Update(ctx context.Context, category *models.Category) error

	// Delete deletes a category by PK and SK
	Delete(ctx context.Context, pk, sk string) error

	// ListCategories lists all categories (optionally filtered by parent)
	ListCategories(ctx context.Context, parentID *string, limit int) ([]*models.Category, error)

	// UpdateArticleCount atomically increments/decrements a category's ArticleCount
	UpdateArticleCount(ctx context.Context, categoryID string, delta int) error
}

CategoryRepository defines the interface for category operations. This handles CMS category management for hierarchical content organization.

type CloudWatchMetricsRepository

type CloudWatchMetricsRepository interface {

	// GetServiceMetrics retrieves comprehensive metrics for a service over the specified period
	GetServiceMetrics(ctx context.Context, serviceName string, period time.Duration) (*ServiceMetrics, error)

	// GetInstanceMetrics retrieves instance-level metrics for the past period
	GetInstanceMetrics(ctx context.Context, period time.Duration) (*ServiceMetrics, error)

	// GetCostBreakdown retrieves detailed cost breakdown for the specified period
	GetCostBreakdown(ctx context.Context, period time.Duration) (*CostBreakdown, error)

	// CacheMetrics stores metrics in DynamoDB for performance optimization
	CacheMetrics(ctx context.Context, serviceName string, metrics *ServiceMetrics) error

	// GetCachedMetrics retrieves cached metrics from DynamoDB
	GetCachedMetrics(ctx context.Context, serviceName string) (*ServiceMetrics, error)
}

CloudWatchMetricsRepository defines the interface for CloudWatch metrics operations. This handles querying CloudWatch metrics with optional DynamoDB caching.

type CommunityNoteRepository

type CommunityNoteRepository interface {

	// CreateCommunityNote creates a new community note
	CreateCommunityNote(ctx context.Context, note *storage.CommunityNote) error

	// GetCommunityNote retrieves a note by ID
	GetCommunityNote(ctx context.Context, noteID string) (*storage.CommunityNote, error)

	// GetVisibleCommunityNotes retrieves visible notes for an object
	GetVisibleCommunityNotes(ctx context.Context, objectID string) ([]*storage.CommunityNote, error)

	// GetCommunityNotesByAuthor retrieves community notes authored by a specific actor
	GetCommunityNotesByAuthor(ctx context.Context, authorID string, limit int, cursor string) ([]*storage.CommunityNote, string, error)

	// UpdateCommunityNoteScore updates a note's score and visibility
	UpdateCommunityNoteScore(ctx context.Context, noteID string, score float64, status string) error

	// UpdateCommunityNoteAnalysis updates AI analysis results for a note
	UpdateCommunityNoteAnalysis(ctx context.Context, noteID string, sentiment, objectivity, sourceQuality float64) error

	// CreateCommunityNoteVote creates a vote on a note
	CreateCommunityNoteVote(ctx context.Context, vote *storage.CommunityNoteVote) error

	// GetCommunityNoteVotes retrieves votes on a specific community note
	GetCommunityNoteVotes(ctx context.Context, noteID string) ([]*storage.CommunityNoteVote, error)

	// GetUserCommunityNoteVotes retrieves a user's votes on specific notes
	GetUserCommunityNoteVotes(ctx context.Context, userID string, noteIDs []string) (map[string]*storage.CommunityNoteVote, error)

	// GetUserVotingHistory retrieves a user's voting history for reputation calculation
	GetUserVotingHistory(ctx context.Context, userID string, limit int) ([]*storage.CommunityNoteVote, error)
}

CommunityNoteRepository defines the interface for community note operations. This handles community-contributed notes for content moderation and fact-checking.

type ConcreteRelationshipRepository

type ConcreteRelationshipRepository interface {

	// CreateRelationship creates a new follow relationship
	CreateRelationship(ctx context.Context, followerUsername, followingUsername, activityID string) error

	// DeleteRelationship removes a follow relationship
	DeleteRelationship(ctx context.Context, followerUsername, followingUsername string) error

	// GetRelationship retrieves a specific follow relationship
	GetRelationship(ctx context.Context, followerUsername, followingUsername string) (*models.RelationshipRecord, error)

	// UpdateRelationship updates relationship settings
	UpdateRelationship(ctx context.Context, followerUsername, followingUsername string, updates map[string]interface{}) error

	// IsFollowing checks if followerUsername is following the targetActorID
	IsFollowing(ctx context.Context, followerUsername, targetActorID string) (bool, error)

	// GetFollowRequest gets a follow request by follower and target IDs
	GetFollowRequest(ctx context.Context, followerID, targetID string) (*storage.RelationshipRecord, error)

	// HasFollowRequest checks if there's a follow request between two users
	HasFollowRequest(ctx context.Context, requesterID, targetID string) (bool, error)

	// HasPendingFollowRequest checks if there's a pending follow request between two users
	HasPendingFollowRequest(ctx context.Context, requesterID, targetID string) (bool, error)

	// GetPendingFollowRequests retrieves pending follow requests for a user
	GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	// AcceptFollowRequest accepts a follow request
	AcceptFollowRequest(ctx context.Context, followerUsername, followingUsername string) error

	// RejectFollowRequest rejects a follow request
	RejectFollowRequest(ctx context.Context, followerUsername, followingUsername string) error

	// GetFollowers retrieves all followers for a user
	GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	// GetFollowing retrieves all users that a user is following
	GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	// CountFollowers returns the number of followers for a user
	CountFollowers(ctx context.Context, username string) (int, error)

	// CountFollowing returns the number of users that a user is following
	CountFollowing(ctx context.Context, username string) (int, error)

	// GetFollowerCount returns the number of followers for a user (int64 version)
	GetFollowerCount(ctx context.Context, userID string) (int64, error)

	// GetFollowingCount returns the number of users that a user is following (int64 version)
	GetFollowingCount(ctx context.Context, userID string) (int64, error)

	// CountRelationshipsByDomain counts follower/following relationships involving a remote domain
	CountRelationshipsByDomain(ctx context.Context, domain string) (followers, following int, err error)

	// Unfollow removes a follow relationship (wrapper for DeleteRelationship)
	Unfollow(ctx context.Context, followerID, followingID string) error

	// CreateBlock creates a new block relationship
	CreateBlock(ctx context.Context, blockerActor, blockedActor, activityID string) error

	// DeleteBlock removes a block relationship
	DeleteBlock(ctx context.Context, blockerActor, blockedActor string) error

	// BlockUser blocks another user
	BlockUser(ctx context.Context, blockerID, blockedID string) error

	// UnblockUser removes a block relationship
	UnblockUser(ctx context.Context, blockerID, blockedID string) error

	// IsBlocked checks if one actor has blocked another
	IsBlocked(ctx context.Context, blockerActor, blockedActor string) (bool, error)

	// IsBlockedBidirectional checks if either actor has blocked the other
	IsBlockedBidirectional(ctx context.Context, actor1, actor2 string) (bool, error)

	// GetBlockedUsers returns a list of users blocked by the given actor
	GetBlockedUsers(ctx context.Context, blockerActor string, limit int, cursor string) ([]string, string, error)

	// GetUsersWhoBlocked returns a list of users who have blocked the given actor
	GetUsersWhoBlocked(ctx context.Context, blockedActor string, limit int, cursor string) ([]string, string, error)

	// GetBlock retrieves a specific block relationship
	GetBlock(ctx context.Context, blockerActor, blockedActor string) (*storage.Block, error)

	// CountBlockedUsers returns the number of users blocked by the given actor
	CountBlockedUsers(ctx context.Context, blockerActor string) (int, error)

	// CountUsersWhoBlocked returns the number of users who have blocked the given actor
	CountUsersWhoBlocked(ctx context.Context, blockedActor string) (int, error)

	// CreateMute creates a new mute relationship
	CreateMute(ctx context.Context, muterActor, mutedActor, activityID string, hideNotifications bool, duration *time.Duration) error

	// DeleteMute removes a mute relationship
	DeleteMute(ctx context.Context, muterActor, mutedActor string) error

	// UnmuteUser removes a mute relationship
	UnmuteUser(ctx context.Context, muterID, mutedID string) error

	// IsMuted checks if one actor has muted another
	IsMuted(ctx context.Context, muterActor, mutedActor string) (bool, error)

	// GetMutedUsers returns a list of users muted by the given actor
	GetMutedUsers(ctx context.Context, muterActor string, limit int, cursor string) ([]string, string, error)

	// GetUsersWhoMuted returns a list of users who have muted the given actor
	GetUsersWhoMuted(ctx context.Context, mutedActor string, limit int, cursor string) ([]string, string, error)

	// GetMute retrieves a specific mute relationship
	GetMute(ctx context.Context, muterActor, mutedActor string) (*storage.Mute, error)

	// CountMutedUsers returns the number of users muted by the given actor
	CountMutedUsers(ctx context.Context, muterActor string) (int, error)

	// CountUsersWhoMuted returns the number of users who have muted the given actor
	CountUsersWhoMuted(ctx context.Context, mutedActor string) (int, error)

	// IsEndorsed checks if a user has endorsed (pinned) a target account
	IsEndorsed(ctx context.Context, userID, targetID string) (bool, error)

	// CreateEndorsement creates a new endorsement (account pin) relationship
	CreateEndorsement(ctx context.Context, endorsement *storage.AccountPin) error

	// DeleteEndorsement removes an endorsement (account pin) relationship
	DeleteEndorsement(ctx context.Context, endorserID, endorsedID string) error

	// GetEndorsements retrieves all endorsements (account pins) for a user
	GetEndorsements(ctx context.Context, userID string, limit int, cursor string) ([]*storage.AccountPin, string, error)

	// GetRelationshipNote retrieves a private note on an account
	GetRelationshipNote(ctx context.Context, userID, targetID string) (*storage.AccountNote, error)

	// CreateMove creates a new move record
	CreateMove(ctx context.Context, move *storage.Move) error

	// GetMove retrieves the most recent move for an actor
	GetMove(ctx context.Context, actor string) (*storage.Move, error)

	// GetAccountMoves retrieves all moves for an account (as actor)
	GetAccountMoves(ctx context.Context, actor string) ([]*storage.Move, error)

	// UpdateMoveProgress updates move migration progress
	UpdateMoveProgress(ctx context.Context, actor, target string, progress map[string]interface{}) error

	// VerifyMove marks a move as verified
	VerifyMove(ctx context.Context, actor, target string) error

	// GetPendingMoves retrieves moves that haven't been fully processed
	GetPendingMoves(ctx context.Context, limit int) ([]*storage.Move, error)

	// GetMoveByTarget retrieves all moves to a specific target account
	GetMoveByTarget(ctx context.Context, target string) ([]*storage.Move, error)

	// HasMovedFrom checks if newActor has moved from oldActor
	HasMovedFrom(ctx context.Context, oldActor, newActor string) (bool, error)

	// AddToCollection adds an item to a collection
	AddToCollection(ctx context.Context, collection string, item *storage.CollectionItem) error

	// RemoveFromCollection removes an item from a collection
	RemoveFromCollection(ctx context.Context, collection, itemID string) error

	// GetCollectionItems retrieves items from a collection with pagination
	GetCollectionItems(ctx context.Context, collection string, limit int, cursor string) ([]*storage.CollectionItem, string, error)

	// IsInCollection checks if an item is in a collection
	IsInCollection(ctx context.Context, collection, itemID string) (bool, error)

	// CountCollectionItems returns the count of items in a collection
	CountCollectionItems(ctx context.Context, collection string) (int, error)

	// ClearCollection removes all items from a collection
	ClearCollection(ctx context.Context, collection string) error
}

ConcreteRelationshipRepository defines the interface for relationship operations that matches the concrete repositories.RelationshipRepository implementation. This handles follow relationships, blocks, mutes, endorsements, moves, and collections.

type ConversationRepository

type ConversationRepository interface {

	// CreateConversation creates a new conversation with participants
	CreateConversation(ctx context.Context, conversation *models.Conversation, participants []string) error

	// GetConversation retrieves a conversation by ID
	GetConversation(ctx context.Context, id string) (*models.Conversation, error)

	// UpdateConversation updates a conversation
	UpdateConversation(ctx context.Context, conversation *models.Conversation) error

	// DeleteConversation deletes a conversation by ID
	DeleteConversation(ctx context.Context, id string) error

	// GetUserConversations retrieves conversations for a user with pagination
	GetUserConversations(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Conversation], error)

	// GetConversationByParticipants finds a conversation with exact participants
	GetConversationByParticipants(ctx context.Context, participants []string) (*models.Conversation, error)

	// GetUnreadConversations retrieves unread conversations for a user
	GetUnreadConversations(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Conversation], error)

	// SearchConversations searches conversations for a user by query
	SearchConversations(ctx context.Context, userID, query string, opts PaginationOptions) (*PaginatedResult[*models.Conversation], error)

	// MarkConversationRead marks a conversation as read for a user
	MarkConversationRead(ctx context.Context, conversationID, username string) error

	// MarkConversationUnread marks a conversation as unread for a user
	MarkConversationUnread(ctx context.Context, conversationID, userID string) error

	// GetUnreadConversationCount gets the count of unread conversations for a user
	GetUnreadConversationCount(ctx context.Context, username string) (int, error)

	// AddStatusToConversation adds a status/message to a conversation
	AddStatusToConversation(ctx context.Context, conversationID, statusID, senderUsername string) error

	// GetConversationStatuses retrieves messages in a conversation with pagination
	GetConversationStatuses(ctx context.Context, conversationID string, limit int, cursor string) ([]*storage.ConversationStatus, string, error)

	// RemoveStatusFromConversation removes a status from a conversation
	RemoveStatusFromConversation(ctx context.Context, conversationID, statusID string) error

	// MarkStatusRead marks a specific status as read by a user
	MarkStatusRead(ctx context.Context, conversationID, statusID, username string) error

	// GetUnreadStatusCount gets the count of unread statuses in a conversation for a user
	GetUnreadStatusCount(ctx context.Context, conversationID, username string) (int, error)

	// UpdateConversationLastStatus updates the last status in a conversation
	UpdateConversationLastStatus(ctx context.Context, id, lastStatusID string) error

	// AddParticipant adds a participant to a conversation
	AddParticipant(ctx context.Context, conversationID, participantID string) error

	// RemoveParticipant removes a participant from a conversation
	RemoveParticipant(ctx context.Context, conversationID, participantID string) error

	// GetConversationParticipants retrieves the list of participants in a conversation
	GetConversationParticipants(ctx context.Context, conversationID string) ([]string, error)

	// LeaveConversation removes a participant from a conversation
	LeaveConversation(ctx context.Context, conversationID, username string) error

	// CreateConversationMute creates a new conversation mute
	CreateConversationMute(ctx context.Context, mute *storage.ConversationMute) error

	// DeleteConversationMute removes a conversation mute
	DeleteConversationMute(ctx context.Context, username, conversationID string) error

	// IsConversationMuted checks if a conversation is muted by a user
	IsConversationMuted(ctx context.Context, username, conversationID string) (bool, error)

	// GetMutedConversations retrieves all muted conversations for a user
	GetMutedConversations(ctx context.Context, username string) ([]string, error)
}

ConversationRepository defines the interface for conversation operations. This handles direct message conversations, participants, and message threading.

type CostBreakdown

type CostBreakdown struct {
	TotalCost        float64
	DynamoDBCost     float64
	LambdaCost       float64
	APIGatewayCost   float64
	S3Cost           float64
	DataTransferCost float64
	Breakdown        []*CostItem
}

CostBreakdown represents cost breakdown data.

type CostDataPoint

type CostDataPoint struct {
	Timestamp     time.Time
	CostDollars   float64
	Operations    int64
	ReadCapacity  float64
	WriteCapacity float64
}

CostDataPoint represents a single point in the cost trend

type CostItem

type CostItem struct {
	Operation string
	Count     int
	Cost      float64
}

CostItem represents a single cost item.

type CostTrend

type CostTrend struct {
	Period          string
	OperationType   string
	StartTime       time.Time
	EndTime         time.Time
	DataPoints      []CostDataPoint
	TotalCost       float64
	AverageCost     float64
	MinCost         float64
	MaxCost         float64
	TrendPercentage float64
}

CostTrend represents cost trend analysis

type DLQAnalytics

type DLQAnalytics struct {
	Service               string                         `json:"service"`
	TimeRange             DLQTimeRange                   `json:"time_range"`
	TotalMessages         int                            `json:"total_messages"`
	NewMessages           int                            `json:"new_messages"`
	ReprocessingMessages  int                            `json:"reprocessing_messages"`
	ResolvedMessages      int                            `json:"resolved_messages"`
	FailedMessages        int                            `json:"failed_messages"`
	AbandonedMessages     int                            `json:"abandoned_messages"`
	ResolutionRate        float64                        `json:"resolution_rate"`
	AbandonmentRate       float64                        `json:"abandonment_rate"`
	TotalCostMicroCents   int64                          `json:"total_cost_micro_cents"`
	TotalCostDollars      float64                        `json:"total_cost_dollars"`
	AverageCostPerMessage float64                        `json:"average_cost_per_message"`
	ErrorTypeStats        map[string]*DLQErrorTypeStats  `json:"error_type_stats"`
	ServiceStats          map[string]*DLQServiceStats    `json:"service_stats"`
	SimilarityGroups      map[string]*DLQSimilarityGroup `json:"similarity_groups"`
}

DLQAnalytics represents analytics data for DLQ messages.

type DLQDailyStats

type DLQDailyStats struct {
	Date                time.Time      `json:"date"`
	MessageCount        int            `json:"message_count"`
	TotalCostMicroCents int64          `json:"total_cost_micro_cents"`
	TotalCostDollars    float64        `json:"total_cost_dollars"`
	ErrorTypes          map[string]int `json:"error_types"`
	StatusCounts        map[string]int `json:"status_counts"`
}

DLQDailyStats represents statistics for a single day.

type DLQErrorTypeStats

type DLQErrorTypeStats struct {
	ErrorType           string  `json:"error_type"`
	Count               int     `json:"count"`
	ResolvedCount       int     `json:"resolved_count"`
	ResolutionRate      float64 `json:"resolution_rate"`
	TotalCostMicroCents int64   `json:"total_cost_micro_cents"`
}

DLQErrorTypeStats represents statistics for a specific error type.

type DLQHealthStatus

type DLQHealthStatus struct {
	Service           string         `json:"service"`
	CheckTime         time.Time      `json:"check_time"`
	TotalMessages     int            `json:"total_messages"`
	NewMessages       int            `json:"new_messages"`
	ReprocessingCount int            `json:"reprocessing_count"`
	AbandonedCount    int            `json:"abandoned_count"`
	ErrorRates        map[string]int `json:"error_rates"`
	AverageRetryCount float64        `json:"average_retry_count"`
	IsHealthy         bool           `json:"is_healthy"`
	Alerts            []string       `json:"alerts"`
}

DLQHealthStatus represents health metrics for DLQ monitoring.

type DLQRepository

type DLQRepository interface {

	// CreateDLQMessage creates a new DLQ message
	CreateDLQMessage(ctx context.Context, message *models.DLQMessage) error

	// GetDLQMessage retrieves a DLQ message by ID
	GetDLQMessage(ctx context.Context, id string) (*models.DLQMessage, error)

	// UpdateDLQMessage updates an existing DLQ message
	UpdateDLQMessage(ctx context.Context, message *models.DLQMessage) error

	// DeleteDLQMessage deletes a DLQ message
	DeleteDLQMessage(ctx context.Context, message *models.DLQMessage) error

	// BatchUpdateDLQMessages updates multiple DLQ messages
	BatchUpdateDLQMessages(ctx context.Context, messages []*models.DLQMessage) error

	// GetDLQMessagesByService retrieves DLQ messages for a specific service with pagination
	GetDLQMessagesByService(ctx context.Context, service string, date time.Time, limit int, cursor string) ([]*models.DLQMessage, string, error)

	// GetDLQMessagesByServiceDateRange retrieves DLQ messages for a service across multiple dates
	GetDLQMessagesByServiceDateRange(ctx context.Context, service string, startDate, endDate time.Time, limit int) ([]*models.DLQMessage, error)

	// GetDLQMessagesByErrorType retrieves DLQ messages by error type with pagination
	GetDLQMessagesByErrorType(ctx context.Context, errorType string, limit int, cursor string) ([]*models.DLQMessage, string, error)

	// GetDLQMessagesForReprocessing retrieves messages that can be reprocessed
	GetDLQMessagesForReprocessing(ctx context.Context, service string, status string, limit int, cursor string) ([]*models.DLQMessage, string, error)

	// GetDLQMessagesByStatus retrieves messages by status
	GetDLQMessagesByStatus(ctx context.Context, service, status string, limit int, cursor string) ([]*models.DLQMessage, string, error)

	// SearchDLQMessages searches DLQ messages with various filters
	SearchDLQMessages(ctx context.Context, filter *DLQSearchFilter) ([]*models.DLQMessage, string, error)

	// GetSimilarMessages finds messages with the same similarity hash
	GetSimilarMessages(ctx context.Context, similarityHash string, limit int) ([]*models.DLQMessage, error)

	// GetDLQAnalytics returns analytics data for DLQ messages
	GetDLQAnalytics(ctx context.Context, service string, timeRange DLQTimeRange) (*DLQAnalytics, error)

	// GetDLQTrends returns trend data for DLQ messages over time
	GetDLQTrends(ctx context.Context, service string, days int) (*DLQTrends, error)

	// AnalyzeFailurePatterns analyzes DLQ messages to identify common failure patterns
	AnalyzeFailurePatterns(ctx context.Context, service string, days int) (map[string]*DLQSimilarityGroup, error)

	// SendToDeadLetterQueue creates and stores a DLQ message with proper error categorization
	SendToDeadLetterQueue(ctx context.Context, service, messageID, messageBody, errorType, errorMessage string, isPermanent bool) error

	// RetryFailedMessage attempts to reprocess a DLQ message with exponential backoff
	RetryFailedMessage(ctx context.Context, messageID string) error

	// GetRetryableMessages returns messages that are ready for retry based on backoff schedule
	GetRetryableMessages(ctx context.Context, service string, limit int) ([]*models.DLQMessage, error)

	// CleanupExpiredMessages deletes expired DLQ messages
	CleanupExpiredMessages(ctx context.Context, before time.Time) (int, error)

	// MonitorDLQHealth provides health metrics for DLQ monitoring and alerting
	MonitorDLQHealth(ctx context.Context, service string) (*DLQHealthStatus, error)
}

DLQRepository defines the interface for dead letter queue operations. This handles failed message storage, retry logic, analytics, and health monitoring.

type DLQSearchFilter

type DLQSearchFilter struct {
	Service     string    `json:"service"`
	ErrorType   string    `json:"error_type,omitempty"`
	Status      string    `json:"status,omitempty"`
	Priority    string    `json:"priority,omitempty"`
	IsPermanent *bool     `json:"is_permanent,omitempty"`
	StartTime   time.Time `json:"start_time,omitempty"`
	EndTime     time.Time `json:"end_time,omitempty"`
	SearchText  string    `json:"search_text,omitempty"`
	Limit       int       `json:"limit,omitempty"`
	Cursor      string    `json:"cursor,omitempty"`
}

DLQSearchFilter represents search criteria for DLQ messages.

type DLQServiceStats

type DLQServiceStats struct {
	Service             string  `json:"service"`
	MessageCount        int     `json:"message_count"`
	ErrorTypes          int     `json:"error_types"`
	ResolutionRate      float64 `json:"resolution_rate"`
	TotalCostMicroCents int64   `json:"total_cost_micro_cents"`
}

DLQServiceStats represents statistics for a specific service.

type DLQSimilarityGroup

type DLQSimilarityGroup struct {
	SimilarityHash string    `json:"similarity_hash"`
	ErrorType      string    `json:"error_type"`
	Service        string    `json:"service"`
	MessageCount   int       `json:"message_count"`
	MessageIDs     []string  `json:"message_ids"`
	FirstSeen      time.Time `json:"first_seen"`
	LastSeen       time.Time `json:"last_seen"`
	SampleError    string    `json:"sample_error"`
}

DLQSimilarityGroup represents a group of similar error messages.

type DLQTimeRange

type DLQTimeRange struct {
	StartTime time.Time `json:"start_time"`
	EndTime   time.Time `json:"end_time"`
}

DLQTimeRange represents a time range for DLQ analytics queries.

type DLQTrends

type DLQTrends struct {
	Service    string                    `json:"service"`
	Days       int                       `json:"days"`
	DailyStats map[string]*DLQDailyStats `json:"daily_stats"`
}

DLQTrends represents trend data over time.

type DNSCacheRepository

type DNSCacheRepository interface {
	// GetDNSCache retrieves a cached DNS lookup result
	GetDNSCache(ctx context.Context, hostname string) (*storage.DNSCacheEntry, error)

	// SetDNSCache stores a DNS lookup result in the cache
	SetDNSCache(ctx context.Context, entry *storage.DNSCacheEntry) error

	// InvalidateDNSCache removes a DNS cache entry
	InvalidateDNSCache(ctx context.Context, hostname string) error
}

DNSCacheRepository defines the interface for DNS cache operations. This handles caching of DNS lookup results for performance optimization.

type DailyAggregate

type DailyAggregate struct {
	Date            time.Time
	TotalCost       float64
	TotalOperations int64
}

DailyAggregate represents aggregated daily costs

type DomainBlockRepository

type DomainBlockRepository interface {

	// AddDomainBlock adds a domain to the user's block list
	AddDomainBlock(ctx context.Context, username, domain string) error

	// RemoveDomainBlock removes a domain from the user's block list
	RemoveDomainBlock(ctx context.Context, username, domain string) error

	// GetUserDomainBlocks retrieves all domains blocked by a user
	GetUserDomainBlocks(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	// IsBlockedDomain checks if a domain is blocked by a user
	IsBlockedDomain(ctx context.Context, username, domain string) (bool, error)

	// CreateInstanceDomainBlock creates an instance-level domain block
	CreateInstanceDomainBlock(ctx context.Context, block *storage.InstanceDomainBlock) error

	// GetInstanceDomainBlock retrieves a domain block by domain
	GetInstanceDomainBlock(ctx context.Context, domain string) (*storage.InstanceDomainBlock, error)

	// GetInstanceDomainBlockByID retrieves a domain block by ID
	GetInstanceDomainBlockByID(ctx context.Context, id string) (*storage.InstanceDomainBlock, error)

	// ListInstanceDomainBlocks lists all instance domain blocks with pagination
	ListInstanceDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.InstanceDomainBlock, string, error)

	// UpdateInstanceDomainBlock updates an existing domain block
	UpdateInstanceDomainBlock(ctx context.Context, domain string, updates map[string]any) error

	// DeleteInstanceDomainBlock deletes a domain block
	DeleteInstanceDomainBlock(ctx context.Context, domain string) error

	// IsInstanceDomainBlocked checks if a domain is blocked at the instance level
	IsInstanceDomainBlocked(ctx context.Context, domain string) (bool, *storage.InstanceDomainBlock, error)

	// GetDomainBlocks retrieves instance-level domain blocks with pagination
	GetDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.InstanceDomainBlock, string, error)

	// GetDomainBlock retrieves a specific domain block by ID
	GetDomainBlock(ctx context.Context, id string) (*storage.InstanceDomainBlock, error)

	// CreateDomainBlock creates a new instance-level domain block
	CreateDomainBlock(ctx context.Context, block *storage.InstanceDomainBlock) error

	// UpdateDomainBlock updates an existing domain block
	UpdateDomainBlock(ctx context.Context, id string, updates map[string]any) error

	// DeleteDomainBlock removes a domain block
	DeleteDomainBlock(ctx context.Context, id string) error

	// IsDomainBlocked checks if a domain is blocked at the instance level
	IsDomainBlocked(ctx context.Context, domain string) (bool, *storage.InstanceDomainBlock, error)

	// CreateEmailDomainBlock creates an email domain block
	CreateEmailDomainBlock(ctx context.Context, block *storage.EmailDomainBlock) error

	// GetEmailDomainBlocks retrieves email domain blocks with pagination
	GetEmailDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.EmailDomainBlock, string, error)

	// DeleteEmailDomainBlock deletes an email domain block
	DeleteEmailDomainBlock(ctx context.Context, id string) error

	// GetDomainAllows retrieves domain allows (for allowlist mode)
	GetDomainAllows(ctx context.Context, limit int, cursor string) ([]*storage.DomainAllow, string, error)

	// CreateDomainAllow adds a domain to the allowlist
	CreateDomainAllow(ctx context.Context, allow *storage.DomainAllow) error

	// DeleteDomainAllow removes a domain from the allowlist
	DeleteDomainAllow(ctx context.Context, id string) error
}

DomainBlockRepository defines the interface for domain block operations. This handles both user-level and instance-level domain blocking.

type DraftRepository

type DraftRepository interface {

	// CreateDraft creates a new draft
	CreateDraft(ctx context.Context, draft *models.Draft) error

	// GetDraft retrieves a draft by author ID and draft ID
	GetDraft(ctx context.Context, authorID, draftID string) (*models.Draft, error)

	// UpdateDraft updates an existing draft
	UpdateDraft(ctx context.Context, draft *models.Draft) error

	// DeleteDraft deletes a draft
	DeleteDraft(ctx context.Context, authorID, draftID string) error

	// ListDraftsByAuthor lists drafts for an author
	ListDraftsByAuthor(ctx context.Context, authorID string, limit int) ([]*models.Draft, error)

	// ListDraftsByAuthorPaginated lists drafts for an author with cursor pagination
	ListDraftsByAuthorPaginated(ctx context.Context, authorID string, limit int, cursor string) ([]*models.Draft, string, error)

	// ListScheduledDraftsDuePaginated lists drafts scheduled to publish at or before the provided time
	ListScheduledDraftsDuePaginated(ctx context.Context, dueBefore time.Time, limit int, cursor string) ([]*models.Draft, string, error)
}

DraftRepository defines the interface for draft operations. This handles CMS draft management including CRUD operations and scheduling.

type EmojiRepository

type EmojiRepository interface {

	// CreateCustomEmoji creates a new custom emoji
	CreateCustomEmoji(ctx context.Context, emoji *storage.CustomEmoji) error

	// GetCustomEmoji retrieves a custom emoji by shortcode
	GetCustomEmoji(ctx context.Context, shortcode string) (*storage.CustomEmoji, error)

	// GetCustomEmojis retrieves all custom emojis (not disabled)
	GetCustomEmojis(ctx context.Context) ([]*storage.CustomEmoji, error)

	// UpdateCustomEmoji updates an existing custom emoji
	UpdateCustomEmoji(ctx context.Context, emoji *storage.CustomEmoji) error

	// DeleteCustomEmoji deletes a custom emoji
	DeleteCustomEmoji(ctx context.Context, shortcode string) error

	// GetRemoteEmoji retrieves a remote emoji by shortcode and domain
	GetRemoteEmoji(ctx context.Context, shortcode, domain string) (*storage.CustomEmoji, error)

	// GetCustomEmojisByCategory retrieves custom emojis by category
	GetCustomEmojisByCategory(ctx context.Context, category string) ([]*storage.CustomEmoji, error)

	// SearchEmojis performs sophisticated emoji searches with relevance scoring
	SearchEmojis(ctx context.Context, query string, limit int) ([]*storage.CustomEmoji, error)

	// GetPopularEmojis retrieves emojis by popularity score, optionally filtered by domain
	GetPopularEmojis(ctx context.Context, domain string, limit int) ([]*storage.CustomEmoji, error)

	// IncrementEmojiUsage increments the usage count for an emoji
	IncrementEmojiUsage(ctx context.Context, shortcode string) error
}

EmojiRepository defines the interface for custom emoji operations. This handles custom emoji creation, retrieval, search, and usage tracking.

type ExportRepository

type ExportRepository interface {

	// CreateExport creates a new export record
	CreateExport(ctx context.Context, export *models.Export) error

	// GetExport retrieves an export by ID
	GetExport(ctx context.Context, exportID string) (*models.Export, error)

	// UpdateExportStatus updates the status and metadata of an export
	UpdateExportStatus(ctx context.Context, exportID, status string, completionData map[string]any, errorMsg string) error

	// GetExportsForUser retrieves all exports for a user
	GetExportsForUser(ctx context.Context, username string, limit int, cursor string) ([]*models.Export, string, error)

	// GetUserExportsByStatus retrieves exports for a user filtered by status
	GetUserExportsByStatus(ctx context.Context, username string, statuses []string) ([]*models.Export, error)

	// CreateExportCostTracking creates a new export cost tracking record
	CreateExportCostTracking(ctx context.Context, costTracking *models.ExportCostTracking) error

	// GetExportCostTracking retrieves export cost tracking records for an export
	GetExportCostTracking(ctx context.Context, exportID string) ([]*models.ExportCostTracking, error)

	// GetUserExportCosts retrieves export costs for a user within a date range
	GetUserExportCosts(ctx context.Context, username string, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)

	// GetExportCostsByDateRange retrieves export costs for all users within a date range
	GetExportCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)

	// GetExportCostSummary calculates cost summary for a user's exports
	GetExportCostSummary(ctx context.Context, username string, startDate, endDate time.Time) (*models.ExportCostSummary, error)

	// GetHighCostExports returns export operations that exceed a cost threshold
	GetHighCostExports(ctx context.Context, thresholdMicroCents int64, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)
}

ExportRepository defines the interface for export operations. This handles data export jobs, status tracking, and cost management.

type FeaturedTagRepository

type FeaturedTagRepository interface {

	// CreateFeaturedTag creates a new featured tag for a user
	CreateFeaturedTag(ctx context.Context, tag *storage.FeaturedTag) error

	// DeleteFeaturedTag removes a featured tag
	DeleteFeaturedTag(ctx context.Context, username, name string) error

	// GetFeaturedTags returns all featured tags for a user
	GetFeaturedTags(ctx context.Context, username string) ([]*storage.FeaturedTag, error)

	// GetTagSuggestions returns suggested tags based on user's usage
	GetTagSuggestions(ctx context.Context, username string, limit int) ([]string, error)
}

FeaturedTagRepository defines the interface for featured tag operations. This handles user-featured hashtags for profile display and tag suggestions.

type FederationRepository

type FederationRepository interface {

	// GetInstanceInfo retrieves information about a federated instance
	GetInstanceInfo(ctx context.Context, domain string) (*storage.InstanceInfo, error)

	// UpsertInstanceInfo creates or updates instance information
	UpsertInstanceInfo(ctx context.Context, info *storage.InstanceInfo) error

	// GetKnownInstances retrieves a list of known federated instances
	GetKnownInstances(ctx context.Context, limit int, cursor string) ([]*storage.InstanceInfo, string, error)

	// GetFederationStatistics retrieves federation statistics for a time range
	GetFederationStatistics(ctx context.Context, startTime, endTime time.Time) (*storage.FederationStats, error)

	// GetInstanceStats retrieves comprehensive statistics for a specific instance
	GetInstanceStats(ctx context.Context, domain string) (*storage.InstanceStats, error)

	// RecordFederationActivity records a single federation activity for cost tracking
	RecordFederationActivity(ctx context.Context, activity *storage.FederationActivity) error

	// GetFederationCosts retrieves aggregated federation costs
	GetFederationCosts(ctx context.Context, startTime, endTime time.Time, limit int, cursor string) ([]*storage.FederationCost, string, error)

	// GetInstanceHealthReport generates a health report for a specific instance
	GetInstanceHealthReport(ctx context.Context, domain string, period time.Duration) (*storage.InstanceHealthReport, error)

	// GetCostProjections generates cost projections based on historical data
	GetCostProjections(ctx context.Context, period string) (*storage.CostProjection, error)

	// GetFederationNodes retrieves federation nodes up to a certain depth
	GetFederationNodes(ctx context.Context, depth int) ([]*storage.FederationNode, error)

	// GetFederationNodesByHealth retrieves federation nodes filtered by health status
	GetFederationNodesByHealth(ctx context.Context, healthStatus string, limit int) ([]*storage.FederationNode, error)

	// GetFederationEdges retrieves edges between specified domains
	GetFederationEdges(ctx context.Context, domains []string) ([]*storage.FederationEdge, error)

	// GetInstanceMetadata retrieves metadata for a specific instance
	GetInstanceMetadata(ctx context.Context, domain string) (*storage.InstanceMetadata, error)

	// CalculateFederationClusters calculates instance clusters based on connections
	CalculateFederationClusters(ctx context.Context) ([]*storage.InstanceCluster, error)
}

FederationRepository defines the interface for federation tracking operations. This handles federated instance information, statistics, and cost tracking.

type FilterRepository

type FilterRepository interface {
	// Core filter operations
	CreateFilter(ctx context.Context, filter *models.Filter) error
	GetFilter(ctx context.Context, filterID string) (*models.Filter, error)
	UpdateFilter(ctx context.Context, filter *models.Filter) error
	DeleteFilter(ctx context.Context, filterID string) error

	// User filter management
	GetUserFilters(ctx context.Context, username string) ([]*models.Filter, error)
	GetActiveFilters(ctx context.Context, username string, context []string) ([]*models.Filter, error)

	// Filter keyword operations
	AddFilterKeyword(ctx context.Context, keyword *models.FilterKeyword) error
	RemoveFilterKeyword(ctx context.Context, keywordID string) error
	GetFilterKeywords(ctx context.Context, filterID string) ([]*models.FilterKeyword, error)

	// Filter status operations
	AddFilterStatus(ctx context.Context, filterStatus *models.FilterStatus) error
	RemoveFilterStatus(ctx context.Context, filterStatusID string) error
	GetFilterStatuses(ctx context.Context, filterID string) ([]*models.FilterStatus, error)

	// Content filtering evaluation
	EvaluateFilters(ctx context.Context, username string, content string, context []string) ([]*models.Filter, error)
	CheckContentFiltered(ctx context.Context, username, statusID string, context []string) (bool, []*models.Filter, error)
}

FilterRepository defines the interface for content filter operations This handles user-defined content filtering rules

type HashtagRepository

type HashtagRepository interface {
	// IndexHashtag indexes a hashtag when used in a status
	IndexHashtag(ctx context.Context, hashtag string, statusID string, authorID string, visibility string) error

	// IndexStatusHashtags indexes a status with its hashtags for efficient search
	IndexStatusHashtags(ctx context.Context, statusID string, authorID string, authorHandle string, statusURL string, content string, hashtags []string, published time.Time, visibility string) error

	// RemoveStatusFromHashtagIndex removes a status from all hashtag indexes
	RemoveStatusFromHashtagIndex(ctx context.Context, statusID string) error

	// GetHashtagInfo retrieves information about a specific hashtag
	GetHashtagInfo(ctx context.Context, hashtag string) (*storage.Hashtag, error)

	// GetHashtagUsageHistory retrieves recent usage history for a hashtag
	GetHashtagUsageHistory(ctx context.Context, hashtag string, days int) ([]int64, error)

	// GetHashtagActivity retrieves activities for a hashtag since a specific time
	GetHashtagActivity(ctx context.Context, hashtag string, since time.Time) ([]*storage.Activity, error)

	// GetHashtagStats retrieves hashtag statistics
	GetHashtagStats(ctx context.Context, hashtag string) (any, error)

	// GetHashtagTimelineAdvanced retrieves hashtag timeline with advanced filtering
	GetHashtagTimelineAdvanced(ctx context.Context, hashtag string, maxID *string, limit int, visibility string) ([]*storage.StatusSearchResult, error)

	// GetMultiHashtagTimeline retrieves timeline for multiple hashtags
	GetMultiHashtagTimeline(ctx context.Context, hashtags []string, maxID *string, limit int, userID string) ([]*storage.StatusSearchResult, error)

	// GetSuggestedHashtags gets suggested hashtags for a user
	GetSuggestedHashtags(ctx context.Context, userID string, limit int) ([]*storage.HashtagSearchResult, error)

	// FollowHashtag creates a hashtag follow relationship
	FollowHashtag(ctx context.Context, userID, hashtag string) error

	// UnfollowHashtag removes a hashtag follow relationship
	UnfollowHashtag(ctx context.Context, userID, hashtag string) error

	// IsFollowingHashtag checks if a user is following a hashtag
	IsFollowingHashtag(ctx context.Context, userID, hashtag string) (bool, error)

	// GetHashtagFollow retrieves the hashtag follow record for a user
	GetHashtagFollow(ctx context.Context, userID string, hashtag string) (*models.HashtagFollow, error)

	// GetHashtagMute retrieves the hashtag mute record for a user
	GetHashtagMute(ctx context.Context, userID string, hashtag string) (*models.HashtagMute, error)
}

HashtagRepository defines the interface for hashtag operations. This handles hashtag indexing, trending, and user hashtag follows.

type ImportRepository

type ImportRepository interface {

	// CreateImport creates a new import record
	CreateImport(ctx context.Context, importRecord *models.Import) error

	// GetImport retrieves an import by ID
	GetImport(ctx context.Context, importID string) (*models.Import, error)

	// UpdateImportStatus updates the status and metadata of an import
	UpdateImportStatus(ctx context.Context, importID, status string, completionData map[string]any, errorMsg string) error

	// UpdateImportProgress updates the progress of an import
	UpdateImportProgress(ctx context.Context, importID string, progress int) error

	// GetImportsForUser retrieves all imports for a user
	GetImportsForUser(ctx context.Context, username string, limit int, cursor string) ([]*models.Import, string, error)

	// GetUserImportsByStatus retrieves imports for a user filtered by status
	GetUserImportsByStatus(ctx context.Context, username string, statuses []string) ([]*models.Import, error)

	// CreateImportCostTracking creates a new import cost tracking record
	CreateImportCostTracking(ctx context.Context, costTracking *models.ImportCostTracking) error

	// GetImportCostTracking retrieves import cost tracking records for an import
	GetImportCostTracking(ctx context.Context, importID string) ([]*models.ImportCostTracking, error)

	// GetUserImportCosts retrieves import costs for a user within a date range
	GetUserImportCosts(ctx context.Context, username string, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

	// GetImportCostsByDateRange retrieves import costs for all users within a date range
	GetImportCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

	// GetImportCostSummary calculates cost summary for a user's imports
	GetImportCostSummary(ctx context.Context, username string, startDate, endDate time.Time) (*models.ImportCostSummary, error)

	// GetHighCostImports returns import operations that exceed a cost threshold
	GetHighCostImports(ctx context.Context, thresholdMicroCents int64, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

	// CreateImportBudget creates a new import budget configuration
	CreateImportBudget(ctx context.Context, budget *models.ImportBudget) error

	// UpdateImportBudget updates an existing import budget
	UpdateImportBudget(ctx context.Context, budget *models.ImportBudget) error

	// GetImportBudget retrieves import budget configuration for a user
	GetImportBudget(ctx context.Context, username, period string) (*models.ImportBudget, error)

	// CheckBudgetLimits checks if a user is within their budget limits
	CheckBudgetLimits(ctx context.Context, username string, importCostMicroCents, exportCostMicroCents int64) (*models.ImportBudget, bool, error)

	// UpdateBudgetUsage updates the current usage for a user's budget
	UpdateBudgetUsage(ctx context.Context, username, period string, importCostMicroCents, exportCostMicroCents int64) error
}

ImportRepository defines the interface for import operations. This handles data import jobs, status tracking, progress updates, and budget management.

type InstanceRepository

type InstanceRepository interface {

	// GetInstanceState returns the current instance activation state
	GetInstanceState(ctx context.Context) (*models.InstanceState, error)

	// EnsureInstanceState ensures the instance state record exists and returns it
	EnsureInstanceState(ctx context.Context) (*models.InstanceState, error)

	// SetInstanceLocked updates the instance lock state
	SetInstanceLocked(ctx context.Context, locked bool) error

	// SetBootstrapWalletAddress sets the bootstrap wallet address used for setup authentication
	SetBootstrapWalletAddress(ctx context.Context, address string) error

	// SetPrimaryAdminUsername records the primary admin username created during setup
	SetPrimaryAdminUsername(ctx context.Context, username string) error

	// GetAgentInstanceConfig returns the current instance agent policy.
	GetAgentInstanceConfig(ctx context.Context) (*models.AgentInstanceConfig, error)

	// EnsureAgentInstanceConfig ensures the instance agent policy record exists and returns it.
	EnsureAgentInstanceConfig(ctx context.Context) (*models.AgentInstanceConfig, error)

	// SetAgentInstanceConfig updates the instance agent policy.
	SetAgentInstanceConfig(ctx context.Context, cfg *models.AgentInstanceConfig) error

	// GetInstanceRules retrieves the instance rules
	GetInstanceRules(ctx context.Context) ([]storage.InstanceRule, error)

	// SetInstanceRules updates the instance rules
	SetInstanceRules(ctx context.Context, rules []storage.InstanceRule) error

	// GetRulesByCategory retrieves rules filtered by category
	GetRulesByCategory(ctx context.Context, category string) ([]storage.InstanceRule, error)

	// GetExtendedDescription retrieves the instance extended description
	GetExtendedDescription(ctx context.Context) (string, time.Time, error)

	// SetExtendedDescription updates the instance extended description
	SetExtendedDescription(ctx context.Context, description string) error

	// GetTotalUserCount returns the total number of users
	GetTotalUserCount(ctx context.Context) (int64, error)

	// GetTotalStatusCount returns the total number of statuses
	GetTotalStatusCount(ctx context.Context) (int64, error)

	// GetTotalDomainCount returns the total number of known domains
	GetTotalDomainCount(ctx context.Context) (int64, error)

	// GetActiveUserCount returns the number of active users in the last N days
	GetActiveUserCount(ctx context.Context, days int) (int64, error)

	// GetDailyActiveUserCount returns the number of daily active users
	GetDailyActiveUserCount(ctx context.Context) (int64, error)

	// GetLocalPostCount returns the number of local posts
	GetLocalPostCount(ctx context.Context) (int64, error)

	// GetLocalCommentCount returns the number of local comments
	GetLocalCommentCount(ctx context.Context) (int64, error)

	// GetWeeklyActivity retrieves weekly activity data for a specific week
	GetWeeklyActivity(ctx context.Context, weekTimestamp int64) (*storage.WeeklyActivity, error)

	// RecordActivity records activity data for analytics
	RecordActivity(ctx context.Context, activityType string, userID string, timestamp time.Time) error

	// GetContactAccount returns the contact account for the instance
	GetContactAccount(ctx context.Context) (*storage.ActorRecord, error)

	// GetStorageUsage returns current storage usage statistics
	GetStorageUsage(ctx context.Context) (any, error)

	// GetStorageHistory returns storage usage history for the last N days
	GetStorageHistory(ctx context.Context, days int) ([]any, error)

	// GetUserGrowthHistory returns user growth data for the last N days
	GetUserGrowthHistory(ctx context.Context, days int) ([]any, error)

	// GetDomainStats returns statistics for a specific domain
	GetDomainStats(ctx context.Context, domain string) (any, error)

	// RecordDailyMetrics records daily historical metrics for the instance
	RecordDailyMetrics(ctx context.Context, date string, metrics map[string]interface{}) error

	// GetMetricsSummary returns aggregated metrics for a given time range
	GetMetricsSummary(ctx context.Context, timeRange string) (map[string]interface{}, error)
}

InstanceRepository defines the interface for instance configuration and metrics operations. This handles instance settings, rules, metrics, and activity tracking.

type LikeRepository

type LikeRepository interface {
	// CreateLike creates a new like
	CreateLike(ctx context.Context, actor, object, statusAuthorID string) (*models.Like, error)

	// DeleteLike removes a like
	DeleteLike(ctx context.Context, actor, object string) error

	// GetLike retrieves a specific like
	GetLike(ctx context.Context, actor, object string) (*models.Like, error)

	// GetObjectLikes retrieves all likes for an object with pagination
	GetObjectLikes(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Like, string, error)

	// GetActorLikes retrieves all likes by an actor with pagination
	GetActorLikes(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Like, string, error)

	// CountActorLikes returns the total number of likes by an actor
	CountActorLikes(ctx context.Context, actorID string) (int64, error)

	// HasLiked checks if an actor has liked an object
	HasLiked(ctx context.Context, actor, object string) (bool, error)

	// CascadeDeleteLikes deletes all likes for an object
	CascadeDeleteLikes(ctx context.Context, objectID string) error

	// TombstoneObject creates a tombstone for a deleted object
	TombstoneObject(ctx context.Context, objectID string, deletedBy string) error

	// GetTombstone retrieves a tombstone by object ID
	GetTombstone(ctx context.Context, objectID string) (*storage.Tombstone, error)

	// GetLikeCount counts likes for a status
	GetLikeCount(ctx context.Context, statusID string) (int64, error)

	// GetBoostCount counts boosts/announces for a status
	GetBoostCount(ctx context.Context, statusID string) (int64, error)

	// IncrementReblogCount increments the reblog count on a status
	IncrementReblogCount(ctx context.Context, objectID string) error

	// HasReblogged checks if a user has reblogged/boosted a specific status
	HasReblogged(ctx context.Context, actorID, statusID string) (bool, error)

	// CountForObject provides Storage interface compatibility for CountObjectLikes
	CountForObject(ctx context.Context, objectID string) (int64, error)

	// GetForObject provides Storage interface compatibility for GetObjectLikes
	GetForObject(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Like, string, error)

	// GetLikedObjects provides Storage interface compatibility
	GetLikedObjects(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Like, string, error)
}

LikeRepository defines the interface for like operations. This handles likes/favorites for statuses and other content.

type ListRepository

type ListRepository interface {
	// Core list operations
	CreateList(ctx context.Context, list *models.List) error
	GetList(ctx context.Context, listID string) (*models.List, error)
	UpdateList(ctx context.Context, list *models.List) error
	DeleteList(ctx context.Context, listID string) error

	// User list management
	GetUserLists(ctx context.Context, username string, opts PaginationOptions) (*PaginatedResult[*models.List], error)
	GetListsByMember(ctx context.Context, memberUsername string, opts PaginationOptions) (*PaginatedResult[*models.List], error)
	GetListsForUser(ctx context.Context, username string) ([]*storage.List, error)
	GetListsForUserPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.List, string, error)
	CountUserLists(ctx context.Context, username string) (int, error)

	// List membership operations
	AddListMember(ctx context.Context, listID, memberUsername string) error
	RemoveListMember(ctx context.Context, listID, memberUsername string) error
	GetListMembers(ctx context.Context, listID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)
	IsListMember(ctx context.Context, listID, memberUsername string) (bool, error)
	CountListMembers(ctx context.Context, listID string) (int, error)

	// Account list operations
	GetAccountLists(ctx context.Context, accountID string) ([]*storage.List, error)
	GetAccountListsPaginated(ctx context.Context, accountID string, limit int, cursor string) ([]*storage.List, string, error)
	GetAccountListsForUser(ctx context.Context, accountID, username string) ([]*storage.List, error)
	RemoveAccountFromAllLists(ctx context.Context, accountID string) error

	// Exclusive lists
	GetExclusiveLists(ctx context.Context, username string) ([]*storage.List, error)

	// Batch operations
	AddAccountsToList(ctx context.Context, listID string, accountIDs []string) error
	RemoveAccountsFromList(ctx context.Context, listID string, accountIDs []string) error
	GetListAccounts(ctx context.Context, listID string) ([]string, error)
	GetListsContainingAccount(ctx context.Context, accountID, username string) ([]*storage.List, error)

	// List timeline operations
	GetListTimeline(ctx context.Context, listID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetListStatuses(ctx context.Context, listID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
}

ListRepository defines the interface for user list operations. This handles Mastodon-style user-created lists for timeline organization.

type MarkerRepository

type MarkerRepository interface {
	// SaveMarker saves or updates a timeline position marker
	SaveMarker(ctx context.Context, username, timeline string, lastReadID string, version int) error

	// GetMarkers retrieves timeline position markers for specified timelines
	GetMarkers(ctx context.Context, username string, timelines []string) (map[string]*storage.Marker, error)
}

MarkerRepository defines the interface for timeline position marker operations. This handles saving and retrieving read position markers for timelines.

type MediaAnalyticsRepository

type MediaAnalyticsRepository interface {
	// Core analytics operations
	RecordMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error
	GetMediaAnalyticsByID(ctx context.Context, format string, timestamp time.Time, mediaID string) (*models.MediaAnalytics, error)
	UpdateMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error
	StoreMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error

	// Analytics queries by date and variant
	GetMediaAnalyticsByDate(ctx context.Context, date string) ([]*models.MediaAnalytics, error)
	GetMediaAnalyticsByVariant(ctx context.Context, variantKey string) ([]*models.MediaAnalytics, error)
	GetMediaAnalyticsByTimeRange(ctx context.Context, mediaID string, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)
	GetAllMediaAnalyticsByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)

	// Cost and summary operations
	GetDailyCostSummary(ctx context.Context, date string) (map[string]interface{}, error)
	GetTopVariantsByDemand(ctx context.Context, date string, limit int) ([]map[string]interface{}, error)

	// Media view and behavior tracking
	RecordMediaView(ctx context.Context, mediaID, userID string, duration time.Duration, quality string) error
	TrackUserBehavior(ctx context.Context, userID string, behaviorData map[string]interface{}) error

	// Popularity and metrics
	CalculatePopularityMetrics(ctx context.Context, mediaID string, days int) (map[string]interface{}, error)
	GetMediaMetricsForDate(ctx context.Context, mediaID, date string) (map[string]interface{}, error)

	// Reporting and recommendations
	GenerateAnalyticsReport(ctx context.Context, startDate, endDate string) (map[string]interface{}, error)
	GetContentRecommendations(ctx context.Context, userID string, limit int) ([]map[string]interface{}, error)

	// Bandwidth and popular media queries
	GetBandwidthByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)
	GetPopularMedia(ctx context.Context, startTime, endTime time.Time, limit int, cursor *string) ([]*models.MediaAnalytics, error)

	// Cleanup operations
	CleanupOldAnalytics(ctx context.Context, olderThan time.Duration) error
}

MediaAnalyticsRepository defines the interface for media analytics operations. This handles media streaming analytics with variant-level cost attribution.

type MediaMetadataRepository

type MediaMetadataRepository interface {
	// Core metadata operations
	CreateMediaMetadata(ctx context.Context, metadata *models.MediaMetadata) error
	GetMediaMetadata(ctx context.Context, mediaID string) (*models.MediaMetadata, error)
	UpdateMediaMetadata(ctx context.Context, metadata *models.MediaMetadata) error
	DeleteMediaMetadata(ctx context.Context, mediaID string) error

	// Status-based queries
	GetMediaMetadataByStatus(ctx context.Context, status string, limit int) ([]*models.MediaMetadata, error)
	GetPendingMediaMetadata(ctx context.Context, limit int) ([]*models.MediaMetadata, error)
	GetProcessingMediaMetadata(ctx context.Context, limit int) ([]*models.MediaMetadata, error)

	// Processing status updates
	MarkProcessingStarted(ctx context.Context, mediaID string) error
	MarkProcessingComplete(ctx context.Context, mediaID string, result ProcessingResult) error
	MarkProcessingFailed(ctx context.Context, mediaID string, errorMsg string) error

	// Cleanup operations
	CleanupExpiredMetadata(ctx context.Context) error
}

MediaMetadataRepository defines the interface for media metadata operations. This handles media processing metadata, status tracking, and cleanup.

type MediaPopularityRepository

type MediaPopularityRepository interface {
	// Core popularity operations
	UpsertPopularity(ctx context.Context, popularity *models.MediaPopularity) error
	GetPopularityForMedia(ctx context.Context, mediaID, period string) (*models.MediaPopularity, error)

	// Popular media queries
	GetPopularMediaByPeriod(ctx context.Context, period string, limit int, cursor *string) ([]*models.MediaPopularity, error)

	// View count operations
	IncrementViewCount(ctx context.Context, mediaID, period string, incrementBy int64) error
}

MediaPopularityRepository defines the interface for media popularity operations. This handles aggregated popularity metrics for media items.

type MediaRepository

type MediaRepository interface {
	// Core media operations
	CreateMedia(ctx context.Context, media *models.Media) error
	GetMedia(ctx context.Context, mediaID string) (*models.Media, error)
	UpdateMedia(ctx context.Context, media *models.Media) error
	DeleteMedia(ctx context.Context, mediaID string) error

	// Media queries
	GetMediaByUser(ctx context.Context, userID string, limit int) ([]*models.Media, error)
	GetMediaByStatus(ctx context.Context, status string, limit int) ([]*models.Media, error)
	GetMediaByContentType(ctx context.Context, contentType string, limit int) ([]*models.Media, error)
	GetUserMediaLegacy(ctx context.Context, username string) ([]any, error)

	// User media queries (paginated)
	GetUserMedia(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Media], error)
	GetUserMediaByType(ctx context.Context, userID, contentType string, opts PaginationOptions) (*PaginatedResult[*models.Media], error)
	GetUnusedMedia(ctx context.Context, olderThan time.Time, opts PaginationOptions) (*PaginatedResult[*models.Media], error)

	// Media processing
	MarkMediaProcessing(ctx context.Context, mediaID string) error
	MarkMediaReady(ctx context.Context, mediaID string) error
	MarkMediaFailed(ctx context.Context, mediaID, errorMsg string) error
	GetPendingMedia(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Media], error)
	GetProcessingMedia(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Media], error)

	// Media variants and thumbnails
	AddMediaVariant(ctx context.Context, mediaID, variantName string, variant models.MediaVariant) error
	GetMediaVariant(ctx context.Context, mediaID, variantName string) (*models.MediaVariant, error)
	DeleteMediaVariant(ctx context.Context, mediaID, variantName string) error

	// Media attachment updates
	UpdateMediaAttachment(ctx context.Context, mediaID string, updates map[string]any) error
	UnmarkAllMediaAsSensitive(ctx context.Context, username string) error

	// Media usage tracking
	MarkMediaUsed(ctx context.Context, mediaID string) error
	GetMediaUsageStats(ctx context.Context, mediaID string) (usageCount int, lastUsed *time.Time, err error)

	// Content moderation
	SetMediaModeration(ctx context.Context, mediaID string, isNSFW bool, score float64, labels []string) error
	GetModerationPendingMedia(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Media], error)

	// Batch operations
	GetMediaByIDs(ctx context.Context, mediaIDs []string) ([]*models.Media, error)
	DeleteExpiredMedia(ctx context.Context, expiredBefore time.Time) (int64, error)

	// Storage and CDN operations
	GetMediaStorageUsage(ctx context.Context, userID string) (int64, error)
	GetTotalStorageUsage(ctx context.Context) (int64, error)

	// Media job operations
	CreateMediaJob(ctx context.Context, job *models.MediaJob) error
	GetMediaJob(ctx context.Context, jobID string) (*models.MediaJob, error)
	UpdateMediaJob(ctx context.Context, job *models.MediaJob) error
	DeleteMediaJob(ctx context.Context, jobID string) error
	GetJobsByStatus(ctx context.Context, status string, limit int) ([]*models.MediaJob, error)
	GetJobsByUser(ctx context.Context, username string, limit int) ([]*models.MediaJob, error)

	// User media configuration
	CreateUserMediaConfig(ctx context.Context, config *models.UserMediaConfig) error
	GetUserMediaConfig(ctx context.Context, userID string) (*models.UserMediaConfig, error)
	GetUserMediaConfigByUsername(ctx context.Context, username string) (*models.UserMediaConfig, error)
	UpdateUserMediaConfig(ctx context.Context, config *models.UserMediaConfig) error
	DeleteUserMediaConfig(ctx context.Context, userID string) error

	// Media spending tracking
	CreateMediaSpending(ctx context.Context, spending *models.MediaSpending) error
	GetMediaSpending(ctx context.Context, userID, period string) (*models.MediaSpending, error)
	UpdateMediaSpending(ctx context.Context, spending *models.MediaSpending) error
	GetMediaSpendingByTimeRange(ctx context.Context, userID string, periodType string, limit int) ([]*models.MediaSpending, error)
	GetOrCreateMediaSpending(ctx context.Context, userID, period, periodType string) (*models.MediaSpending, error)

	// Spending transactions
	CreateMediaSpendingTransaction(ctx context.Context, transaction *models.MediaSpendingTransaction) error
	GetMediaSpendingTransactions(ctx context.Context, userID string, limit int) ([]*models.MediaSpendingTransaction, error)
	AddSpendingTransaction(ctx context.Context, transaction *models.MediaSpendingTransaction) error

	// Transcoding job operations
	CreateTranscodingJob(ctx context.Context, job *models.TranscodingJob) error
	GetTranscodingJob(ctx context.Context, jobID string) (*models.TranscodingJob, error)
	UpdateTranscodingJob(ctx context.Context, job *models.TranscodingJob) error
	GetTranscodingJobsByUser(ctx context.Context, userID string, limit int) ([]*models.TranscodingJob, error)
	GetTranscodingJobsByMedia(ctx context.Context, mediaID string, limit int) ([]*models.TranscodingJob, error)
	GetTranscodingJobsByStatus(ctx context.Context, status string, limit int) ([]*models.TranscodingJob, error)
	DeleteTranscodingJob(ctx context.Context, jobID string) error
	GetTranscodingCostsByUser(ctx context.Context, userID string, timeRange string) (map[string]int64, error)

	// Dependencies
	SetDependencies(deps map[string]interface{})
}

MediaRepository defines the interface for media/attachment operations. This handles file uploads, processing, and CDN management.

type MediaRepositoryInterface

type MediaRepositoryInterface interface {
	GetMedia(ctx context.Context, mediaID string) (*models.Media, error)
}

MediaRepositoryInterface defines the interface for media operations needed by scheduled status

type MediaSessionRepository

type MediaSessionRepository interface {
	// Session lifecycle operations
	StartStreamingSession(ctx context.Context, userID, mediaID string, format types.MediaFormat, quality types.Quality) (*types.StreamingSession, error)
	EndStreamingSession(ctx context.Context, sessionID string) error
	UpdateStreamingMetrics(ctx context.Context, sessionID string, segmentIndex int, bytesTransferred int64, bufferHealth float64, currentQuality types.Quality) error

	// Legacy session operations
	CreateSession(ctx context.Context, session *types.StreamingSession) error
	GetSession(ctx context.Context, sessionID string) (*types.StreamingSession, error)
	UpdateSession(ctx context.Context, session *types.StreamingSession) error
	EndSession(ctx context.Context, sessionID string) error

	// Session queries
	GetActiveStreams(ctx context.Context, limit int) ([]*types.StreamingSession, error)
	GetUserSessions(ctx context.Context, userID string) ([]*types.StreamingSession, error)
	GetMediaSessions(ctx context.Context, mediaID string, limit int32) ([]*types.StreamingSession, error)
	GetSessionsByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int32) ([]*types.StreamingSession, error)

	// Session validation and access
	ValidateSessionAccess(ctx context.Context, sessionID, userID string) (bool, error)

	// Session analytics and monitoring
	GetActiveSessionsCount(ctx context.Context) (int, error)

	// Session cleanup
	CleanupExpiredSessions(ctx context.Context, maxAge time.Duration) error

	// Session TTL configuration
	SetSessionTTL(ttl time.Duration)
}

MediaSessionRepository defines the interface for media streaming session operations. This handles session management for streaming media.

type MetricRecordRepository

type MetricRecordRepository interface {

	// CreateMetricRecord creates a new metric record
	CreateMetricRecord(ctx context.Context, record *models.MetricRecord) error

	// BatchCreateMetricRecords creates multiple metric records efficiently
	BatchCreateMetricRecords(ctx context.Context, records []*models.MetricRecord) error

	// GetMetricRecord retrieves a single metric record by its keys
	GetMetricRecord(ctx context.Context, metricType, bucket, timestamp string) (*models.MetricRecord, error)

	// UpdateMetricRecord updates an existing metric record
	UpdateMetricRecord(ctx context.Context, record *models.MetricRecord) error

	// DeleteMetricRecord deletes a metric record by its keys
	DeleteMetricRecord(ctx context.Context, metricType, bucket, timestamp string) error

	// GetMetricsByService queries metrics by service within a time range using GSI1
	GetMetricsByService(ctx context.Context, serviceName string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

	// GetMetricsByType queries metrics by type within a time range using GSI2
	GetMetricsByType(ctx context.Context, metricType string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

	// GetMetricsByDate queries metrics by date and service using GSI3
	GetMetricsByDate(ctx context.Context, date time.Time, serviceName string) ([]*models.MetricRecord, error)

	// GetMetricsByAggregationLevel queries metrics by aggregation level within a time range using GSI4
	GetMetricsByAggregationLevel(ctx context.Context, level string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

	// GetServiceMetricsStats calculates statistics for a service's metrics
	GetServiceMetricsStats(ctx context.Context, serviceName string, metricType string, startTime, endTime time.Time) (*MetricRecordStats, error)
}

MetricRecordRepository defines the interface for metric record operations. This handles new reporting table schema with extensive indexing for metrics storage.

type MetricRecordStats

type MetricRecordStats struct {
	Service    string
	Type       string
	StartTime  time.Time
	EndTime    time.Time
	Count      int
	TotalCount int64
	TotalSum   float64
	Average    float64
	Min        float64
	Max        float64
}

MetricRecordStats represents statistics for metric records.

type MetricsConfig

type MetricsConfig struct {
	// EnableMetrics enables metrics collection and reporting
	EnableMetrics bool

	// MetricsPrefix is the prefix for all metric names
	MetricsPrefix string

	// EnableDetailedMetrics enables detailed operation-level metrics
	EnableDetailedMetrics bool

	// MetricsInterval is the interval for metrics aggregation and reporting
	MetricsInterval time.Duration
}

MetricsConfig provides metrics and monitoring configuration

type MigrationInfo

type MigrationInfo struct {
	AlsoKnownAs []string `json:"also_known_as"`
	MovedTo     string   `json:"moved_to,omitempty"`
}

MigrationInfo represents account migration information

type ModerationMLRepository

type ModerationMLRepository interface {

	// CreateSample creates a new moderation training sample
	CreateSample(ctx context.Context, sample *models.ModerationSample) error

	// GetSample retrieves a sample by ID
	GetSample(ctx context.Context, sampleID string) (*models.ModerationSample, error)

	// ListSamplesByLabel retrieves samples with a specific label
	ListSamplesByLabel(ctx context.Context, label string, limit int) ([]*models.ModerationSample, error)

	// ListSamplesByReviewer retrieves samples submitted by a specific reviewer
	ListSamplesByReviewer(ctx context.Context, reviewerID string, limit int) ([]*models.ModerationSample, error)

	// CreateModelVersion creates a new model version record
	CreateModelVersion(ctx context.Context, version *models.ModerationModelVersion) error

	// GetModelVersion retrieves a model version by ID
	GetModelVersion(ctx context.Context, versionID string) (*models.ModerationModelVersion, error)

	// GetActiveModelVersion retrieves the currently active model version
	GetActiveModelVersion(ctx context.Context) (*models.ModerationModelVersion, error)

	// UpdateModelVersion updates an existing model version
	UpdateModelVersion(ctx context.Context, version *models.ModerationModelVersion) error

	// CreateEffectivenessMetric creates a new effectiveness metric record
	CreateEffectivenessMetric(ctx context.Context, metric *models.ModerationEffectivenessMetric) error

	// GetEffectivenessMetric retrieves effectiveness metrics for a pattern/period
	GetEffectivenessMetric(ctx context.Context, patternID, period string, startTime time.Time) (*models.ModerationEffectivenessMetric, error)

	// ListEffectivenessMetricsByPattern retrieves all metrics for a pattern
	ListEffectivenessMetricsByPattern(ctx context.Context, patternID string, limit int) ([]*models.ModerationEffectivenessMetric, error)

	// ListEffectivenessMetricsByPeriod retrieves top-performing patterns for a period
	ListEffectivenessMetricsByPeriod(ctx context.Context, period string, limit int) ([]*models.ModerationEffectivenessMetric, error)
}

ModerationMLRepository defines the interface for ML moderation data storage operations. This handles moderation samples, model versions, and effectiveness metrics.

type ModerationRepository

type ModerationRepository interface {

	// CreateModerationEvent creates a new moderation event
	CreateModerationEvent(ctx context.Context, event *storage.ModerationEvent) error

	// GetModerationEvent retrieves a moderation event by ID
	GetModerationEvent(ctx context.Context, eventID string) (*storage.ModerationEvent, error)

	// GetModerationEvents retrieves moderation events with optional filters
	GetModerationEvents(ctx context.Context, filter *storage.ModerationEventFilter, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

	// GetModerationEventsByObject retrieves all moderation events for an object
	GetModerationEventsByObject(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

	// GetModerationEventsByActor retrieves all moderation events created by an actor
	GetModerationEventsByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

	// GetModerationQueue retrieves pending moderation events
	GetModerationQueue(ctx context.Context, filter *storage.ModerationFilter) ([]*storage.ModerationQueueItem, error)

	// GetModerationQueuePaginated retrieves pending moderation events with pagination
	GetModerationQueuePaginated(ctx context.Context, limit int, cursor string) ([]*storage.ModerationQueueItem, string, error)

	// GetModerationQueueCount returns the count of items in the moderation queue
	GetModerationQueueCount(ctx context.Context) (int, error)

	// AddModerationReview adds a review to a moderation event
	AddModerationReview(ctx context.Context, review *storage.ModerationReview) error

	// GetModerationReviews retrieves all reviews for a moderation event
	GetModerationReviews(ctx context.Context, eventID string) ([]*storage.ModerationReview, error)

	// CreateAdminReview creates an admin review that overrides consensus
	CreateAdminReview(ctx context.Context, eventID string, adminID string, action storage.ActionType, reason string) error

	// GetReviewerStats retrieves statistics for a reviewer
	GetReviewerStats(ctx context.Context, reviewerID string) (*storage.ReviewerStats, error)

	// CreateModerationDecision creates a consensus decision
	CreateModerationDecision(ctx context.Context, decision *storage.ModerationDecision) error

	// GetModerationDecision retrieves the current decision for an object
	GetModerationDecision(ctx context.Context, objectID string) (*storage.ModerationDecision, error)

	// StoreModerationDecision stores a moderation decision (alias for CreateModerationDecision)
	StoreModerationDecision(ctx context.Context, decision *storage.ModerationDecision) error

	// UpdateModerationDecision updates a moderation decision based on a review
	UpdateModerationDecision(ctx context.Context, contentID string, review *storage.ModerationReview) error

	// CreateModerationPattern creates a new moderation pattern
	CreateModerationPattern(ctx context.Context, pattern *storage.ModerationPattern) error

	// GetModerationPattern retrieves a specific moderation pattern
	GetModerationPattern(ctx context.Context, patternID string) (*storage.ModerationPattern, error)

	// GetModerationPatterns retrieves moderation patterns based on criteria
	GetModerationPatterns(ctx context.Context, active bool, severity string, limit int) ([]*storage.ModerationPattern, error)

	// UpdateModerationPattern updates an existing moderation pattern
	UpdateModerationPattern(ctx context.Context, pattern *storage.ModerationPattern) error

	// DeleteModerationPattern deletes a moderation pattern
	DeleteModerationPattern(ctx context.Context, patternID string) error

	// RecordPatternMatch records a moderation pattern match for analytics
	RecordPatternMatch(ctx context.Context, patternID string, matched bool, timestamp time.Time) error

	// GetModerationHistory retrieves the complete moderation history for an object
	GetModerationHistory(ctx context.Context, objectID string) (*storage.ModerationHistory, error)

	// CreateFilter creates a new filter
	CreateFilter(ctx context.Context, filter *storage.Filter) error

	// GetFilter retrieves a filter by ID
	GetFilter(ctx context.Context, filterID string) (*storage.Filter, error)

	// GetFiltersForUser retrieves all filters for a user
	GetFiltersForUser(ctx context.Context, username string) ([]*storage.Filter, error)

	// UpdateFilter updates a filter
	UpdateFilter(ctx context.Context, filterID string, updates map[string]any) error

	// DeleteFilter deletes a filter and all its associated keywords and statuses
	DeleteFilter(ctx context.Context, filterID string) error

	// AddFilterKeyword adds a new keyword to a filter
	AddFilterKeyword(ctx context.Context, filterID string, keyword *storage.FilterKeyword) error

	// GetFilterKeywords retrieves all keywords for a filter
	GetFilterKeywords(ctx context.Context, filterID string) ([]*storage.FilterKeyword, error)

	// UpdateFilterKeyword updates a filter keyword
	UpdateFilterKeyword(ctx context.Context, keywordID string, updates map[string]any) error

	// DeleteFilterKeyword deletes a filter keyword
	DeleteFilterKeyword(ctx context.Context, keywordID string) error

	// AddFilterStatus adds a new status to a filter
	AddFilterStatus(ctx context.Context, filterID string, status *storage.FilterStatus) error

	// GetFilterStatuses retrieves all statuses for a filter
	GetFilterStatuses(ctx context.Context, filterID string) ([]*storage.FilterStatus, error)

	// DeleteFilterStatus deletes a filter status
	DeleteFilterStatus(ctx context.Context, statusID string) error

	// CreateReport creates a new report
	CreateReport(ctx context.Context, report *storage.Report) error

	// GetReport retrieves a report by ID
	GetReport(ctx context.Context, id string) (*storage.Report, error)

	// GetUserReports retrieves all reports created by a user
	GetUserReports(ctx context.Context, username string, limit int, cursor string) ([]*storage.Report, string, error)

	// GetReportsByTarget retrieves reports targeting a specific account
	GetReportsByTarget(ctx context.Context, targetAccountID string, limit int, cursor string) ([]*storage.Report, string, error)

	// GetReportsByStatus retrieves reports with a specific status
	GetReportsByStatus(ctx context.Context, status storage.ReportStatus, limit int, cursor string) ([]*storage.Report, string, error)

	// UpdateReportStatus updates the status of a report
	UpdateReportStatus(ctx context.Context, id string, status storage.ReportStatus, actionTaken string, moderatorID string) error

	// AssignReport assigns a report to a moderator
	AssignReport(ctx context.Context, reportID string, assignedTo string) error

	// UnassignReport removes assignment from a report
	UnassignReport(ctx context.Context, reportID string) error

	// GetOpenReportsCount returns the count of open reports
	GetOpenReportsCount(ctx context.Context) (int, error)

	// GetReportedStatuses retrieves statuses associated with a report
	GetReportedStatuses(ctx context.Context, reportID string) ([]any, error)

	// GetReportStats retrieves reporting statistics for a user
	GetReportStats(ctx context.Context, username string) (*storage.ReportStats, error)

	// IncrementFalseReports increments the false report count for a user
	IncrementFalseReports(ctx context.Context, username string) error

	// CreateFlag creates a new flag
	CreateFlag(ctx context.Context, flag *storage.Flag) error

	// GetFlag retrieves a flag by ID
	GetFlag(ctx context.Context, id string) (*storage.Flag, error)

	// GetFlagsByObject retrieves all flags for a specific object
	GetFlagsByObject(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.Flag, string, error)

	// GetFlagsByActor retrieves all flags created by a specific actor
	GetFlagsByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.Flag, string, error)

	// GetPendingFlags retrieves all pending flags
	GetPendingFlags(ctx context.Context, limit int, cursor string) ([]*storage.Flag, string, error)

	// UpdateFlagStatus updates the status of a flag
	UpdateFlagStatus(ctx context.Context, id string, status storage.FlagStatus, reviewedBy string, reviewNote string) error

	// CountPendingFlags returns the count of pending flags
	CountPendingFlags(ctx context.Context) (int, error)

	// DeleteFlag removes a flag
	DeleteFlag(ctx context.Context, id string) error

	// CreateAuditLog creates a new audit log entry
	CreateAuditLog(ctx context.Context, auditLog *storage.AuditLog) error

	// GetAuditLogs retrieves audit log entries with pagination
	GetAuditLogs(ctx context.Context, limit int, cursor string) ([]*storage.AuditLog, string, error)

	// GetAuditLogsByAdmin retrieves audit log entries for a specific admin
	GetAuditLogsByAdmin(ctx context.Context, adminID string, limit int, cursor string) ([]*storage.AuditLog, string, error)

	// GetAuditLogsByTarget retrieves audit log entries for a specific target
	GetAuditLogsByTarget(ctx context.Context, targetID string, limit int, cursor string) ([]*storage.AuditLog, string, error)

	// GetPendingModerationCount returns the count of pending moderation tasks for a specific moderator
	GetPendingModerationCount(ctx context.Context, moderatorID string) (int, error)

	// StoreAnalysisResult stores detailed analysis results for audit/appeals
	StoreAnalysisResult(ctx context.Context, analysisData map[string]interface{}) error

	// StoreDecision stores a moderation decision with enforcement tracking
	StoreDecision(ctx context.Context, decisionData map[string]interface{}) error

	// GetReviewQueue retrieves review queue items with filtering
	GetReviewQueue(ctx context.Context, filters map[string]interface{}) ([]*models.ModerationReviewQueue, error)

	// GetDecisionHistory retrieves decision history for a specific content ID
	GetDecisionHistory(ctx context.Context, contentID string) ([]*models.ModerationDecisionResult, error)

	// UpdateEnforcementStatus updates the enforcement status of a decision
	UpdateEnforcementStatus(ctx context.Context, contentID, status string) error

	// GetModerationDecisionsByModerator retrieves moderation decisions made by a specific moderator
	GetModerationDecisionsByModerator(ctx context.Context, moderatorUsername string, limit int) ([]*models.ModerationReview, error)
}

ModerationRepository defines the interface for moderation operations. This handles moderation events, reviews, decisions, patterns, reports, flags, filters, and audit logs.

type MonthlyAggregate

type MonthlyAggregate struct {
	Year            int
	Month           int
	TotalCost       float64
	TotalOperations int64
}

MonthlyAggregate represents aggregated monthly costs

type NotificationDispatcher

type NotificationDispatcher interface {
	DispatchPushForNotification(ctx context.Context, notification *models.Notification)
}

NotificationDispatcher receives callbacks after notifications are persisted.

type NotificationRepository

type NotificationRepository interface {
	// Dispatcher configuration
	SetDispatcher(dispatcher NotificationDispatcher)

	// Core notification operations
	CreateNotification(ctx context.Context, notification *models.Notification) error
	GetNotification(ctx context.Context, notificationID string) (*models.Notification, error)
	UpdateNotification(ctx context.Context, notification *models.Notification) error
	DeleteNotification(ctx context.Context, notificationID string) error

	// User notification queries
	GetUserNotifications(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Notification], error)
	GetUnreadNotifications(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Notification], error)
	GetNotificationsByType(ctx context.Context, userID, notificationType string, opts PaginationOptions) (*PaginatedResult[*models.Notification], error)

	// Notification status management
	MarkNotificationRead(ctx context.Context, notificationID string) error
	MarkNotificationUnread(ctx context.Context, notificationID string) error
	MarkAllNotificationsRead(ctx context.Context, userID string) error
	MarkNotificationsReadByType(ctx context.Context, userID, notificationType string) error

	// Push notification tracking
	MarkNotificationPushSent(ctx context.Context, notificationID string) error
	MarkNotificationPushFailed(ctx context.Context, notificationID, errorMsg string) error
	GetPendingPushNotifications(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Notification], error)

	// Notification grouping and consolidation
	GetNotificationGroups(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Notification], error)
	ConsolidateNotifications(ctx context.Context, groupKey string) error

	// Notification counts and summaries
	GetUnreadNotificationCount(ctx context.Context, userID string) (int64, error)
	GetNotificationCountsByType(ctx context.Context, userID string) (map[string]int64, error)

	// Batch operations
	CreateNotifications(ctx context.Context, notifications []*models.Notification) error
	DeleteNotificationsByType(ctx context.Context, userID, notificationType string) error
	DeleteNotificationsByObject(ctx context.Context, objectID string) error
	DeleteExpiredNotifications(ctx context.Context, expiredBefore time.Time) (int64, error)

	// Filtered and advanced queries
	GetNotificationsFiltered(ctx context.Context, username string, filter map[string]interface{}) ([]*models.Notification, string, error)
	ClearOldNotifications(ctx context.Context, username string, olderThan time.Time) (int, error)
	GetNotificationsAdvanced(ctx context.Context, userID string, filters map[string]interface{}, pagination PaginationOptions) (*PaginatedResult[*models.Notification], error)

	// Notification preferences
	GetNotificationPreferences(ctx context.Context, userID string) (*models.NotificationPreferences, error)
	UpdateNotificationPreferences(ctx context.Context, prefs *models.NotificationPreferences) error
	SetNotificationPreference(ctx context.Context, userID string, preferenceType string, enabled bool) error
}

NotificationRepository defines the interface for notification operations This handles user notifications for various ActivityPub and app events

type OAuthRepository

type OAuthRepository interface {

	// StoreOAuthState stores OAuth state for CSRF protection
	StoreOAuthState(ctx context.Context, state string, data *storage.OAuthState) error

	// GetOAuthState retrieves OAuth state
	GetOAuthState(ctx context.Context, state string) (*storage.OAuthState, error)

	// DeleteOAuthState deletes OAuth state
	DeleteOAuthState(ctx context.Context, state string) error

	// CreateAuthorizationCode creates a new OAuth authorization code
	CreateAuthorizationCode(ctx context.Context, code *storage.AuthorizationCode) error

	// GetAuthorizationCode retrieves an OAuth authorization code
	GetAuthorizationCode(ctx context.Context, code string) (*storage.AuthorizationCode, error)

	// DeleteAuthorizationCode deletes an OAuth authorization code
	DeleteAuthorizationCode(ctx context.Context, code string) error

	// CreateRefreshToken creates a new OAuth refresh token
	CreateRefreshToken(ctx context.Context, token *storage.RefreshToken) error

	// GetRefreshToken retrieves an OAuth refresh token
	GetRefreshToken(ctx context.Context, token string) (*storage.RefreshToken, error)

	// DeleteRefreshToken deletes an OAuth refresh token
	DeleteRefreshToken(ctx context.Context, token string) error

	// CreateOAuthClient creates a new OAuth client
	CreateOAuthClient(ctx context.Context, client *storage.OAuthClient) error

	// GetOAuthClient retrieves an OAuth client by client ID
	GetOAuthClient(ctx context.Context, clientID string) (*storage.OAuthClient, error)

	// UpdateOAuthClient updates an existing OAuth client
	UpdateOAuthClient(ctx context.Context, clientID string, updates map[string]any) error

	// DeleteOAuthClient deletes an OAuth client
	DeleteOAuthClient(ctx context.Context, clientID string) error

	// ListOAuthClients lists OAuth clients with pagination
	ListOAuthClients(ctx context.Context, limit int32, cursor string) ([]*storage.OAuthClient, string, error)

	// DeleteExpiredTokens removes expired OAuth tokens
	DeleteExpiredTokens(ctx context.Context) error

	// SaveUserAppConsent saves user consent for an OAuth app
	SaveUserAppConsent(ctx context.Context, consent *storage.UserAppConsent) error

	// GetUserAppConsent retrieves user consent for an OAuth app
	GetUserAppConsent(ctx context.Context, userID, appID string) (*storage.UserAppConsent, error)
}

OAuthRepository defines the interface for OAuth-related storage operations. This handles OAuth 2.0 client management, authorization codes, tokens, and user consent.

type ObjectRepository

type ObjectRepository interface {

	// CreateObject stores a generic ActivityPub object
	CreateObject(ctx context.Context, object any) error

	// GetObject retrieves an object by ID
	GetObject(ctx context.Context, id string) (any, error)

	// UpdateObject updates an existing object
	UpdateObject(ctx context.Context, object any) error

	// UpdateObjectWithHistory updates an object and tracks the edit history
	UpdateObjectWithHistory(ctx context.Context, object any, updatedBy string) error

	// DeleteObject deletes an object by ID
	DeleteObject(ctx context.Context, objectID string) error

	// GetObjectsByActor retrieves objects created by a specific actor
	GetObjectsByActor(ctx context.Context, actorID string, cursor string, limit int) ([]any, string, error)

	// GetStatus retrieves a status by ID (alias for GetObject)
	GetStatus(ctx context.Context, statusID string) (any, error)

	// GetUserStatusCount counts the number of statuses by a user
	GetUserStatusCount(ctx context.Context, userID string) (int, error)

	// GetStatusReplyCount counts replies to a specific status
	GetStatusReplyCount(ctx context.Context, statusID string) (int, error)

	// CountObjectReplies counts the number of replies to an object
	CountObjectReplies(ctx context.Context, objectID string) (int, error)

	// CountReplies counts the number of replies to an object using GSI6
	CountReplies(ctx context.Context, objectID string) (int, error)

	// GetReplies retrieves replies to an object with pagination
	GetReplies(ctx context.Context, objectID string, limit int, cursor string) ([]any, string, error)

	// IncrementReplyCount increments the reply count for an object
	IncrementReplyCount(ctx context.Context, objectID string) error

	// GetReplyCount gets the reply count for a status
	GetReplyCount(ctx context.Context, statusID string) (int64, error)

	// TombstoneObject marks an object as deleted by creating a tombstone
	TombstoneObject(ctx context.Context, objectID string, deletedBy string) error

	// CreateTombstone creates a tombstone for a deleted object
	CreateTombstone(ctx context.Context, tombstone *models.Tombstone) error

	// GetTombstone retrieves a tombstone by object ID
	GetTombstone(ctx context.Context, objectID string) (*models.Tombstone, error)

	// IsTombstoned checks if an object has been tombstoned (deleted)
	IsTombstoned(ctx context.Context, objectID string) (bool, error)

	// GetTombstonesByActor retrieves all tombstones created by a specific actor
	GetTombstonesByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Tombstone, string, error)

	// GetTombstonesByType retrieves tombstones by their former type
	GetTombstonesByType(ctx context.Context, formerType string, limit int, cursor string) ([]*models.Tombstone, string, error)

	// CleanupExpiredTombstones removes tombstones that have exceeded their TTL
	CleanupExpiredTombstones(ctx context.Context, batchSize int) (int, error)

	// ReplaceObjectWithTombstone atomically replaces an object with a tombstone
	ReplaceObjectWithTombstone(ctx context.Context, objectID, formerType, deletedBy string) error

	// CreateUpdateHistory creates a new update history entry for an object
	CreateUpdateHistory(ctx context.Context, history *storage.UpdateHistory) error

	// GetUpdateHistory retrieves update history for an object
	GetUpdateHistory(ctx context.Context, objectID string, limit int) ([]*storage.UpdateHistory, error)

	// GetObjectHistory retrieves the version history of an object
	GetObjectHistory(ctx context.Context, objectID string) ([]*storage.UpdateHistory, error)

	// AddToCollection adds an item to a collection
	AddToCollection(ctx context.Context, collection string, item *storage.CollectionItem) error

	// RemoveFromCollection removes an item from a collection
	RemoveFromCollection(ctx context.Context, collection, itemID string) error

	// GetCollectionItems retrieves items from a collection with pagination
	GetCollectionItems(ctx context.Context, collection string, limit int, cursor string) ([]*storage.CollectionItem, string, error)

	// IsInCollection checks if an item is in a collection
	IsInCollection(ctx context.Context, collection, itemID string) (bool, error)

	// CountCollectionItems returns the count of items in a collection
	CountCollectionItems(ctx context.Context, collection string) (int, error)

	// CountQuotes counts the number of quotes for a specific note
	CountQuotes(ctx context.Context, noteID string) (int, error)

	// CountWithdrawnQuotes counts the number of withdrawn quotes for a specific note
	CountWithdrawnQuotes(ctx context.Context, noteID string) (int, error)

	// CreateQuoteRelationship creates a new quote relationship between notes
	CreateQuoteRelationship(ctx context.Context, quote *storage.QuoteRelationship) error

	// GetQuotesForNote retrieves quotes for a specific note with pagination
	GetQuotesForNote(ctx context.Context, noteID string, limit int, cursor string) ([]*storage.QuoteRelationship, string, error)

	// IsQuoted checks if a note is quoted by a specific actor
	IsQuoted(ctx context.Context, actorID, noteID string) (bool, error)

	// WithdrawQuote withdraws a quote by marking it as withdrawn
	WithdrawQuote(ctx context.Context, quoteNoteID string) error

	// WithdrawStatusFromQuotes withdraws a status from being quoted with proper cascade effects
	WithdrawStatusFromQuotes(ctx context.Context, statusID string) error

	// UpdateQuotePermissions updates the quote permissions for a status
	UpdateQuotePermissions(ctx context.Context, statusID string, permissions *storage.QuotePermissions) error

	// IsQuoteAllowed checks if a quote is allowed for a status by a quoter
	IsQuoteAllowed(ctx context.Context, statusID, quoterID string) (bool, error)

	// GetQuoteType returns the quote type for a status
	GetQuoteType(ctx context.Context, statusID string) (string, error)

	// IsWithdrawnFromQuotes checks if a status is withdrawn from quotes
	IsWithdrawnFromQuotes(ctx context.Context, statusID string) (bool, error)

	// GetQuotesOfStatus retrieves quotes of a specific status
	GetQuotesOfStatus(ctx context.Context, statusID string, limit int) ([]*storage.StatusSearchResult, error)

	// GetMissingReplies returns a list of known missing replies in a thread
	GetMissingReplies(ctx context.Context, statusID string) ([]*storage.StatusSearchResult, error)

	// MarkThreadAsSynced marks a thread as successfully synced
	MarkThreadAsSynced(ctx context.Context, statusID string) error

	// SyncThreadFromRemote syncs a thread from a remote server
	SyncThreadFromRemote(ctx context.Context, statusID string) (*storage.StatusSearchResult, error)

	// SyncMissingRepliesFromRemote syncs missing replies from remote servers
	SyncMissingRepliesFromRemote(ctx context.Context, statusID string) ([]*storage.StatusSearchResult, error)

	// GetThreadContext retrieves the thread context for a status with full hierarchy
	GetThreadContext(ctx context.Context, statusID string) (*storage.ThreadContext, error)
}

ObjectRepository defines the interface for ActivityPub object operations. This handles object lifecycle, collections, quotes, threads, tombstones, and update history.

type OperationCostStats

type OperationCostStats struct {
	OperationType           string
	Count                   int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostMicroCents   int64
	TotalReadCapacityUnits  float64
	TotalWriteCapacityUnits float64
}

OperationCostStats represents cost statistics for a specific operation type

type PaginatedResult

type PaginatedResult[T any] struct {
	Items      []T    // The actual data items
	NextCursor string // Cursor for the next page (empty if no more pages)
	HasMore    bool   // Whether there are more pages available
	Total      int64  // Total count (if available, -1 if not calculated)
}

PaginatedResult represents a paginated result set

type PaginationOptions

type PaginationOptions struct {
	Limit  int    // Maximum number of items to return
	Cursor string // Pagination cursor/token for the next page
	Since  *time.Time
	Until  *time.Time
}

PaginationOptions represents pagination parameters for repository queries

type PaginationResult

type PaginationResult struct {
	HasNextPage bool
	NextCursor  string
	TotalCount  int
}

PaginationResult represents pagination information for search results

type PollRepository

type PollRepository interface {
	// Core poll operations
	CreatePoll(ctx context.Context, poll *storage.Poll) error
	GetPoll(ctx context.Context, pollID string) (*storage.Poll, error)
	GetPollByStatusID(ctx context.Context, statusID string) (*storage.Poll, error)

	// Voting operations
	VoteOnPoll(ctx context.Context, pollID string, voterID string, choices []int) error
	GetPollVotes(ctx context.Context, pollID string) (map[string][]int, error)
	HasUserVoted(ctx context.Context, pollID string, userID string) (bool, []int, error)
}

PollRepository defines the interface for poll operations. This handles poll creation, voting, and results retrieval.

type ProcessingResult

type ProcessingResult struct {
	Width    int                 `json:"width"`
	Height   int                 `json:"height"`
	Duration int                 `json:"duration"` // Duration in milliseconds
	FileSize int                 `json:"file_size"`
	Blurhash string              `json:"blurhash"`
	Sizes    map[string]SizeInfo `json:"sizes"`
}

ProcessingResult represents the result of media processing

type PublicationMemberRepository

type PublicationMemberRepository interface {

	// CreateMember adds a new member to a publication
	CreateMember(ctx context.Context, member *models.PublicationMember) error

	// GetMember retrieves a member by publication ID and user ID
	GetMember(ctx context.Context, publicationID, userID string) (*models.PublicationMember, error)

	// Update updates an existing publication member
	Update(ctx context.Context, member *models.PublicationMember) error

	// DeleteMember removes a member from a publication
	DeleteMember(ctx context.Context, publicationID, userID string) error

	// ListMembers lists all members of a publication
	ListMembers(ctx context.Context, publicationID string) ([]*models.PublicationMember, error)

	// ListMembershipsForUserPaginated lists publications a user is a member of with pagination
	ListMembershipsForUserPaginated(ctx context.Context, userID string, limit int, cursor string) ([]*models.PublicationMember, string, error)
}

PublicationMemberRepository defines the interface for publication member operations. This handles CMS publication membership management for contributors.

type PublicationRepository

type PublicationRepository interface {

	// GetDB returns the underlying DynamoDB connection for advanced operations
	GetDB() dynamormcore.DB

	// CreatePublication creates a new publication
	CreatePublication(ctx context.Context, publication *models.Publication) error

	// GetPublication retrieves a publication by ID
	GetPublication(ctx context.Context, id string) (*models.Publication, error)

	// Update updates an existing publication
	Update(ctx context.Context, publication *models.Publication) error

	// Delete deletes a publication by PK and SK
	Delete(ctx context.Context, pk, sk string) error
}

PublicationRepository defines the interface for publication operations. This handles CMS publication management for multi-contributor blogs/newsletters.

type PushSubscriptionRepository

type PushSubscriptionRepository interface {
	// Push subscription operations
	CreatePushSubscription(ctx context.Context, username string, subscription *storage.PushSubscription) error
	GetPushSubscription(ctx context.Context, username, subscriptionID string) (*storage.PushSubscription, error)
	GetUserPushSubscriptions(ctx context.Context, username string) ([]*storage.PushSubscription, error)
	UpdatePushSubscription(ctx context.Context, username, subscriptionID string, alerts storage.PushSubscriptionAlerts) error
	DeletePushSubscription(ctx context.Context, username, subscriptionID string) error
	DeleteAllPushSubscriptions(ctx context.Context, username string) error

	// VAPID key management
	GetVAPIDKeys(ctx context.Context) (*storage.VAPIDKeys, error)
	SetVAPIDKeys(ctx context.Context, keys *storage.VAPIDKeys) error
}

PushSubscriptionRepository defines the interface for push subscription operations. This handles web push notifications and VAPID key management.

type QuoteRepository

type QuoteRepository interface {
	// Core quote operations
	CreateQuoteRelationship(ctx context.Context, relationship *models.QuoteRelationship) error
	GetQuoteRelationship(ctx context.Context, quoteStatusID, targetStatusID string) (*models.QuoteRelationship, error)
	UpdateQuoteRelationship(ctx context.Context, relationship *models.QuoteRelationship) error
	DeleteQuoteRelationship(ctx context.Context, quoteStatusID, targetStatusID string) error

	// Quote discovery
	GetQuotesForStatus(ctx context.Context, statusID string, opts PaginationOptions) (*PaginatedResult[*models.QuoteRelationship], error)
	GetQuotesByUser(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.QuoteRelationship], error)

	// Quote permissions
	CreateQuotePermissions(ctx context.Context, permissions *models.QuotePermissions) error
	GetQuotePermissions(ctx context.Context, username string) (*models.QuotePermissions, error)
	UpdateQuotePermissions(ctx context.Context, permissions *models.QuotePermissions) error
	DeleteQuotePermissions(ctx context.Context, username string) error

	// Quote counts and statistics
	GetQuoteCount(ctx context.Context, statusID string) (int64, error)
	IncrementQuoteCount(ctx context.Context, statusID string) error
	DecrementQuoteCount(ctx context.Context, statusID string) error

	// Quote withdrawal operations
	WithdrawQuotes(ctx context.Context, noteID, userID string) (int, error)
}

QuoteRepository defines the interface for quote post operations

type RateLimitRepository

type RateLimitRepository interface {

	// RecordLoginAttempt records a login attempt for rate limiting
	RecordLoginAttempt(ctx context.Context, identifier string, success bool) error

	// GetLoginAttemptCount returns the number of login attempts since the given time
	GetLoginAttemptCount(ctx context.Context, identifier string, since time.Time) (int, error)

	// IsRateLimited checks if an identifier is currently rate limited
	IsRateLimited(ctx context.Context, identifier string) (bool, time.Time, error)

	// ClearLoginAttempts clears all login attempts for an identifier
	ClearLoginAttempts(ctx context.Context, identifier string) error

	// CheckAPIRateLimit checks and updates API rate limiting for a user/endpoint combination
	CheckAPIRateLimit(ctx context.Context, userID, endpoint string, limit int, window time.Duration) error

	// GetAPIRateLimitInfo returns current rate limit info for response headers
	GetAPIRateLimitInfo(ctx context.Context, userID, endpoint string, limit int, window time.Duration) (remaining int, resetTime time.Time, err error)

	// CheckFederationRateLimit checks and updates federation rate limiting for a domain/endpoint combination
	CheckFederationRateLimit(ctx context.Context, domain, endpoint string, limit int, window time.Duration) error

	// GetFederationRateLimitInfo returns current federation rate limit info
	GetFederationRateLimitInfo(ctx context.Context, domain, endpoint string, limit int, window time.Duration) (remaining int, resetTime time.Time, err error)

	// GetViolationCount returns the number of violations in a time period for escalating penalties
	GetViolationCount(ctx context.Context, userID, domain string, since time.Duration) (int, error)

	// IsUserBlocked checks if a user is currently blocked due to rate limiting
	IsUserBlocked(ctx context.Context, userID string) (bool, time.Time, error)

	// IsDomainBlocked checks if a federation domain is currently blocked
	IsDomainBlocked(ctx context.Context, domain string) (bool, time.Time, error)

	// CheckCommunityNoteRateLimit checks if a user can create more community notes today
	CheckCommunityNoteRateLimit(ctx context.Context, userID string, limit int) (bool, int, error)
}

RateLimitRepository defines the interface for rate limiting operations. This handles login attempts, API rate limiting, federation rate limiting, and violations.

type RecoveryRepository

type RecoveryRepository interface {

	// StoreTrustee stores a trustee configuration for social recovery
	StoreTrustee(ctx context.Context, username string, trustee *storage.TrusteeConfig) error

	// GetTrustees retrieves all trustees for a user
	GetTrustees(ctx context.Context, username string) ([]*storage.TrusteeConfig, error)

	// DeleteTrustee removes a trustee
	DeleteTrustee(ctx context.Context, username, trusteeActorID string) error

	// UpdateTrusteeConfirmed updates the confirmed status of a trustee
	UpdateTrusteeConfirmed(ctx context.Context, username, trusteeActorID string, confirmed bool) error

	// StoreRecoveryRequest stores a social recovery request
	StoreRecoveryRequest(ctx context.Context, request *storage.SocialRecoveryRequest) error

	// GetRecoveryRequest retrieves a recovery request by ID
	GetRecoveryRequest(ctx context.Context, requestID string) (*storage.SocialRecoveryRequest, error)

	// UpdateRecoveryRequest updates a recovery request
	UpdateRecoveryRequest(ctx context.Context, request *storage.SocialRecoveryRequest) error

	// DeleteRecoveryRequest deletes a recovery request
	DeleteRecoveryRequest(ctx context.Context, requestID string) error

	// GetActiveRecoveryRequests gets all active recovery requests for a user
	GetActiveRecoveryRequests(ctx context.Context, username string) ([]*storage.SocialRecoveryRequest, error)

	// StoreRecoveryCode stores a recovery code
	StoreRecoveryCode(ctx context.Context, username string, code *storage.RecoveryCodeItem) error

	// GetRecoveryCodes retrieves all recovery codes for a user
	GetRecoveryCodes(ctx context.Context, username string) ([]*storage.RecoveryCodeItem, error)

	// MarkRecoveryCodeUsed marks a recovery code as used
	MarkRecoveryCodeUsed(ctx context.Context, username, codeHash string) error

	// DeleteAllRecoveryCodes deletes all recovery codes for a user
	DeleteAllRecoveryCodes(ctx context.Context, username string) error

	// CountUnusedRecoveryCodes counts how many unused recovery codes the user has
	CountUnusedRecoveryCodes(ctx context.Context, username string) (int, error)

	// StoreRecoveryToken stores a generic recovery token with data
	StoreRecoveryToken(ctx context.Context, key string, data map[string]any) error

	// GetRecoveryToken retrieves a recovery token by key
	GetRecoveryToken(ctx context.Context, key string) (map[string]any, error)

	// DeleteRecoveryToken deletes a recovery token
	DeleteRecoveryToken(ctx context.Context, key string) error
}

RecoveryRepository defines the interface for account recovery operations. This handles trustees, recovery requests, recovery codes, and recovery tokens.

type RelationshipRepository

type RelationshipRepository interface {
	// Core relationship operations
	CreateFollowRequest(ctx context.Context, followerID, followingID string) error
	AcceptFollowRequest(ctx context.Context, followerID, followingID string) error
	RejectFollowRequest(ctx context.Context, followerID, followingID string) error
	Unfollow(ctx context.Context, followerID, followingID string) error

	// Relationship queries
	IsFollowing(ctx context.Context, followerID, followingID string) (bool, error)
	GetFollowStatus(ctx context.Context, followerID, followingID string) (string, error) // pending, accepted, rejected, none
	GetFollowRelationship(ctx context.Context, followerID, followingID string) (*models.RelationshipRecord, error)

	// Follower/Following lists
	GetFollowers(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)
	GetFollowing(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)
	GetFollowRequests(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)
	GetPendingFollowRequests(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)

	// Mutual relationships
	GetMutualFollows(ctx context.Context, userID, otherUserID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)

	// Blocking operations
	BlockUser(ctx context.Context, blockerID, blockedID string) error
	UnblockUser(ctx context.Context, blockerID, blockedID string) error
	IsBlocked(ctx context.Context, blockerID, blockedID string) (bool, error)
	GetBlockedUsers(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)

	// Muting operations
	MuteUser(ctx context.Context, muterID, mutedID string) error
	UnmuteUser(ctx context.Context, muterID, mutedID string) error
	IsMuted(ctx context.Context, muterID, mutedID string) (bool, error)
	GetMutedUsers(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*storage.Account], error)

	// Relationship counts
	GetFollowerCount(ctx context.Context, userID string) (int64, error)
	GetFollowingCount(ctx context.Context, userID string) (int64, error)
	GetMutualFollowCount(ctx context.Context, userID, otherUserID string) (int64, error)

	// Batch operations
	GetRelationships(ctx context.Context, requestingUserID string, targetUserIDs []string) (map[string]*models.RelationshipRecord, error)
}

RelationshipRepository defines the interface for follow/relationship operations This handles both local and federated follow relationships

type RelayRepository

type RelayRepository interface {

	// StoreRelayInfo stores relay information
	StoreRelayInfo(ctx context.Context, relay *storage.RelayInfo) error

	// GetRelayInfo retrieves relay information
	GetRelayInfo(ctx context.Context, relayURL string) (*storage.RelayInfo, error)

	// RemoveRelayInfo removes relay information
	RemoveRelayInfo(ctx context.Context, relayURL string) error

	// GetActiveRelays retrieves all active relays
	GetActiveRelays(ctx context.Context) ([]*storage.RelayInfo, error)

	// GetAllRelays retrieves all relays with pagination
	GetAllRelays(ctx context.Context, limit int, cursor string) ([]*storage.RelayInfo, string, error)

	// ListRelays retrieves all relays (alias for GetAllRelays without pagination)
	ListRelays(ctx context.Context) ([]*storage.RelayInfo, error)

	// UpdateRelayStatus updates the active status of a relay
	UpdateRelayStatus(ctx context.Context, relayURL string, active bool) error

	// UpdateRelayState updates multiple relay fields beyond just active status
	UpdateRelayState(ctx context.Context, relayURL string, state storage.RelayState) error

	// CreateRelay creates a new relay
	CreateRelay(ctx context.Context, relay *storage.RelayInfo) error

	// GetRelay retrieves a relay by URL (alias for GetRelayInfo)
	GetRelay(ctx context.Context, relayURL string) (*storage.RelayInfo, error)

	// DeleteRelay removes a relay (alias for RemoveRelayInfo)
	DeleteRelay(ctx context.Context, relayURL string) error
}

RelayRepository defines the interface for ActivityPub relay operations. This handles relay information storage, retrieval, and status management.

type RepositoryAccess

type RepositoryAccess interface {
	// Repository access methods - return interface{} to allow flexibility with actual repository types
	Account() interface{}
	Actor() interface{}
	Object() interface{}
	Activity() interface{}
	Timeline() interface{}
	Notification() interface{}
	Like() interface{}
	Moderation() interface{}
	List() interface{}
	Media() interface{}
	MediaMetadata() interface{}
	Poll() interface{}
	PushSubscription() interface{}
	Hashtag() interface{}
	ScheduledStatus() interface{}
	Announcement() interface{}
	DomainBlock() interface{}
	Relationship() interface{}
	Instance() interface{}
	Federation() interface{}
	Recovery() interface{}
	Analytics() interface{} // Analytics/Trending repository
	Social() interface{}
	User() interface{}
	Status() interface{}
	Cost() interface{}
	WebSocketCost() interface{}
	Trust() interface{}
	Search() interface{}
	Relay() interface{}
	CommunityNote() interface{}
	Emoji() interface{}
	RateLimit() interface{}
	Conversation() interface{}
	Marker() interface{}
	FeaturedTag() interface{}
	AI() interface{}
	Export() interface{}
	Import() interface{}
	DLQ() interface{}
	MetricRecord() interface{}
	CloudWatchMetrics() interface{}
	StreamingCloudWatch() interface{}
	Audit() interface{}
	OAuth() interface{}
	DNSCache() interface{}
	Filter() interface{}

	// Utility methods
	GetDB() interface{}
	GetTableName() string
	GetLogger() interface{}
}

RepositoryAccess provides access to all DynamORM repositories This replaces the core.RepositoryStorage embedding to avoid circular imports

type RepositoryRegistry

type RepositoryRegistry interface {
	Status() StatusRepository
	Account() AccountRepository
	Relationship() RelationshipRepository
	Media() MediaRepository
	Conversation() ConversationRepository
	List() ListRepository
	Filter() FilterRepository
	Notification() NotificationRepository
	Like() LikeRepository
	Social() SocialRepository
	Quote() QuoteRepository
}

RepositoryRegistry provides access to all repository interfaces This allows services to access storage operations through a single interface

type RevisionRepository

type RevisionRepository interface {

	// CreateRevision creates a new revision
	CreateRevision(ctx context.Context, revision *models.Revision) error

	// GetRevision retrieves a revision by object ID and version
	GetRevision(ctx context.Context, objectID string, version int) (*models.Revision, error)

	// Delete deletes a revision by PK and SK
	Delete(ctx context.Context, pk, sk string) error

	// ListRevisions lists revisions for an object
	ListRevisions(ctx context.Context, objectID string, limit int) ([]*models.Revision, error)

	// ListRevisionsPaginated lists revisions for an object with cursor pagination
	ListRevisionsPaginated(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Revision, string, error)
}

RevisionRepository defines the interface for revision operations. This handles CMS revision management for version history tracking.

type ScheduledStatusRepository

type ScheduledStatusRepository interface {
	// CreateScheduledStatus creates a new scheduled status
	CreateScheduledStatus(ctx context.Context, scheduled *storage.ScheduledStatus) error

	// GetScheduledStatus retrieves a scheduled status by ID
	GetScheduledStatus(ctx context.Context, id string) (*storage.ScheduledStatus, error)

	// GetScheduledStatuses retrieves scheduled statuses for a user
	GetScheduledStatuses(ctx context.Context, username string, limit int, cursor string) ([]*storage.ScheduledStatus, string, error)

	// UpdateScheduledStatus updates a scheduled status
	UpdateScheduledStatus(ctx context.Context, scheduled *storage.ScheduledStatus) error

	// DeleteScheduledStatus deletes a scheduled status
	DeleteScheduledStatus(ctx context.Context, id string) error

	// GetDueScheduledStatuses retrieves scheduled statuses that are due to be published
	GetDueScheduledStatuses(ctx context.Context, before time.Time, limit int) ([]*storage.ScheduledStatus, error)

	// MarkScheduledStatusPublished marks a scheduled status as published
	MarkScheduledStatusPublished(ctx context.Context, id string) error

	// GetScheduledStatusMedia gets media for scheduled status
	GetScheduledStatusMedia(ctx context.Context, id string) ([]*models.Media, error)

	// SetMediaRepository sets the media repository dependency
	SetMediaRepository(mediaRepo MediaRepositoryInterface)
}

ScheduledStatusRepository defines the interface for scheduled status operations. This handles creating, retrieving, and managing scheduled posts.

type SearchRepository

type SearchRepository interface {

	// SearchAccounts searches for accounts matching the given query
	SearchAccounts(ctx context.Context, query string, limit int, followingOnly bool, offset int) ([]*activitypub.Actor, error)

	// SearchAccountsWithPrivacy searches for accounts with privacy enforcement
	SearchAccountsWithPrivacy(ctx context.Context, query string, limit int, followingOnly bool, offset int, searcherActorID string) ([]*activitypub.Actor, error)

	// SearchAccountsAdvanced searches for accounts with advanced filtering
	SearchAccountsAdvanced(ctx context.Context, query string, resolve bool, limit int, offset int, following bool, accountID string) ([]*activitypub.Actor, error)

	// SearchStatuses searches for statuses matching the given query
	SearchStatuses(ctx context.Context, query string, limit int) ([]*storage.StatusSearchResult, error)

	// SearchStatusesWithOptions searches for statuses with advanced options
	SearchStatusesWithOptions(ctx context.Context, query string, options storage.StatusSearchOptions) ([]*storage.StatusSearchResult, error)

	// SearchStatusesWithOptionsPaginated searches for statuses with advanced options and pagination support
	SearchStatusesWithOptionsPaginated(ctx context.Context, query string, options storage.StatusSearchOptions) ([]*storage.StatusSearchResult, *PaginationResult, error)

	// SearchStatusesWithPrivacy searches for statuses with privacy enforcement
	SearchStatusesWithPrivacy(ctx context.Context, query string, options storage.StatusSearchOptions, searcherActorID string) ([]*storage.StatusSearchResult, error)

	// SearchStatusesWithPrivacyPaginated searches for statuses with privacy enforcement and pagination
	SearchStatusesWithPrivacyPaginated(ctx context.Context, query string, options storage.StatusSearchOptions, searcherActorID string) ([]*storage.StatusSearchResult, *PaginationResult, error)

	// SearchStatusesAdvanced searches for statuses with advanced filtering
	SearchStatusesAdvanced(ctx context.Context, query string, limit int, maxID, minID *string, accountID string) ([]*storage.StatusSearchResult, error)

	// SetDependencies sets the dependencies for cross-repository operations
	SetDependencies(deps SearchRepositoryDeps)
}

SearchRepository defines the interface for search operations. This handles account search, status search, and search with privacy enforcement.

type SearchRepositoryDeps

type SearchRepositoryDeps interface {
	GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	IsBlocked(ctx context.Context, blockerActor, blockedActor string) (bool, error)
	IsBlockedBidirectional(ctx context.Context, actor1, actor2 string) (bool, error)
	GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
}

SearchRepositoryDeps interface for dependencies - implemented by the storage adapter

type SeriesRepository

type SeriesRepository interface {

	// CreateSeries creates a new series
	CreateSeries(ctx context.Context, series *models.Series) error

	// GetSeries retrieves a series by author ID and series ID
	GetSeries(ctx context.Context, authorID, seriesID string) (*models.Series, error)

	// Update updates an existing series
	Update(ctx context.Context, series *models.Series) error

	// Delete deletes a series by PK and SK
	Delete(ctx context.Context, pk, sk string) error

	// ListSeriesByAuthor lists series for an author
	ListSeriesByAuthor(ctx context.Context, authorID string, limit int) ([]*models.Series, error)

	// ListSeriesByAuthorPaginated lists series for an author with cursor pagination
	ListSeriesByAuthorPaginated(ctx context.Context, authorID string, limit int, cursor string) ([]*models.Series, string, error)

	// UpdateArticleCount atomically increments/decrements a series's ArticleCount
	UpdateArticleCount(ctx context.Context, authorID string, seriesID string, delta int) error
}

SeriesRepository defines the interface for series operations. This handles CMS series management for multi-part content.

type ServiceMetrics

type ServiceMetrics struct {
	ServiceName       string
	RequestCount      int64
	ErrorCount        int64
	LatencyP50Ms      float64
	LatencyP90Ms      float64
	LatencyP99Ms      float64
	DynamoDBReads     int64
	DynamoDBWrites    int64
	LambdaInvocations int64
	S3Requests        int64
	DataTransferBytes int64
	EstimatedCostUSD  float64
}

ServiceMetrics represents aggregated metrics for a service.

type SeveranceFilters

type SeveranceFilters struct {
	Instance string                 // Filter by remote instance
	Status   models.SeveranceStatus // Filter by status
	Reason   models.SeveranceReason // Filter by reason
}

SeveranceFilters defines filters for querying severed relationships

type SeveranceRepository

type SeveranceRepository interface {

	// CreateSeveredRelationship creates a new severed relationship record
	CreateSeveredRelationship(ctx context.Context, severance *models.SeveredRelationship) error

	// GetSeveredRelationship retrieves a severed relationship by ID
	GetSeveredRelationship(ctx context.Context, id string) (*models.SeveredRelationship, error)

	// ListSeveredRelationships retrieves severed relationships with filters and pagination
	ListSeveredRelationships(ctx context.Context, localInstance string, filters SeveranceFilters, limit int, cursor string) ([]*models.SeveredRelationship, string, error)

	// UpdateSeveranceStatus updates the status of a severed relationship
	UpdateSeveranceStatus(ctx context.Context, id string, status models.SeveranceStatus) error

	// CreateAffectedRelationship creates a new affected relationship record
	CreateAffectedRelationship(ctx context.Context, affected *models.AffectedRelationship) error

	// GetAffectedRelationships retrieves affected relationships for a severance
	GetAffectedRelationships(ctx context.Context, severanceID string, limit int, cursor string) ([]*models.AffectedRelationship, string, error)

	// CreateReconnectionAttempt creates a new reconnection attempt record
	CreateReconnectionAttempt(ctx context.Context, attempt *models.SeveranceReconnectionAttempt) error

	// UpdateReconnectionAttempt updates a reconnection attempt record
	UpdateReconnectionAttempt(ctx context.Context, attempt *models.SeveranceReconnectionAttempt) error

	// GetReconnectionAttempt retrieves a reconnection attempt by ID
	GetReconnectionAttempt(ctx context.Context, severanceID, attemptID string) (*models.SeveranceReconnectionAttempt, error)

	// GetReconnectionAttempts retrieves all reconnection attempts for a severance
	GetReconnectionAttempts(ctx context.Context, severanceID string) ([]*models.SeveranceReconnectionAttempt, error)
}

SeveranceRepository defines the interface for severed relationship operations. This handles tracking and managing severed federation relationships.

type SizeInfo

type SizeInfo struct {
	Width  int    `json:"width"`
	Height int    `json:"height"`
	S3Key  string `json:"s3_key"`
	URL    string `json:"url"`
}

SizeInfo contains information about a processed media size

type SocialRepository

type SocialRepository interface {

	// CreateBlock creates a new block relationship
	CreateBlock(ctx context.Context, block *storage.Block) error

	// DeleteBlock removes a block relationship
	DeleteBlock(ctx context.Context, actor, blockedActor string) error

	// GetBlock retrieves a specific block relationship
	GetBlock(ctx context.Context, actor, blockedActor string) (*storage.Block, error)

	// IsBlocked checks if targetActor is blocked by actor
	IsBlocked(ctx context.Context, actor, targetActor string) (bool, error)

	// GetBlockedUsers returns a paginated list of actors blocked by the given actor
	GetBlockedUsers(ctx context.Context, actor string, limit int, cursor string) ([]*storage.Block, string, error)

	// GetBlockedByUsers returns a paginated list of actors who have blocked the given actor
	GetBlockedByUsers(ctx context.Context, actor string, limit int, cursor string) ([]*storage.Block, string, error)

	// CreateMute creates a new mute relationship
	CreateMute(ctx context.Context, mute *storage.Mute) error

	// DeleteMute removes a mute relationship
	DeleteMute(ctx context.Context, actor, mutedActor string) error

	// GetMute retrieves a specific mute relationship
	GetMute(ctx context.Context, actor, mutedActor string) (*storage.Mute, error)

	// IsMuted checks if targetActor is muted by actor
	IsMuted(ctx context.Context, actor, targetActor string) (bool, error)

	// GetMutedUsers returns all actors muted by the given actor
	GetMutedUsers(ctx context.Context, actor string, limit int, cursor string) ([]*storage.Mute, string, error)

	// CreateAnnounce creates a new Announce activity
	CreateAnnounce(ctx context.Context, announce *storage.Announce) error

	// DeleteAnnounce removes an Announce activity
	DeleteAnnounce(ctx context.Context, actor, object string) error

	// GetAnnounce retrieves a specific Announce by actor and object
	GetAnnounce(ctx context.Context, actor, object string) (*storage.Announce, error)

	// GetStatusAnnounces retrieves all announces for a specific object
	GetStatusAnnounces(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.Announce, string, error)

	// HasUserAnnounced checks if a user has announced a specific object
	HasUserAnnounced(ctx context.Context, actor, object string) (bool, error)

	// GetActorAnnounces retrieves all objects announced by a specific actor with pagination
	GetActorAnnounces(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.Announce, string, error)

	// CountObjectAnnounces returns the total number of announces for an object
	CountObjectAnnounces(ctx context.Context, objectID string) (int, error)

	// CascadeDeleteAnnounces deletes all announces for an object
	CascadeDeleteAnnounces(ctx context.Context, objectID string) error

	// CreateAccountPin creates a new account pin (endorsed account)
	CreateAccountPin(ctx context.Context, pin *storage.AccountPin) error

	// DeleteAccountPin deletes an account pin
	DeleteAccountPin(ctx context.Context, username, pinnedActorID string) error

	// GetAccountPins retrieves all pinned accounts for a user
	GetAccountPins(ctx context.Context, username string) ([]*storage.AccountPin, error)

	// GetAccountPinsPaginated retrieves pinned accounts for a user with pagination
	GetAccountPinsPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.AccountPin, string, error)

	// IsAccountPinned checks if an account is pinned
	IsAccountPinned(ctx context.Context, username, pinnedActorID string) (bool, error)

	// CreateAccountNote creates a new private note on an account
	CreateAccountNote(ctx context.Context, note *storage.AccountNote) error

	// UpdateAccountNote updates an existing private note on an account
	UpdateAccountNote(ctx context.Context, note *storage.AccountNote) error

	// DeleteAccountNote deletes a private note on an account
	DeleteAccountNote(ctx context.Context, username, targetActorID string) error

	// GetAccountNote retrieves a private note on an account
	GetAccountNote(ctx context.Context, username, targetActorID string) (*storage.AccountNote, error)

	// CreateStatusPin creates a new status pin
	CreateStatusPin(ctx context.Context, pin *storage.StatusPin) error

	// DeleteStatusPin deletes a status pin
	DeleteStatusPin(ctx context.Context, username, statusID string) error

	// GetStatusPins retrieves all pinned statuses for a user
	GetStatusPins(ctx context.Context, username string) ([]*storage.StatusPin, error)

	// GetStatusPinsPaginated retrieves pinned statuses for a user with pagination
	GetStatusPinsPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.StatusPin, string, error)

	// IsStatusPinned checks if a status is pinned by a user
	IsStatusPinned(ctx context.Context, username, statusID string) (bool, error)

	// ReorderStatusPins reorders pinned statuses
	ReorderStatusPins(ctx context.Context, username string, statusIDs []string) error

	// CountUserPinnedStatuses counts the number of pinned statuses for a user
	CountUserPinnedStatuses(ctx context.Context, username string) (int, error)
}

SocialRepository defines the interface for social interaction operations. This handles blocks, mutes, announces (boosts), account pins, account notes, and status pins.

type StatusFilter

type StatusFilter struct {
	Local      *bool      // Filter by local vs remote statuses
	Remote     *bool      // Filter by remote statuses only
	ByDomain   string     // Filter by specific domain
	Visibility string     // Filter by visibility (public, unlisted, private, direct)
	Flagged    *bool      // Filter by flagged status
	Reported   *bool      // Filter by reported status
	WithMedia  *bool      // Filter by presence of media attachments
	Sensitive  *bool      // Filter by sensitive flag
	MinDate    *time.Time // Filter by minimum creation date
	MaxDate    *time.Time // Filter by maximum creation date
}

StatusFilter represents filtering criteria for admin status listing

type StatusRepository

type StatusRepository interface {
	// Core CRUD operations
	CreateStatus(ctx context.Context, status *models.Status) error
	CreateBoostStatus(ctx context.Context, status *models.Status) error
	GetStatus(ctx context.Context, statusID string) (*models.Status, error)
	GetStatusByURL(ctx context.Context, url string) (*models.Status, error)
	UpdateStatus(ctx context.Context, status *models.Status) error
	DeleteStatus(ctx context.Context, statusID string) error
	DeleteBoostStatus(ctx context.Context, boosterID, targetStatusID string) (*models.Status, error)

	// Timeline operations
	GetPublicTimeline(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetHomeTimeline(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetUserTimeline(ctx context.Context, userID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetConversationThread(ctx context.Context, conversationID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetReplies(ctx context.Context, parentStatusID string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)

	// Search and discovery
	SearchStatuses(ctx context.Context, query string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetStatusesByHashtag(ctx context.Context, hashtag string, opts PaginationOptions) (*PaginatedResult[*models.Status], error)
	GetTrendingStatuses(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Status], error)

	// Engagement operations
	LikeStatus(ctx context.Context, userID, statusID string) error
	UnlikeStatus(ctx context.Context, userID, statusID string) error
	ReblogStatus(ctx context.Context, userID, statusID string, reblogStatusID string) error
	UnreblogStatus(ctx context.Context, userID, statusID string) error
	BookmarkStatus(ctx context.Context, userID, statusID string) error
	UnbookmarkStatus(ctx context.Context, userID, statusID string) error

	// Moderation operations
	FlagStatus(ctx context.Context, statusID, reason string, reportedBy string) error
	UnflagStatus(ctx context.Context, statusID string) error
	GetFlaggedStatuses(ctx context.Context, opts PaginationOptions) (*PaginatedResult[*models.Status], error)

	// Batch operations for performance
	GetStatusesByIDs(ctx context.Context, statusIDs []string) ([]*models.Status, error)
	GetStatusCounts(ctx context.Context, statusID string) (likes, reblogs, replies int, err error)

	// Context and metadata
	GetStatusContext(ctx context.Context, statusID string) (ancestors, descendants []*models.Status, err error)
	GetStatusEngagement(ctx context.Context, statusID, userID string) (liked, reblogged, bookmarked bool, err error)

	// Count operations
	CountStatusesByAuthor(ctx context.Context, authorID string) (int, error)
	CountReplies(ctx context.Context, statusID string) (int, error)

	// Admin operations
	ListStatusesForAdmin(ctx context.Context, filter *StatusFilter, limit int, cursor string) ([]*models.Status, string, error)
}

StatusRepository defines the interface for status/note operations This handles both local status creation and federated ActivityPub Note objects

type Storage

type Storage interface {
	// Repository Access - provides access to all DynamORM repositories
	RepositoryAccess

	// Actor lifecycle operations
	CreateActor(ctx context.Context, actor *activitypub.Actor, privateKey string) error
	GetActor(ctx context.Context, username string) (*activitypub.Actor, error)
	UpdateActor(ctx context.Context, actor *activitypub.Actor) error
	DeleteActor(ctx context.Context, username string) error
	GetActorByID(ctx context.Context, actorID string) (*activitypub.Actor, error)

	// Actor key management
	GetActorPrivateKey(ctx context.Context, username string) (string, error)
	UpdateActorKeys(ctx context.Context, username, publicKey, privateKey string) error

	// User lifecycle operations
	CreateUser(ctx context.Context, user interface{}) error
	GetUser(ctx context.Context, username string) (interface{}, error)
	UpdateUser(ctx context.Context, user interface{}) error
	DeleteUser(ctx context.Context, username string) error
	GetUserByID(ctx context.Context, userID string) (interface{}, error)
	GetUserByEmail(ctx context.Context, email string) (interface{}, error)

	// User preferences and settings
	GetUserPreferences(ctx context.Context, username string) (interface{}, error)
	UpdateUserPreferences(ctx context.Context, username string, preferences interface{}) error

	// User validation and authentication
	ValidateCredentials(ctx context.Context, username, password string) (interface{}, error)
	UpdatePassword(ctx context.Context, username, hashedPassword string) error

	// Object lifecycle operations
	CreateObject(ctx context.Context, object interface{}) error
	GetObject(ctx context.Context, objectID string) (interface{}, error)
	UpdateObject(ctx context.Context, objectID string, object interface{}) error
	DeleteObject(ctx context.Context, objectID string) error
	TombstoneObject(ctx context.Context, objectID, actorID string) error

	// Object metadata and relationships
	IncrementReplyCount(ctx context.Context, objectID string) error
	DecrementReplyCount(ctx context.Context, objectID string) error
	GetObjectMetadata(ctx context.Context, objectID string) (interface{}, error)

	// Object history and versioning
	GetObjectHistory(ctx context.Context, objectID string) ([]interface{}, error)
	RestoreObjectVersion(ctx context.Context, objectID string, version int) error

	// Activity lifecycle operations
	StoreActivity(ctx context.Context, activity *activitypub.Activity) error
	CreateActivity(ctx context.Context, activity *activitypub.Activity) error
	GetActivity(ctx context.Context, activityID string) (*activitypub.Activity, error)
	UpdateActivity(ctx context.Context, activity *activitypub.Activity) error
	DeleteActivity(ctx context.Context, activityID string) error

	// Activity processing and routing
	ProcessInboundActivity(ctx context.Context, activity *activitypub.Activity, fromDomain string) error
	ProcessOutboundActivity(ctx context.Context, activity *activitypub.Activity) error
	GetActivitiesByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*activitypub.Activity, string, error)

	// Follow relationships
	CreateRelationship(ctx context.Context, followerUsername, followingID, activityID string) error
	RemoveRelationship(ctx context.Context, followerUsername, followingID string) error
	IsFollowing(ctx context.Context, followerUsername, followingID string) (bool, error)
	GetRelationship(ctx context.Context, followerUsername, followingID string) (interface{}, error)
	UpdateRelationshipStatus(ctx context.Context, followerUsername, followingID string, status string) error

	// Follow requests
	CreateFollowRequest(ctx context.Context, followerUsername, followingID, activityID string) error
	AcceptFollowRequest(ctx context.Context, followerUsername, followingID, activityID string) error
	RejectFollowRequest(ctx context.Context, followerUsername, followingID string) error
	GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Follower/following operations
	FollowActor(ctx context.Context, followerUsername, targetUsername string) error
	UnfollowActor(ctx context.Context, followerUsername, targetUsername string) error
	GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	GetFollowersCount(ctx context.Context, username string) (int64, error)
	GetFollowingCount(ctx context.Context, username string) (int64, error)

	// Blocking and muting
	BlockActor(ctx context.Context, blockerUsername, blockedUsername string) error
	UnblockActor(ctx context.Context, blockerUsername, blockedUsername string) error
	IsBlocked(ctx context.Context, blockerUsername, blockedUsername string) (bool, error)
	GetBlockedUsers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	MuteActor(ctx context.Context, muterUsername, mutedUsername string) error
	UnmuteActor(ctx context.Context, muterUsername, mutedUsername string) error
	IsMuted(ctx context.Context, muterUsername, mutedUsername string) (bool, error)
	GetMutedUsers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

	// Like operations
	CreateLike(ctx context.Context, actorID, objectID, activityID string) error
	RemoveLike(ctx context.Context, actorID, objectID string) error
	HasLiked(ctx context.Context, actorID, objectID string) (bool, error)
	GetLikeCount(ctx context.Context, objectID string) (int64, error)
	GetLikedObjects(ctx context.Context, actorID string, limit int, cursor string) ([]string, string, error)
	GetObjectLikes(ctx context.Context, objectID string, limit int, cursor string) ([]interface{}, string, error)

	// Timeline management
	GetTimeline(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)
	GetHomeTimeline(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)
	GetPublicTimeline(ctx context.Context, limit int, cursor string) ([]interface{}, string, error)
	GetHashtagTimeline(ctx context.Context, hashtag string, limit int, cursor string) ([]interface{}, string, error)
	GetUserTimeline(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Timeline entry management
	AddToTimeline(ctx context.Context, username string, objectID string, activityType string) error
	RemoveFromTimeline(ctx context.Context, username, objectID string) error
	RemoveFromTimelines(ctx context.Context, objectID string) error
	FanOutPost(ctx context.Context, activity *activitypub.Activity) error

	// Notification management
	CreateNotification(ctx context.Context, notification interface{}) error
	GetNotifications(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)
	GetUnreadNotificationCount(ctx context.Context, username string) (int64, error)
	MarkNotificationAsRead(ctx context.Context, notificationID string) error
	MarkAllNotificationsAsRead(ctx context.Context, username string) error
	DeleteNotification(ctx context.Context, notificationID string) error
	DeleteNotificationsByObject(ctx context.Context, objectID string) error

	// Search functionality
	SearchUsers(ctx context.Context, query string, limit int, cursor string) ([]interface{}, string, error)
	SearchStatuses(ctx context.Context, query string, limit int, cursor string) ([]interface{}, string, error)
	SearchHashtags(ctx context.Context, query string, limit int, cursor string) ([]interface{}, string, error)
	SearchAll(ctx context.Context, query string, limit int, cursor string) (interface{}, string, error)

	// Search suggestions and trending
	GetSearchSuggestions(ctx context.Context, query string, limit int) ([]interface{}, error)
	GetTrendingHashtags(ctx context.Context, limit int) ([]interface{}, error)
	GetTrendingStatuses(ctx context.Context, limit int, cursor string) ([]interface{}, string, error)

	// Session management
	CreateSession(ctx context.Context, session interface{}) error
	GetSession(ctx context.Context, sessionID string) (interface{}, error)
	UpdateSession(ctx context.Context, session interface{}) error
	DeleteSession(ctx context.Context, sessionID string) error
	CleanupExpiredSessions(ctx context.Context) error
	GetUserSessions(ctx context.Context, username string) ([]interface{}, error)

	// Token management
	ValidateToken(ctx context.Context, token string) (interface{}, error)
	CreateAccessToken(ctx context.Context, token interface{}) error
	GetAccessToken(ctx context.Context, tokenID string) (interface{}, error)
	RevokeAccessToken(ctx context.Context, tokenID string) error
	CleanupExpiredTokens(ctx context.Context) error

	// OAuth operations
	CreateOAuthState(ctx context.Context, state interface{}) error
	GetOAuthState(ctx context.Context, state string) (interface{}, error)
	DeleteOAuthState(ctx context.Context, state string) error
	CreateOAuthClient(ctx context.Context, client interface{}) error
	GetOAuthClient(ctx context.Context, clientID string) (interface{}, error)

	// Media attachment management
	CreateMediaAttachment(ctx context.Context, media interface{}) error
	GetMediaAttachment(ctx context.Context, mediaID string) (interface{}, error)
	UpdateMediaAttachment(ctx context.Context, media interface{}) error
	DeleteMediaAttachment(ctx context.Context, mediaID string) error
	GetMediaAttachmentsByUser(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Media processing and metadata
	QueueMediaProcessing(ctx context.Context, mediaID string, processingType interface{}) error
	UpdateMediaProcessingStatus(ctx context.Context, mediaID string, status interface{}, metadata map[string]interface{}) error
	GetMediaMetadata(ctx context.Context, mediaID string) (interface{}, error)

	// Federation instance management
	CreateFederationInstance(ctx context.Context, instance interface{}) error
	GetFederationInstance(ctx context.Context, domain string) (interface{}, error)
	UpdateFederationInstance(ctx context.Context, instance interface{}) error
	GetAllFederationInstances(ctx context.Context, limit int, cursor string) ([]interface{}, string, error)

	// Federation activity tracking
	RecordFederationActivity(ctx context.Context, activity interface{}) error
	GetFederationActivities(ctx context.Context, domain string, limit int, cursor string) ([]interface{}, string, error)
	GetFederationStatistics(ctx context.Context, domain string, since time.Time) (interface{}, error)

	// Federation health and monitoring
	UpdateFederationHealth(ctx context.Context, domain string, isHealthy bool, responseTime time.Duration) error
	GetFederationHealth(ctx context.Context, domain string) (interface{}, error)
	GetUnhealthyFederationInstances(ctx context.Context, limit int) ([]interface{}, error)

	// Report management
	CreateReport(ctx context.Context, report interface{}) error
	GetReport(ctx context.Context, reportID string) (interface{}, error)
	UpdateReport(ctx context.Context, report interface{}) error
	GetReportsByStatus(ctx context.Context, status interface{}, limit int, cursor string) ([]interface{}, string, error)
	GetReportsByUser(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Moderation queue operations
	GetModerationQueue(ctx context.Context, filter interface{}) ([]interface{}, error)
	CreateModerationDecision(ctx context.Context, decision interface{}) error
	GetModerationDecision(ctx context.Context, contentID string) (interface{}, error)
	UpdateModerationDecision(ctx context.Context, contentID string, decision interface{}) error

	// Content flagging
	CreateFlag(ctx context.Context, flag interface{}) error
	GetFlags(ctx context.Context, objectID string) ([]interface{}, error)
	GetFlagsByUser(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Domain blocking
	CreateDomainBlock(ctx context.Context, domain string, reason string) error
	RemoveDomainBlock(ctx context.Context, domain string) error
	IsDomainBlocked(ctx context.Context, domain string) (bool, error)
	GetDomainBlocks(ctx context.Context, limit int, cursor string) ([]interface{}, string, error)

	// DNS cache management (PK=`DNSCACHE#hostname`, SK=`ENTRY`)
	SetDNSCache(ctx context.Context, hostname string, record interface{}) error
	GetDNSCache(ctx context.Context, hostname string) (interface{}, error)
	DeleteDNSCache(ctx context.Context, hostname string) error
	CleanupExpiredDNSCache(ctx context.Context) error

	// General cache operations
	SetCache(ctx context.Context, key string, value interface{}, ttl time.Duration) error
	GetCache(ctx context.Context, key string, value interface{}) error
	DeleteCache(ctx context.Context, key string) error
	ClearCache(ctx context.Context, pattern string) error

	// DynamoDB cost tracking
	TrackDynamoRead(ctx context.Context, tableName string, units int64) error
	TrackDynamoWrite(ctx context.Context, tableName string, units int64) error
	TrackDynamoOperation(ctx context.Context, operation interface{}) error
	GetCostSummary(ctx context.Context, since time.Time) (interface{}, error)
	GetDailyCostSummary(ctx context.Context, date time.Time) (interface{}, error)

	// AWS service cost tracking
	TrackAWSCost(ctx context.Context, service string, operation string, cost float64) error
	TrackLambdaInvocation(ctx context.Context, functionName string, duration time.Duration) error
	TrackS3Operation(ctx context.Context, bucket string, operation string, bytes int64) error

	// Cost alerting and monitoring
	GetCostAlerts(ctx context.Context) ([]interface{}, error)
	CreateCostAlert(ctx context.Context, alert interface{}) error
	UpdateCostAlert(ctx context.Context, alertID string, alert interface{}) error

	// Activity analytics
	RecordActivity(ctx context.Context, activityType, actorID string, timestamp time.Time) error
	RecordInstanceActivity(ctx context.Context, activityType string, timestamp time.Time) error
	RecordHashtagUsage(ctx context.Context, hashtag, objectID, actorID string) error
	RecordLinkShare(ctx context.Context, link, objectID, actorID string) error
	RecordStatusEngagement(ctx context.Context, objectID, engagementType, actorID string) error

	// Instance metrics
	GetInstanceMetrics(ctx context.Context, since time.Time) (interface{}, error)
	GetUserActivityMetrics(ctx context.Context, username string, since time.Time) (interface{}, error)
	GetContentMetrics(ctx context.Context, since time.Time) (interface{}, error)

	// Scheduled status operations
	CreateScheduledStatus(ctx context.Context, scheduled interface{}) error
	GetScheduledStatus(ctx context.Context, id string) (interface{}, error)
	GetScheduledStatuses(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)
	UpdateScheduledStatus(ctx context.Context, scheduled interface{}) error
	DeleteScheduledStatus(ctx context.Context, id string) error
	GetDueScheduledStatuses(ctx context.Context, before time.Time, limit int) ([]interface{}, error)
	MarkScheduledStatusPublished(ctx context.Context, id string) error

	// Background job management
	CreateBackgroundJob(ctx context.Context, job interface{}) error
	GetBackgroundJob(ctx context.Context, jobID string) (interface{}, error)
	UpdateBackgroundJobStatus(ctx context.Context, jobID string, status interface{}, result interface{}) error
	GetPendingBackgroundJobs(ctx context.Context, jobType string, limit int) ([]interface{}, error)

	// List management
	CreateList(ctx context.Context, list interface{}) error
	GetList(ctx context.Context, listID string) (interface{}, error)
	UpdateList(ctx context.Context, list interface{}) error
	DeleteList(ctx context.Context, listID string) error
	GetListsByUser(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// List membership
	AddListMember(ctx context.Context, listID, username string) error
	RemoveListMember(ctx context.Context, listID, username string) error
	GetListMembers(ctx context.Context, listID string, limit int, cursor string) ([]interface{}, string, error)
	IsListMember(ctx context.Context, listID, username string) (bool, error)
	GetUserLists(ctx context.Context, username string) ([]interface{}, error)

	// Poll management
	CreatePoll(ctx context.Context, poll interface{}) error
	GetPoll(ctx context.Context, pollID string) (interface{}, error)
	UpdatePoll(ctx context.Context, poll interface{}) error
	GetPollsByUser(ctx context.Context, username string, limit int, cursor string) ([]interface{}, string, error)

	// Poll voting
	CastPollVote(ctx context.Context, vote interface{}) error
	GetPollVote(ctx context.Context, pollID, voterID string) (interface{}, error)
	GetPollResults(ctx context.Context, pollID string) (interface{}, error)

	// Hashtag management
	CreateHashtag(ctx context.Context, hashtag interface{}) error
	GetHashtag(ctx context.Context, name string) (interface{}, error)
	UpdateHashtag(ctx context.Context, hashtag interface{}) error
	IncrementHashtagUsage(ctx context.Context, name string) error
	GetHashtagsByPopularity(ctx context.Context, limit int, since time.Time) ([]interface{}, error)

	// Hashtag following
	FollowHashtag(ctx context.Context, username, hashtagName string) error
	UnfollowHashtag(ctx context.Context, username, hashtagName string) error
	IsFollowingHashtag(ctx context.Context, username, hashtagName string) (bool, error)
	GetFollowedHashtags(ctx context.Context, username string, limit int, cursor string) ([]*storage.HashtagFollow, string, error)
	MuteHashtag(ctx context.Context, username, hashtagName string, until *time.Time) error
	UnmuteHashtag(ctx context.Context, username, hashtagName string) error
	IsHashtagMuted(ctx context.Context, username, hashtagName string) (bool, error)
	GetHashtagNotificationSettings(ctx context.Context, username, hashtagName string) (*storage.HashtagNotificationSettings, error)
	UpdateHashtagNotificationSettings(ctx context.Context, username, hashtagName string, settings *storage.HashtagNotificationSettings) error

	// Instance announcement management
	CreateAnnouncement(ctx context.Context, announcement interface{}) error
	GetAnnouncement(ctx context.Context, announcementID string) (interface{}, error)
	UpdateAnnouncement(ctx context.Context, announcement interface{}) error
	DeleteAnnouncement(ctx context.Context, announcementID string) error
	GetActiveAnnouncements(ctx context.Context) ([]interface{}, error)
	GetAllAnnouncements(ctx context.Context, limit int, cursor string) ([]interface{}, string, error)

	// User announcement interactions
	DismissAnnouncement(ctx context.Context, username, announcementID string) error
	AddAnnouncementReaction(ctx context.Context, username, announcementID, emoji string) error
	RemoveAnnouncementReaction(ctx context.Context, username, announcementID, emoji string) error

	// Health checks and monitoring
	GetInfrastructureHealth(ctx context.Context) (*model.InfrastructureStatus, error)
	GetInstanceBudgets(ctx context.Context, exceeded *bool) ([]*model.InstanceBudget, error)
	GetInstanceHealthReport(ctx context.Context, domain string) (*model.InstanceHealthReport, error)
	GetInstanceRelationships(ctx context.Context, domain string) (*model.InstanceRelations, error)

	// Database health monitoring
	GetDatabaseStatus(ctx context.Context) (interface{}, error)
	GetDatabaseMetrics(ctx context.Context, since time.Time) (interface{}, error)
	RecordDatabaseError(ctx context.Context, operation string, err error) error

	// Service health monitoring
	RecordServiceHealth(ctx context.Context, service string, status interface{}, metrics map[string]interface{}) error
	GetServiceHealth(ctx context.Context, service string) (interface{}, error)
	GetAllServiceHealth(ctx context.Context) ([]interface{}, error)

	// Transaction management for atomic operations
	BeginTransaction(ctx context.Context) (Transaction, error)
	ExecuteInTransaction(ctx context.Context, fn func(tx Transaction) error) error

	// Storage metadata and configuration
	GetStorageInfo(ctx context.Context) (interface{}, error)
	GetStorageStatistics(ctx context.Context) (interface{}, error)

	// Maintenance operations
	PerformMaintenance(ctx context.Context, operation interface{}) error
	GetMaintenanceStatus(ctx context.Context) (interface{}, error)

	// Migration support
	GetMigrationStatus(ctx context.Context) (interface{}, error)
	UpdateMigrationProgress(ctx context.Context, step string, progress int) error
}

Storage represents the comprehensive storage interface that combines repository access with legacy storage operations still used throughout the Lesser application.

This interface bridges the gap between the legacy storage patterns and the new repository-based DynamORM approach, ensuring all existing functionality continues to work during the migration process.

CRITICAL PATTERNS PRESERVED: - Users: PK=`USER#username`, SK=`PROFILE` - Actors: PK=`ACTOR#username`, SK=`PROFILE` - Objects: PK=`object#id`, SK=`object#id` - DNS Cache: PK=`DNSCACHE#hostname`, SK=`ENTRY` - All existing GSI patterns and TTL logic

type StorageFactory

type StorageFactory interface {
	// CreateStorage creates a new storage implementation with the given options
	CreateStorage(options *StorageOptions) (Storage, error)

	// CreateTransactionStorage creates a storage implementation with transaction support
	CreateTransactionStorage(options *StorageOptions) (Storage, error)

	// CreateRepositoryStorage creates a repository-only storage implementation
	CreateRepositoryStorage(options *StorageOptions) (RepositoryAccess, error)
}

StorageFactory provides methods for creating storage implementations

type StorageOptions

type StorageOptions struct {
	// TableName is the DynamoDB table name for single-table design
	TableName string

	// Region is the AWS region for DynamoDB operations
	Region string

	// EnableCostTracking enables DynamoDB cost tracking and monitoring
	EnableCostTracking bool

	// EnableTransactions enables transaction support for atomic operations
	EnableTransactions bool

	// CacheConfig provides caching configuration for performance optimization
	CacheConfig *CacheConfig

	// MetricsConfig provides metrics and monitoring configuration
	MetricsConfig *MetricsConfig
}

StorageOptions provides configuration options for storage implementations

type StreamingCloudWatchRepository

type StreamingCloudWatchRepository interface {

	// GetQualityBreakdown retrieves cached quality breakdown metrics for a media item
	GetQualityBreakdown(ctx context.Context, mediaID string) (*models.StreamingCloudWatchMetrics, error)

	// CacheQualityBreakdown stores quality breakdown metrics in cache
	CacheQualityBreakdown(ctx context.Context, mediaID string, qualityMetrics map[string]models.QualityMetric) error

	// GetGeographicData retrieves cached geographic distribution metrics
	GetGeographicData(ctx context.Context, mediaID string) (*models.StreamingCloudWatchMetrics, error)

	// CacheGeographicData stores geographic distribution metrics in cache
	CacheGeographicData(ctx context.Context, mediaID string, geoMetrics map[string]models.GeographicMetric) error

	// GetConcurrentViewers retrieves cached concurrent viewer metrics
	GetConcurrentViewers(ctx context.Context, mediaID string) (*models.StreamingCloudWatchMetrics, error)

	// CacheConcurrentViewers stores concurrent viewer metrics in cache
	CacheConcurrentViewers(ctx context.Context, mediaID string, concurrentMetrics models.ConcurrentViewerMetrics) error

	// GetPerformanceMetrics retrieves cached performance metrics
	GetPerformanceMetrics(ctx context.Context, mediaID string) (*models.StreamingCloudWatchMetrics, error)

	// CachePerformanceMetrics stores performance metrics in cache
	CachePerformanceMetrics(ctx context.Context, mediaID string, perfMetrics models.StreamingPerformanceMetrics) error

	// GetAllCachedMetrics retrieves all cached metrics for a media item
	GetAllCachedMetrics(ctx context.Context, mediaID string) (map[string]*models.StreamingCloudWatchMetrics, error)

	// CleanupExpiredMetrics removes expired metrics from cache
	CleanupExpiredMetrics(ctx context.Context) error
}

StreamingCloudWatchRepository defines the interface for streaming CloudWatch metrics caching. This handles caching of streaming-related CloudWatch metrics for performance optimization.

type StreamingConnectionRepository

type StreamingConnectionRepository interface {
	// Connection lifecycle operations
	WriteConnection(ctx context.Context, connectionID, userID, username string, streams []string) (*models.WebSocketConnection, error)
	GetConnection(ctx context.Context, connectionID string) (*models.WebSocketConnection, error)
	UpdateConnection(ctx context.Context, connection *models.WebSocketConnection) error
	DeleteConnection(ctx context.Context, connectionID string) error
	UpdateConnectionState(ctx context.Context, connectionID string, newState models.ConnectionState, reason string) error
	UpdateConnectionActivity(ctx context.Context, connectionID string) error

	// Subscription operations
	WriteSubscription(ctx context.Context, connectionID, userID, stream string) error
	DeleteSubscription(ctx context.Context, connectionID, stream string) error
	DeleteAllSubscriptions(ctx context.Context, connectionID string) error
	GetSubscriptionsForStream(ctx context.Context, stream string) ([]models.WebSocketSubscription, error)

	// Connection queries
	GetConnectionsByUser(ctx context.Context, userID string) ([]models.WebSocketConnection, error)
	GetConnectionsByState(ctx context.Context, state models.ConnectionState) ([]models.WebSocketConnection, error)
	GetIdleConnections(ctx context.Context, idleThreshold time.Time) ([]models.WebSocketConnection, error)
	GetStaleConnections(ctx context.Context, staleThreshold time.Time) ([]models.WebSocketConnection, error)
	GetHealthyConnections(ctx context.Context) ([]models.WebSocketConnection, error)
	GetUnhealthyConnections(ctx context.Context) ([]models.WebSocketConnection, error)

	// Connection counts
	GetActiveConnectionsCount(ctx context.Context, userID string) (int, error)
	GetTotalActiveConnectionsCount(ctx context.Context) (int, error)
	GetConnectionCountByState(ctx context.Context, state models.ConnectionState) (int, error)
	GetUserConnectionCount(ctx context.Context, userID string) (int, error)

	// Connection management
	MarkConnectionsIdle(ctx context.Context, idleThreshold time.Duration) (int, error)
	CloseTimedOutConnections(ctx context.Context) (int, error)
	ReclaimIdleConnections(ctx context.Context, maxIdleConnections int) (int, error)
	CleanupExpiredConnections(ctx context.Context) (int, error)

	// Resource limits
	EnforceResourceLimits(ctx context.Context, connectionID string, messageSize int64) error
	GetConnectionPool(ctx context.Context) (map[string]interface{}, error)

	// Message and activity tracking
	RecordConnectionMessage(ctx context.Context, connectionID string, sent bool, messageSize int64) error
	RecordConnectionError(ctx context.Context, connectionID string, errorMsg string) error
	RecordPing(ctx context.Context, connectionID string) error
	RecordPong(ctx context.Context, connectionID string) error
}

StreamingConnectionRepository defines the interface for WebSocket connection operations. This handles WebSocket connections with complete lifecycle management.

type TableCostStats

type TableCostStats struct {
	TableName               string
	StartTime               time.Time
	EndTime                 time.Time
	Count                   int
	TotalOperations         int64
	TotalItemCount          int64
	TotalReadCapacityUnits  float64
	TotalWriteCapacityUnits float64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostPerOperation float64
	OperationBreakdown      map[string]OperationCostStats
}

TableCostStats represents cost statistics for a table

type ThreadContextResult

type ThreadContextResult struct {
	RootStatusID      string
	RequestedStatusID string
	Nodes             []*models.ThreadNode
	MissingReplies    []*models.MissingReply

	// Calculated stats
	ParticipantCount int
	TotalReplyCount  int
	MissingCount     int
	MaxDepth         int
}

ThreadContextResult represents the complete context of a thread

type ThreadRepository

type ThreadRepository interface {

	// SaveThreadSync saves or updates a thread sync record
	SaveThreadSync(ctx context.Context, sync *models.ThreadSync) error

	// GetThreadSync retrieves a thread sync record by status ID
	GetThreadSync(ctx context.Context, statusID string) (*models.ThreadSync, error)

	// SaveThreadNode saves or updates a thread node
	SaveThreadNode(ctx context.Context, node *models.ThreadNode) error

	// GetThreadNodes retrieves all nodes for a thread by root status ID
	GetThreadNodes(ctx context.Context, rootStatusID string) ([]*models.ThreadNode, error)

	// GetThreadNode retrieves a single thread node by status ID
	GetThreadNode(ctx context.Context, rootStatusID, statusID string) (*models.ThreadNode, error)

	// GetThreadNodeByStatusID retrieves a thread node by status ID using GSI
	GetThreadNodeByStatusID(ctx context.Context, statusID string) (*models.ThreadNode, error)

	// BulkSaveThreadNodes saves multiple thread nodes in a batch
	BulkSaveThreadNodes(ctx context.Context, nodes []*models.ThreadNode) error

	// MarkMissingReplies marks multiple replies as missing in a thread
	MarkMissingReplies(ctx context.Context, rootStatusID, parentStatusID string, replyIDs []string) error

	// GetMissingReplies retrieves all missing replies for a thread
	GetMissingReplies(ctx context.Context, rootStatusID string) ([]*models.MissingReply, error)

	// SaveMissingReply saves or updates a missing reply record
	SaveMissingReply(ctx context.Context, missing *models.MissingReply) error

	// DeleteMissingReply deletes a missing reply record (used when resolved)
	DeleteMissingReply(ctx context.Context, rootStatusID, replyID string) error

	// GetPendingMissingReplies retrieves missing replies that should be retried
	GetPendingMissingReplies(ctx context.Context, limit int) ([]*models.MissingReply, error)

	// GetThreadContext builds a complete thread context by querying nodes
	GetThreadContext(ctx context.Context, statusID string) (*ThreadContextResult, error)
}

ThreadRepository defines the interface for thread synchronization and traversal operations. This handles thread sync records, thread nodes, and missing reply tracking.

type TimelineFilters

type TimelineFilters struct {
	OnlyMedia      bool   // Only show entries with media
	ExcludeReplies bool   // Exclude reply entries
	ExcludeBoosts  bool   // Exclude boost/announce entries
	Language       string // Filter by language
	MinID          string // Minimum entry ID (for pagination)
	MaxID          string // Maximum entry ID (for pagination)
}

TimelineFilters represents filters for timeline queries

type TimelineRepository

type TimelineRepository interface {
	// Core timeline entry operations
	CreateTimelineEntry(ctx context.Context, entry *models.Timeline) error
	CreateTimelineEntries(ctx context.Context, entries []*models.Timeline) error
	GetTimelineEntry(ctx context.Context, timelineType, timelineID, entryID string, timelineAt time.Time) (*models.Timeline, error)
	UpdateTimelineEntry(ctx context.Context, entry *models.Timeline) error
	DeleteTimelineEntry(ctx context.Context, timelineType, timelineID, entryID string, timelineAt time.Time) error

	// Timeline retrieval by type
	GetHomeTimeline(ctx context.Context, username string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetPublicTimeline(ctx context.Context, local bool, limit int, cursor string) ([]*models.Timeline, string, error)
	GetListTimeline(ctx context.Context, listID string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetDirectTimeline(ctx context.Context, username string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetHashtagTimeline(ctx context.Context, hashtag string, local bool, limit int, cursor string) ([]*models.Timeline, string, error)

	// Timeline retrieval by index
	GetTimelineEntriesByPost(ctx context.Context, postID string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetTimelineEntriesByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetTimelineEntriesByVisibility(ctx context.Context, visibility string, limit int, cursor string) ([]*models.Timeline, string, error)
	GetTimelineEntriesByLanguage(ctx context.Context, language string, limit int, cursor string) ([]*models.Timeline, string, error)

	// Advanced timeline queries
	GetTimelineEntriesInRange(ctx context.Context, timelineType, timelineID string, startTime, endTime time.Time, limit int) ([]*models.Timeline, error)
	GetTimelineEntriesWithFilters(ctx context.Context, timelineType, timelineID string, filters TimelineFilters, limit int, cursor string) ([]*models.Timeline, string, error)
	CountTimelineEntries(ctx context.Context, timelineType, timelineID string) (int, error)

	// Batch operations
	DeleteTimelineEntriesByPost(ctx context.Context, postID string) error
	DeleteExpiredTimelineEntries(ctx context.Context, before time.Time) error
	RemoveFromTimelines(ctx context.Context, objectID string) error

	// Conversation support (timeline interface compatibility)
	GetConversations(ctx context.Context, username string, limit int, cursor string) ([]*models.Conversation, string, error)
}

TimelineRepository defines the interface for timeline operations. This handles timeline entry management for home, public, list, direct, and hashtag timelines.

type TrackingRepository

type TrackingRepository interface {

	// Create creates a new cost tracking record
	Create(ctx context.Context, tracking *models.DynamoDBCostRecord) error

	// BatchCreate creates multiple cost tracking records efficiently
	BatchCreate(ctx context.Context, trackingList []*models.DynamoDBCostRecord) error

	// Get retrieves a cost tracking record by operation type, timestamp and ID
	Get(ctx context.Context, operationType, id string, timestamp time.Time) (*models.DynamoDBCostRecord, error)

	// ListByOperationType lists cost tracking records by operation type within a time range
	ListByOperationType(ctx context.Context, operationType string, startTime, endTime time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

	// ListByTable lists cost tracking records by table within a time range
	ListByTable(ctx context.Context, tableName string, startTime, endTime time.Time, limit int, cursor string) ([]*models.DynamoDBCostRecord, string, error)

	// GetRecentCosts retrieves recent cost tracking records across all operations
	GetRecentCosts(ctx context.Context, since time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

	// GetAggregated retrieves aggregated cost tracking
	GetAggregated(ctx context.Context, period, operationType string, windowStart time.Time) (*models.DynamoDBCostAggregation, error)

	// CreateAggregated creates an aggregated cost tracking record
	CreateAggregated(ctx context.Context, aggregated *models.DynamoDBCostAggregation) error

	// UpdateAggregated updates an existing aggregated cost tracking record
	UpdateAggregated(ctx context.Context, aggregated *models.DynamoDBCostAggregation) error

	// ListAggregatedByPeriod lists aggregated cost tracking for a period
	ListAggregatedByPeriod(ctx context.Context, period, operationType string, startTime, endTime time.Time, limit int, cursor string) ([]*models.DynamoDBCostAggregation, string, error)

	// Aggregate performs aggregation of raw cost tracking data
	Aggregate(ctx context.Context, operationType, period string, windowStart, windowEnd time.Time) error

	// GetAggregatedCostsByPeriod retrieves aggregated costs for a specific period
	GetAggregatedCostsByPeriod(ctx context.Context, period string, startDate, endDate time.Time) ([]*models.DynamoDBCostAggregation, error)

	// GetTableCostStats calculates cost statistics for a table
	GetTableCostStats(ctx context.Context, tableName string, startTime, endTime time.Time) (*TableCostStats, error)

	// GetHighCostOperations returns operations that exceed a cost threshold
	GetHighCostOperations(ctx context.Context, thresholdDollars float64, startTime, endTime time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

	// GetCostTrends calculates cost trends over time
	GetCostTrends(ctx context.Context, period string, operationType string, lookbackDays int) (*CostTrend, error)

	// GetCostsByOperationType retrieves costs grouped by operation type
	GetCostsByOperationType(ctx context.Context, startDate, endDate time.Time) (map[string]*models.DynamoDBServiceCostStats, error)

	// GetCostsByService retrieves costs grouped by service/function
	GetCostsByService(ctx context.Context, startDate, endDate time.Time) (map[string]*models.DynamoDBServiceCostStats, error)

	// GetCostsByDateRange returns individual cost records for the specified date range
	GetCostsByDateRange(ctx context.Context, startDate, endDate time.Time) ([]*models.DynamoDBCostRecord, error)

	// GetDailyAggregates returns aggregated daily costs for the specified date range
	GetDailyAggregates(ctx context.Context, startDate, endDate time.Time) ([]*DailyAggregate, error)

	// GetMonthlyAggregate returns aggregated costs for the specified month
	GetMonthlyAggregate(ctx context.Context, year, month int) (*MonthlyAggregate, error)

	// GetCostProjections retrieves the most recent cost projection for the given period
	GetCostProjections(ctx context.Context, period string) (*storage.CostProjection, error)

	// CreateRelayCost creates a new relay cost record
	CreateRelayCost(ctx context.Context, relayCost *models.RelayCost) error

	// GetRelayCostsByURL retrieves relay costs for a specific relay URL within a time range
	GetRelayCostsByURL(ctx context.Context, relayURL string, startTime, endTime time.Time, limit int, cursor string, operationType string) ([]*models.RelayCost, string, error)

	// GetRelayCostsByDateRange retrieves relay costs for all relays within a date range
	GetRelayCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.RelayCost, error)

	// CreateRelayMetrics creates or updates relay metrics
	CreateRelayMetrics(ctx context.Context, metrics *models.RelayMetrics) error

	// UpdateRelayMetrics updates existing relay metrics
	UpdateRelayMetrics(ctx context.Context, metrics *models.RelayMetrics) error

	// GetRelayMetrics retrieves relay metrics for a specific relay and period
	GetRelayMetrics(ctx context.Context, relayURL, period string, windowStart time.Time) (*models.RelayMetrics, error)

	// GetRelayMetricsHistory retrieves metrics history for a relay
	GetRelayMetricsHistory(ctx context.Context, relayURL string, startTime, endTime time.Time, limit int, cursor string) ([]*models.RelayMetrics, string, error)

	// CreateRelayBudget creates a new relay budget configuration
	CreateRelayBudget(ctx context.Context, budget *models.RelayBudget) error
}

TrackingRepository defines the interface for cost tracking operations. This handles DynamoDB cost tracking, aggregation, relay costs, and metrics.

type Transaction

type Transaction interface {
	// Commit applies all transaction operations atomically
	Commit() error

	// Rollback discards all transaction operations
	Rollback() error

	// GetContext returns the transaction context for operation scoping
	GetContext() context.Context

	// IsActive returns true if the transaction is still active (not committed or rolled back)
	IsActive() bool

	// Actor operations within transaction
	TxCreateActor(actor *activitypub.Actor, privateKey string) error
	TxUpdateActor(actor *activitypub.Actor) error
	TxDeleteActor(username string) error

	// User operations within transaction
	TxCreateUser(user interface{}) error
	TxUpdateUser(user interface{}) error
	TxDeleteUser(username string) error

	// Object operations within transaction
	TxCreateObject(object interface{}) error
	TxUpdateObject(objectID string, object interface{}) error
	TxDeleteObject(objectID string) error

	// Activity operations within transaction
	TxCreateActivity(activity *activitypub.Activity) error
	TxUpdateActivity(activity *activitypub.Activity) error
	TxDeleteActivity(activityID string) error

	// Relationship operations within transaction
	TxCreateRelationship(followerUsername, followingID, activityID string) error
	TxRemoveRelationship(followerUsername, followingID string) error
	TxUpdateRelationshipStatus(followerUsername, followingID string, status string) error
}

Transaction interface for atomic operations across multiple storage operations This provides ACID transaction support for complex multi-step operations

type TrendingRepository

type TrendingRepository interface {

	// RecordHashtagUsage records when a hashtag is used in a status
	RecordHashtagUsage(ctx context.Context, hashtag string, statusID string, authorID string) error

	// RecordStatusEngagement records engagement on a status (like, boost, reply)
	RecordStatusEngagement(ctx context.Context, statusID string, engagementType string, userID string) error

	// RecordLinkShare records when a link is shared in a status
	RecordLinkShare(ctx context.Context, linkURL string, statusID string, authorID string) error

	// GetTrendingHashtags returns the top trending hashtags since the given time
	GetTrendingHashtags(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

	// GetTrendingStatuses returns the top trending statuses since the given time
	GetTrendingStatuses(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingStatus, error)

	// GetTrendingLinks returns the top trending links since the given time
	GetTrendingLinks(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingLink, error)

	// GetRecentHashtags returns recent hashtags since the given time
	GetRecentHashtags(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

	// GetRecentStatusesWithEngagement returns recent statuses with engagement since the given time
	GetRecentStatusesWithEngagement(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingStatus, error)

	// GetRecentLinks returns recent links since the given time
	GetRecentLinks(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingLink, error)

	// StoreEngagementMetrics stores engagement metrics for a status
	StoreEngagementMetrics(ctx context.Context, metrics *storage.EngagementMetrics) error

	// GetEngagementMetrics retrieves stored engagement metrics for a status
	GetEngagementMetrics(ctx context.Context, statusID string) (*storage.EngagementMetrics, error)

	// StoreHashtagTrend stores a hashtag trend record
	StoreHashtagTrend(ctx context.Context, trend any) error

	// StoreStatusTrend stores a status trend record
	StoreStatusTrend(ctx context.Context, trend any) error

	// StoreLinkTrend stores a link trend record
	StoreLinkTrend(ctx context.Context, trend any) error

	// SetStatusRepository sets the status repository dependency for cross-repository operations
	SetStatusRepository(statusRepo interface{})
}

TrendingRepository defines the interface for trending and analytics operations. This handles trending hashtags, statuses, links, and engagement metrics.

type TrustRepository

type TrustRepository interface {

	// CreateTrustRelationship creates or updates a trust relationship between two actors
	CreateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

	// GetTrustRelationship retrieves a specific trust relationship
	GetTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) (*storage.TrustRelationship, error)

	// UpdateTrustRelationship updates an existing trust relationship
	UpdateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

	// DeleteTrustRelationship removes a trust relationship
	DeleteTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) error

	// GetTrustRelationships retrieves all trust relationships for a truster with pagination
	GetTrustRelationships(ctx context.Context, trusterID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

	// GetTrustedByRelationships retrieves all relationships where the actor is trusted with pagination
	GetTrustedByRelationships(ctx context.Context, trusteeID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

	// GetAllTrustRelationships retrieves all trust relationships for admin visualization
	GetAllTrustRelationships(ctx context.Context, limit int) ([]*storage.TrustRelationship, error)

	// GetTrustScore retrieves a cached trust score or calculates it
	GetTrustScore(ctx context.Context, actorID, category string) (*storage.TrustScore, error)

	// UpdateTrustScore updates a cached trust score
	UpdateTrustScore(ctx context.Context, score *storage.TrustScore) error

	// GetUserTrustScore retrieves the trust score for a user
	GetUserTrustScore(ctx context.Context, userID string) (float64, error)

	// RecordTrustUpdate records a trust score update event
	RecordTrustUpdate(ctx context.Context, update *storage.TrustUpdate) error
}

TrustRepository provides methods for trust relationship management. This handles trust relationships between actors, trust scores, and trust updates.

type UserRepository

type UserRepository interface {
	// Core CRUD operations
	CreateUser(ctx context.Context, user *storage.User) error
	GetUser(ctx context.Context, username string) (*storage.User, error)
	GetUserByEmail(ctx context.Context, email string) (*storage.User, error)
	UpdateUser(ctx context.Context, username string, updates map[string]any) error
	DeleteUser(ctx context.Context, username string) error

	ListUsers(ctx context.Context, limit int32, cursor string) ([]*storage.User, string, error)
	ListAgents(ctx context.Context, limit int32, cursor string) ([]*storage.User, string, error)
	ListUsersByRole(ctx context.Context, role string) ([]*storage.User, error)

	// Count operations
	GetActiveUserCount(ctx context.Context, days int) (int64, error)
	GetTotalUserCount(ctx context.Context) (int64, error)

	// OAuth provider operations
	GetUserByProviderID(ctx context.Context, provider, providerID string) (*storage.User, error)
	LinkProviderAccount(ctx context.Context, username, provider, providerID string) error
	UnlinkProviderAccount(ctx context.Context, username, provider string) error
	GetLinkedProviders(ctx context.Context, username string) ([]string, error)

	// Account pins (endorsed accounts)
	CreateAccountPin(ctx context.Context, pin *storage.AccountPin) error
	DeleteAccountPin(ctx context.Context, username, pinnedActorID string) error
	GetAccountPins(ctx context.Context, username string) ([]*storage.AccountPin, error)
	IsAccountPinned(ctx context.Context, username, actorID string) (bool, error)

	// Account notes
	CreateAccountNote(ctx context.Context, note *storage.AccountNote) error
	GetAccountNote(ctx context.Context, username, targetActorID string) (*storage.AccountNote, error)
	UpdateAccountNote(ctx context.Context, note *storage.AccountNote) error
	DeleteAccountNote(ctx context.Context, username, targetActorID string) error

	// Reputation operations
	StoreReputation(ctx context.Context, actorID string, reputation *storage.Reputation) error
	GetReputation(ctx context.Context, actorID string) (*storage.Reputation, error)
	GetReputationHistory(ctx context.Context, actorID string, limit int) ([]*storage.Reputation, error)
	GetUserTrustScore(ctx context.Context, userID string) (float64, error)

	// Vouch operations
	CreateVouch(ctx context.Context, vouch *storage.Vouch) error
	GetVouch(ctx context.Context, vouchID string) (*storage.Vouch, error)
	GetVouchesByActor(ctx context.Context, actorID string, activeOnly bool) ([]*storage.Vouch, error)
	GetVouchesForActor(ctx context.Context, actorID string, activeOnly bool) ([]*storage.Vouch, error)
	UpdateVouchStatus(ctx context.Context, vouchID string, active bool, revokedAt *time.Time) error
	GetMonthlyVouchCount(ctx context.Context, actorID string, year int, month time.Month) (int, error)

	// Trust relationship operations
	CreateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error
	GetTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) (*storage.TrustRelationship, error)
	UpdateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error
	DeleteTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) error
	GetTrustRelationships(ctx context.Context, trusterID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)
	GetTrustedByRelationships(ctx context.Context, trusteeID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)
	GetAllTrustRelationships(ctx context.Context, limit int) ([]*storage.TrustRelationship, error)

	// Trust score operations
	GetTrustScore(ctx context.Context, actorID, category string) (*storage.TrustScore, error)
	UpdateTrustScore(ctx context.Context, score *storage.TrustScore) error
	RecordTrustUpdate(ctx context.Context, update *storage.TrustUpdate) error

	// User preferences operations
	GetUserLanguagePreference(ctx context.Context, username string) (string, error)
	SetUserLanguagePreference(ctx context.Context, username string, language string) error
	GetUserPreferences(ctx context.Context, username string) (*storage.UserPreferences, error)
	UpdateUserPreferences(ctx context.Context, username string, preferences *storage.UserPreferences) error
	SetPreference(ctx context.Context, username, key string, value any) error
	GetPreference(ctx context.Context, username, key string) (any, error)
	GetAllPreferences(ctx context.Context, username string) (map[string]any, error)
	UpdatePreferences(ctx context.Context, username string, preferences map[string]any) error

	// Follow operations
	AcceptFollow(ctx context.Context, followerUsername, followedUsername string) error
	RejectFollow(ctx context.Context, followerUsername, followedUsername string) error
	GetFollowRequestState(ctx context.Context, followerID, targetID string) (string, error)
	GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	RemoveFromFollowers(ctx context.Context, username, followerUsername string) error

	// Conversation mute operations
	CreateConversationMute(ctx context.Context, mute *storage.ConversationMute) error
	DeleteConversationMute(ctx context.Context, username, conversationID string) error
	IsConversationMuted(ctx context.Context, username, conversationID string) (bool, error)
	GetMutedConversations(ctx context.Context, username string) ([]string, error)

	// Notification operations
	IsNotificationMuted(ctx context.Context, userID, targetID string) (bool, error)

	// Remote actor caching
	CacheRemoteActor(ctx context.Context, handle string, actor *activitypub.Actor, ttl time.Duration) error

	// Bookmark operations
	CreateBookmark(ctx context.Context, username, objectID string) error
	RemoveBookmark(ctx context.Context, username, objectID string) error
	GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	IsBookmarked(ctx context.Context, username, objectID string) (bool, error)

	// Timeline operations
	DeleteFromTimeline(ctx context.Context, timelineType, timelineID, entryID string) error
	DeleteExpiredTimelineEntries(ctx context.Context, before time.Time) error
	GetDirectTimeline(ctx context.Context, username string, limit int, cursor string) ([]*storage.TimelineEntry, string, error)
	GetHashtagTimeline(ctx context.Context, hashtag string, local bool, limit int, cursor string) ([]*storage.TimelineEntry, string, error)
	GetListTimeline(ctx context.Context, listID string, limit int, cursor string) ([]*storage.TimelineEntry, string, error)

	// Fan-out operations
	FanOutPost(ctx context.Context, activity *activitypub.Activity) error
}

UserRepository provides methods for user data management. This interface mirrors the public methods of repositories.UserRepository, enabling mock implementations for unit testing.

type WebSocketConnectionCostSummary

type WebSocketConnectionCostSummary struct {
	ConnectionID            string
	UserID                  string
	Username                string
	StartTime               time.Time
	EndTime                 time.Time
	Count                   int
	TotalConnectionMinutes  float64
	TotalMessages           int64
	TotalMessageBytes       int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	TotalOperations         int64
	AverageCostPerOperation float64
	AverageMessageSize      float64
	OperationBreakdown      map[string]*WebSocketOperationCostStats
}

WebSocketConnectionCostSummary represents cost summary for a WebSocket connection

type WebSocketCostRepository

type WebSocketCostRepository interface {

	// CreateRecord creates a new WebSocket cost tracking record
	CreateRecord(ctx context.Context, record *models.WebSocketCostRecord) error

	// Create creates a new WebSocket cost tracking record (legacy method name)
	Create(ctx context.Context, record *models.WebSocketCostRecord) error

	// BatchCreate creates multiple WebSocket cost tracking records efficiently
	BatchCreate(ctx context.Context, records []*models.WebSocketCostRecord) error

	// GetRecord retrieves a WebSocket cost tracking record by operation type, timestamp and ID
	GetRecord(ctx context.Context, operationType, id string, timestamp time.Time) (*models.WebSocketCostRecord, error)

	// Get retrieves a WebSocket cost tracking record (legacy method name)
	Get(ctx context.Context, operationType, id string, timestamp time.Time) (*models.WebSocketCostRecord, error)

	// ListByOperationType lists WebSocket cost tracking records by operation type within a time range
	ListByOperationType(ctx context.Context, operationType string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

	// ListByConnection lists WebSocket cost tracking records by connection ID within a time range
	ListByConnection(ctx context.Context, connectionID string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

	// ListByUser lists WebSocket cost tracking records by user ID within a time range
	ListByUser(ctx context.Context, userID string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

	// GetRecentCosts retrieves recent WebSocket cost tracking records across all operations
	GetRecentCosts(ctx context.Context, since time.Time, limit int) ([]*models.WebSocketCostRecord, error)

	// GetConnectionCostSummary calculates cost summary for a specific connection
	GetConnectionCostSummary(ctx context.Context, connectionID string, startTime, endTime time.Time) (*WebSocketConnectionCostSummary, error)

	// GetUserCostSummary calculates cost summary for a specific user
	GetUserCostSummary(ctx context.Context, userID string, startTime, endTime time.Time) (*WebSocketUserCostSummary, error)

	// CreateBudget creates a new WebSocket cost budget for a user
	CreateBudget(ctx context.Context, budget *models.WebSocketCostBudget) error

	// UpdateBudget updates an existing WebSocket cost budget
	UpdateBudget(ctx context.Context, budget *models.WebSocketCostBudget) error

	// GetBudget retrieves WebSocket cost budget for a user and period
	GetBudget(ctx context.Context, userID, period string) (*models.WebSocketCostBudget, error)

	// GetUserBudgets retrieves all budgets for a user
	GetUserBudgets(ctx context.Context, userID string) ([]*models.WebSocketCostBudget, error)

	// UpdateBudgetUsage updates budget usage based on new cost records
	UpdateBudgetUsage(ctx context.Context, userID string, additionalCostMicroCents int64) error

	// CheckBudgetLimits checks if a user has exceeded their budget limits
	CheckBudgetLimits(ctx context.Context, userID string) (*BudgetStatus, error)

	// CreateAggregation creates a new WebSocket cost aggregation
	CreateAggregation(ctx context.Context, aggregation *models.WebSocketCostAggregation) error

	// UpdateAggregation updates an existing WebSocket cost aggregation
	UpdateAggregation(ctx context.Context, aggregation *models.WebSocketCostAggregation) error

	// GetAggregation retrieves WebSocket cost aggregation
	GetAggregation(ctx context.Context, period, operationType string, windowStart time.Time) (*models.WebSocketCostAggregation, error)

	// GetUserAggregation retrieves WebSocket cost aggregation for a specific user
	GetUserAggregation(ctx context.Context, userID, period, operationType string, windowStart time.Time) (*models.WebSocketCostAggregation, error)

	// ListAggregationsByPeriod lists WebSocket cost aggregations for a period
	ListAggregationsByPeriod(ctx context.Context, period, operationType string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostAggregation, error)

	// AggregateWebSocketCosts performs aggregation of raw WebSocket cost data
	AggregateWebSocketCosts(ctx context.Context, operationType, period string, windowStart, windowEnd time.Time) error
}

WebSocketCostRepository defines the interface for WebSocket cost tracking operations. This handles WebSocket connection costs, budgets, and aggregations.

type WebSocketOperationCostStats

type WebSocketOperationCostStats struct {
	OperationType         string
	Count                 int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
	TotalProcessingTime   int64
	AverageProcessingTime float64
	TotalMessages         int64
}

WebSocketOperationCostStats represents cost statistics for a WebSocket operation type

type WebSocketStreamCostStats

type WebSocketStreamCostStats struct {
	StreamName            string
	OperationCount        int64
	MessageCount          int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
}

WebSocketStreamCostStats represents cost statistics for a WebSocket stream

type WebSocketUserCostSummary

type WebSocketUserCostSummary struct {
	UserID                    string
	Username                  string
	StartTime                 time.Time
	EndTime                   time.Time
	Count                     int
	TotalConnectionMinutes    float64
	TotalMessages             int64
	TotalMessageBytes         int64
	TotalCostMicroCents       int64
	TotalCostDollars          float64
	TotalOperations           int64
	TotalIdleTime             int64
	UniqueConnections         int64
	UniqueStreams             int64
	AverageCostPerOperation   float64
	AverageMessageSize        float64
	AverageIdleTime           float64
	AverageCostPerConnection  float64
	AverageConnectionDuration float64
	OperationBreakdown        map[string]*WebSocketOperationCostStats
	StreamBreakdown           map[string]*WebSocketStreamCostStats
}

WebSocketUserCostSummary represents cost summary for a user's WebSocket usage

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL