repositories

package
v1.1.7 Latest Latest
Warning

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

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

Documentation

Overview

Package repositories provides DynamORM repository implementations for account and user management operations.

Package repositories provides DynamoDB-backed repository implementations using DynamORM. This package contains the core repository layer that abstracts database operations, implements the Lift framework patterns, and provides comprehensive cost tracking.

Package repositories provides repository extensions for Moderation ML

Package repositories provides repository implementations for data access layer

Index

Constants

View Source
const (
	FieldName         = "name"
	FieldWebsite      = "website"
	FieldRedirectURIs = "redirect_uris"
	FieldScopes       = "scopes"
)

OAuth field constants

View Source
const (
	// DefaultDomain is the default domain for local development
	DefaultDomain = "localhost"
	// LinkTypePhoto represents photo link type
	LinkTypePhoto = "photo"
	// LinkTypeVideo represents video link type
	LinkTypeVideo = "video"
)
View Source
const (
	SortOrderAsc  = "ASC"
	SortOrderDesc = "DESC"
)

Sort order constants

View Source
const (
	AccountStatusEmail     = "email"
	AccountStatusSuspended = "suspended"
)

Account status constants

View Source
const (
	StatusUnknown   = "unknown"
	StatusCompleted = "completed"
	StatusFailed    = "failed"
	StatusTimeout   = "timeout"
	StatusError     = "error"
	StatusPending   = "pending"
	StatusHealthy   = "healthy"
	StatusCritical  = "critical"
	StatusWarning   = "warning"
	StatusLow       = "low"
	StatusHigh      = "high"
	StatusMedium    = "medium"
)

Status constants - these supplement models.Status* constants

View Source
const (
	PeriodDaily   = "daily"
	PeriodWeekly  = "weekly"
	PeriodMonthly = "monthly"
)

Period constants - these supplement models.Period* constants

View Source
const (
	RepliesPolicyList     = "list"
	RepliesPolicyFollowed = "followed"
	RepliesPolicyNone     = "none"
)

Replies policy constants

View Source
const (
	WSEventConnect    = "connect"
	WSEventDisconnect = "disconnect"
	WSEventMessageIn  = "message_in"
	WSEventMessageOut = "message_out"
	WSEventSubscribe  = "subscribe"
)

WebSocket event types

View Source
const (
	ActivityTypeNote    = "Note"
	ModerationTypeEvent = "EVENT"
	VisibilityPublic    = "public"
	VisibilityDisabled  = "disabled"
	TagTypeMention      = "Mention"
)

Other repository constants

View Source
const (
	PrefKeyLanguage                  = "language"
	PrefKeyDefaultPostingVisibility  = "default_posting_visibility"
	PrefKeyDefaultMediaSensitive     = "default_media_sensitive"
	PrefKeyExpandSpoilers            = "expand_spoilers"
	PrefKeyExpandMedia               = "expand_media"
	PrefKeyAutoplayGifs              = "autoplay_gifs"
	PrefKeyShowFollowCounts          = "show_follow_counts"
	PrefKeyPreferredTimelineOrder    = "preferred_timeline_order"
	PrefKeySearchSuggestionsEnabled  = "search_suggestions_enabled"
	PrefKeyPersonalizedSearchEnabled = "personalized_search_enabled"
	PrefKeyReblogFilters             = "reblog_filters"
	PrefKeyStreamingDefaultQuality   = "streaming_default_quality"
	PrefKeyStreamingAutoQuality      = "streaming_auto_quality"
	PrefKeyStreamingPreloadNext      = "streaming_preload_next"
	PrefKeyStreamingDataSaver        = "streaming_data_saver"
	PrefKeyDirect                    = "direct"
)

User preference keys

View Source
const (
	DLQStatusNew          = "new"
	DLQStatusReprocessing = "reprocessing"
	DLQStatusResolved     = "resolved"
	DLQStatusFailed       = "failed"
	DLQStatusAbandoned    = "abandoned"
)

DLQ message status constants

View Source
const (
	EntityUser                     = "user"
	EntityActor                    = "actor"
	EntityAlert                    = "alert"
	EntityObject                   = "object"
	EntityFollow                   = "follow"
	EntityBlock                    = "block"
	EntityMute                     = "mute"
	EntityList                     = "list"
	EntityHashtag                  = "hashtag"
	EntityFeaturedTag              = "featured tag"
	EntityMedia                    = "media"
	EntityOAuthState               = "OAuth state"
	EntityAuthCode                 = "authorization code"
	EntityRefreshToken             = "refresh token"
	EntityOAuthClient              = "OAuth client"
	EntityOAuthConsent             = "OAuth consent"
	EntityWebAuthnCredential       = "WebAuthn credential" // #nosec G101 -- entity name string, not a credential
	EntityWebAuthnChallenge        = "WebAuthn challenge"
	EntityWalletCredential         = "wallet credential" // #nosec G101 -- entity name string, not a credential
	EntityWalletChallenge          = "wallet challenge"
	EntitySession                  = "session"
	EntityPasswordReset            = "password reset"
	EntityTimelineEntry            = "timeline entry"
	EntityConversation             = "conversation"
	EntityBookmark                 = "bookmark"
	EntityFilter                   = "filter"
	EntityFilterKeyword            = "filter keyword"
	EntityFilterStatus             = "filter status"
	EntityReport                   = "report"
	EntityFlag                     = "flag"
	EntityModerationEvent          = "moderation event"
	EntityModerationDecision       = "moderation decision"
	EntityModerationPattern        = "moderation pattern"
	EntityAnnounce                 = "announce"
	EntityAccountPin               = "account pin"
	EntityAccountNote              = "account note"
	EntityStatusPin                = "status pin"
	EntityCircuitBreaker           = "circuit breaker"
	EntityCircuitState             = "circuit state"
	EntityCircuitEvent             = "circuit breaker event"
	EntityActivity                 = "activity"
	EntityFeature                  = "feature"
	EntityThreatIntel              = "threat intel"
	EntityThreatIndicator          = "threat indicator"
	EntityWebSocketCost            = "websocket cost"
	EntityWebSocketCostBudget      = "websocket cost budget"
	EntityWebSocketCostAggregation = "websocket cost aggregation"
	EntityAudit                    = "audit log"
	EntityAI                       = "ai analysis"
	EntityQueryCache               = "query cache"
	EntityCloudWatchMetrics        = "cloudwatch metrics"
	EntityRateLimit                = "rate limit"
	EntityMarker                   = "marker"
	EntityTrust                    = "trust"
	EntityTrustRelationship        = "trust relationship"
	EntityTrustScore               = "trust score"
	EntityTrustUpdate              = "trust update"
	EntityPublicKeyCache           = "public key cache"
	EntityRoutingMetrics           = "routing metrics"
	EntityNotification             = "notification"
	EntityCSRFToken                = "csrf token"
	EntityStatus                   = "status"
	EntityScheduledStatus          = "scheduled status"
	EntityInstanceDomainBlock      = "instance domain block"
	EntityEmailDomainBlock         = "email domain block"
	EntityDomainAllow              = "domain allow"
	EntityExport                   = "export"
	EntityExportCostTracking       = "export cost tracking"
	EntityImport                   = "import"
	EntityImportCostTracking       = "import cost tracking"
	EntityRecovery                 = "recovery"
	EntityRecoveryCode             = "recovery code"
	EntityRecoveryToken            = "recovery token"
	EntityTrustee                  = "trustee"
	EntityRecoveryRequest          = "recovery request"
	EntityInstanceHealth           = "instance health"
	EntityHealthSummary            = "health summary"
	EntityConnectivityTest         = "connectivity test"
	EntityNodeInfo                 = "nodeinfo verification"
	EntityWebFinger                = "webfinger resolution"
	EntitySeveredRelationship      = "severed relationship"
	EntityDeliveryRecord           = "delivery record"
	EntityFederationMetrics        = "federation metrics"
	EntitySearchCost               = "search cost"
	EntitySearchBudget             = "search budget"
	EntitySearchMetric             = "search metric"
	EntitySearchEmbedding          = "search embedding"
	EntitySearchSuggestion         = "search suggestion"
	EntitySearchAnalytics          = "search analytics"
	EntityEmoji                    = "emoji"
	EntityRelay                    = "relay"
	EntityFederationCost           = "federation cost"
	EntityFederationBudget         = "federation budget"
	EntityFederationInstance       = "federation instance"
	EntityMediaMetadata            = "media metadata"
	EntityDLQMessage               = "dlq message"
	EntityDNSCache                 = "dns cache"
	EntityFederationActivity       = "federation activity"
	EntityQuoteRelationship        = "quote relationship"
	EntityQuotePermissions         = "quote permissions"
)

Common entity type constants for consistent error messages

View Source
const (
	// ReviewedTrue represents the string value for reviewed status
	ReviewedTrue = "true"
	// ReviewedFalse represents the string value for not reviewed status
	ReviewedFalse = "false"
)
View Source
const (
	MediaTypeImage   = "image"
	MediaTypeVideo   = "video"
	MediaTypeAudio   = "audio"
	MediaTypeGifv    = "gifv"
	MediaTypeUnknown = "unknown"
)

Constants for media types to avoid repetition

View Source
const (
	// EnabledValue represents the string "true" for environment variables
	EnabledValue = "true"

	// MaxConnectionsPerUser defines the maximum connections allowed per user
	MaxConnectionsPerUser = 10
	// MaxTotalConnections defines the maximum total connections allowed globally
	MaxTotalConnections = 10000
	// DefaultIdleThreshold defines the default time before a connection is considered idle
	DefaultIdleThreshold = time.Minute * 30
)
View Source
const (
	// Core sort keys
	SKMetadata   = "METADATA"
	SKProfile    = "PROFILE"
	SKState      = "STATE"
	SKCode       = "CODE"
	SKToken      = "TOKEN"
	SKCredential = "CREDENTIAL"
	SKChallenge  = "CHALLENGE"
	SKWebAuthn   = "WEBAUTHN"

	// Prefixes for range queries
	SKPrefixFilter    = "FILTER#"
	SKPrefixKeyword   = "KEYWORD#"
	SKPrefixStatus    = "STATUS#"
	SKPrefixFollowing = "FOLLOWING#"
	SKPrefixFollower  = "FOLLOWER#"
	SKPrefixWallet    = "WALLET#"
)

Common Sort Keys

View Source
const (
	ConnectionTypeAll = "all"
)

Connection type constants

View Source
const (
	FieldDescription = "description"
)

Media field constants

View Source
const (
	StatusCurrent = "CURRENT"
)

Streaming status constants

View Source
const (
	StatusInactive = "inactive"
)

Additional status constants for federation

View Source
const (
	TypeFollowed = "followed"
)

Type constants

Variables

View Source
var (
	// Account authentication errors
	ErrAccountValidationFailed    = AccountValidationFailed("general validation failure")
	ErrDeviceValidationFailed     = DeviceValidationFailed("general validation failure")
	ErrSessionValidationFailed    = SessionValidationFailed("general validation failure")
	ErrWebAuthnValidationFailed   = WebAuthnValidationFailed("general validation failure")
	ErrWalletValidationFailed     = WalletValidationFailed("general validation failure")
	ErrDeviceNotFound             = DeviceNotFound("unknown")
	ErrWebAuthnCredentialNotFound = WebAuthnCredentialNotFound("unknown")

	// Account search errors
	ErrAccountSearchInvalidWebfingerFormat = AccountSearchInvalidWebfingerFormat("unknown format")

	// OAuth errors
	ErrOAuthClientNameRequired   = OAuthClientNameRequired()
	ErrOAuthRedirectURIsRequired = OAuthRedirectURIsRequired()
	ErrOAuthNoUpdatesProvided    = OAuthNoUpdatesProvided()
	ErrOAuthClientAlreadyExists  = OAuthClientAlreadyExists("unknown")
	ErrOAuthStateExpired         = OAuthStateExpired("unknown")

	// Query utility errors
	ErrQueryOperationFailed     = QueryOperationFailed("unknown", stdErrors.New("unknown error"))
	ErrQueryCollectionAddFailed = QueryCollectionAddFailed("unknown", stdErrors.New("unknown error"))
	ErrQueryExecutionFailed     = QueryExecutionFailed("unknown", stdErrors.New("unknown error"))
	ErrQueryValidationFailed    = QueryValidationFailed("unknown")

	// Analytics errors
	ErrInvalidHashtagTrendType      = InvalidHashtagTrendType("unknown")
	ErrInvalidStatusTrendType       = InvalidStatusTrendType("unknown")
	ErrInvalidLinkTrendType         = InvalidLinkTrendType("unknown")
	ErrHashtagBatchUnknownModelType = HashtagBatchUnknownModelType("unknown")
	ErrStatusRepoDependencyMissing  = StatusRepoDependencyMissing()
	ErrInvalidQueryParameters       = InvalidQueryParameters("unknown")
	ErrFailedIndexByEngagement      = FailedIndexByEngagement(stdErrors.New("unknown error"))
	ErrFailedRecordEngagement       = FailedRecordEngagement(stdErrors.New("unknown error"))
	ErrFailedGetEngagementMetrics   = FailedGetEngagementMetrics(stdErrors.New("unknown error"))
	ErrFailedGetEngagementByDate    = FailedGetEngagementByDate(stdErrors.New("unknown error"))
	ErrFailedGetTopContent          = FailedGetTopContent(stdErrors.New("unknown error"))
	ErrFailedUpdateTrendingTag      = FailedUpdateTrendingTag(stdErrors.New("unknown error"))
	ErrFailedGetTrendingTags        = FailedGetTrendingTags(stdErrors.New("unknown error"))
	ErrFailedQueryStaleTrends       = FailedQueryStaleTrends(stdErrors.New("unknown error"))
	ErrFailedRecordInstanceMetric   = FailedRecordInstanceMetric(stdErrors.New("unknown error"))
	ErrFailedGetInstanceMetrics     = FailedGetInstanceMetrics(stdErrors.New("unknown error"))
	ErrFailedGetStartMetric         = FailedGetStartMetric(stdErrors.New("unknown error"))
	ErrFailedGetEndMetric           = FailedGetEndMetric(stdErrors.New("unknown error"))
	ErrFailedRecordManifest         = FailedRecordManifest(stdErrors.New("unknown error"))
	ErrFailedRecordQualityChange    = FailedRecordQualityChange(stdErrors.New("unknown error"))
	ErrFailedRecordMediaEvent       = FailedRecordMediaEvent(stdErrors.New("unknown error"))
	ErrFailedQuerySessionEvents     = FailedQuerySessionEvents(stdErrors.New("unknown error"))
	ErrFailedGetModerationAnalytics = FailedGetModerationAnalytics(stdErrors.New("unknown error"))
	ErrFailedRecordModerationAction = FailedRecordModerationAction(stdErrors.New("unknown error"))
	ErrFailedGetModerationData      = FailedGetModerationData(stdErrors.New("unknown error"))
	ErrInvalidQueryForCounting      = InvalidQueryForCounting("unknown")
	ErrInvalidQueryForCount         = InvalidQueryForCount("unknown")
	ErrFailedGetQueryCount          = FailedGetQueryCount(stdErrors.New("unknown error"))
	ErrFailedGetTopQueries          = FailedGetTopQueries(stdErrors.New("unknown error"))
	ErrFailedGetExistingCounter     = FailedGetExistingCounter(stdErrors.New("unknown error"))
	ErrFailedSaveCounter            = FailedSaveCounter(stdErrors.New("unknown error"))
	ErrFailedGetStats               = FailedGetStats(stdErrors.New("unknown error"))

	// Federation cost errors
	ErrFederationCostRecordFailed        = FederationCostRecordFailed(stdErrors.New("unknown error"))
	ErrFederationCostQueryFailed         = FederationCostQueryFailed(stdErrors.New("unknown error"))
	ErrFederationCostActivityQueryFailed = FederationCostActivityQueryFailed(stdErrors.New("unknown error"))
	ErrFederationBudgetCreateFailed      = FederationBudgetCreateFailed(stdErrors.New("unknown error"))
	ErrFederationBudgetNotFound          = FederationBudgetNotFound("unknown")
	ErrFederationBudgetQueryFailed       = FederationBudgetQueryFailed(stdErrors.New("unknown error"))
	ErrActiveBudgetsQueryFailed          = ActiveBudgetsQueryFailed(stdErrors.New("unknown error"))

	// Federation instance errors
	ErrFederationInstanceSearchFailed                 = FederationInstanceSearchFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceHealthStoreFailed            = FederationInstanceHealthStoreFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceHealthQueryFailed            = FederationInstanceHealthQueryFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchGetFailed               = FederationInstanceBatchGetFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchCreateFailed            = FederationInstanceBatchCreateFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchCreateChunkFailed       = FederationInstanceBatchCreateChunkFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchUpdateHealthFailed      = FederationInstanceBatchUpdateHealthFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchUpdateHealthChunkFailed = FederationInstanceBatchUpdateHealthChunkFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceUsageUpdateFailed            = FederationInstanceUsageUpdateFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchUpdateUsageFailed       = FederationInstanceBatchUpdateUsageFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceBatchUpdateUsageChunkFailed  = FederationInstanceBatchUpdateUsageChunkFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceListFailed                   = FederationInstanceListFailed(stdErrors.New("unknown error"))
	ErrFederationInstanceCursorTooLong                = FederationInstanceCursorTooLong(1025)
	ErrFederationInstanceCursorInvalid                = FederationInstanceCursorInvalid("unknown")
	ErrFederationInstanceLimitNegative                = FederationInstanceLimitNegative(-1)
	ErrFederationInstanceLimitTooLarge                = FederationInstanceLimitTooLarge(1001)

	// CSRF errors
	ErrCSRFTokenInvalid       = CSRFTokenInvalid("unknown")
	ErrCSRFTokenExpired       = CSRFTokenExpired("unknown")
	ErrCSRFTokenAlreadyExists = CSRFTokenAlreadyExists("unknown")
	ErrCSRFTooManyTokens      = CSRFTooManyTokens("unknown", 11)

	// Media metadata errors
	ErrMediaMetadataPrepareFailed      = MediaMetadataPrepareFailed(stdErrors.New("unknown error"))
	ErrMediaMetadataNotFound           = MediaMetadataNotFound("unknown")
	ErrMediaMetadataQueryFailed        = MediaMetadataQueryFailed(stdErrors.New("unknown error"))
	ErrMediaMetadataStatusQueryFailed  = MediaMetadataStatusQueryFailed(stdErrors.New("unknown error"))
	ErrExpiredMediaMetadataQueryFailed = ExpiredMediaMetadataQueryFailed(stdErrors.New("unknown error"))

	// DLQ errors
	ErrDLQServiceRequired         = DLQServiceRequired()
	ErrDLQMessageNotFound         = DLQMessageNotFound("unknown")
	ErrDLQMessageNotReprocessable = DLQMessageNotReprocessable("unknown", "unknown")
	ErrDLQBatchUpdateFailed       = DLQBatchUpdateFailed(stdErrors.New("unknown error"))

	// Notification errors
	ErrNotificationUnknownPreferenceType = NotificationUnknownPreferenceType("unknown")

	// DNS cache errors
	ErrDNSCacheEntryRequired    = DNSCacheEntryRequired()
	ErrDNSCacheGetFailed        = DNSCacheGetFailed(stdErrors.New("unknown error"))
	ErrDNSCacheSetFailed        = DNSCacheSetFailed(stdErrors.New("unknown error"))
	ErrDNSCacheInvalidateFailed = DNSCacheInvalidateFailed(stdErrors.New("unknown error"))

	// Federation activity errors
	ErrFederationActivityValidationFailed = FederationActivityValidationFailed("unknown")
	ErrFederationActivityNotFound         = FederationActivityNotFound("unknown")

	// Quote errors
	ErrQuoteRelationshipCreateFailed = QuoteRelationshipCreateFailed(stdErrors.New("unknown error"))
	ErrQuoteRelationshipGetFailed    = QuoteRelationshipGetFailed(stdErrors.New("unknown error"))
	ErrQuoteRelationshipUpdateFailed = QuoteRelationshipUpdateFailed(stdErrors.New("unknown error"))
	ErrQuoteRelationshipDeleteFailed = QuoteRelationshipDeleteFailed(stdErrors.New("unknown error"))
	ErrQuoteRelationshipQueryFailed  = QuoteRelationshipQueryFailed(stdErrors.New("unknown error"))
	ErrQuotePermissionsCreateFailed  = QuotePermissionsCreateFailed(stdErrors.New("unknown error"))
	ErrQuotePermissionsGetFailed     = QuotePermissionsGetFailed(stdErrors.New("unknown error"))
	ErrQuotePermissionsUpdateFailed  = QuotePermissionsUpdateFailed(stdErrors.New("unknown error"))
	ErrQuotePermissionsDeleteFailed  = QuotePermissionsDeleteFailed(stdErrors.New("unknown error"))
	ErrQuoteCountQueryFailed         = QuoteCountQueryFailed(stdErrors.New("unknown error"))

	// Marker errors
	ErrMarkerSaveFailed = MarkerSaveFailed(stdErrors.New("unknown error"))

	// Scheduled job cost errors
	ErrScheduledJobCostBeforeCreateFailed = ScheduledJobCostBeforeCreateFailed("unknown")
	ErrScheduledJobCostBeforeUpdateFailed = ScheduledJobCostBeforeUpdateFailed("unknown")
	ErrScheduledJobCostNotFound           = ScheduledJobCostNotFound("unknown")
	ErrScheduledJobCostAggregationFailed  = ScheduledJobCostAggregationFailed(stdErrors.New("unknown error"))

	// Moderation metrics errors
	ErrModerationMetricsFalsePositivesQueryFailed  = ModerationMetricsFalsePositivesQueryFailed(stdErrors.New("unknown error"))
	ErrModerationMetricsDecisionSamplesQueryFailed = ModerationMetricsDecisionSamplesQueryFailed(stdErrors.New("unknown error"))
	ErrModerationMetricsTopPatternsQueryFailed     = ModerationMetricsTopPatternsQueryFailed(stdErrors.New("unknown error"))
	ErrModerationMetricsEntriesQueryFailed         = ModerationMetricsEntriesQueryFailed(stdErrors.New("unknown error"))

	// Pagination errors
	ErrPaginationParametersInvalid = PaginationParametersInvalid("unknown")
	ErrPaginationCursorInvalid     = PaginationCursorInvalid("unknown")
	ErrPaginationCursorFormat      = PaginationCursorFormat("unknown")
	ErrPaginationCursorData        = PaginationCursorData("unknown", "unknown")

	// Relationship pagination errors
	ErrRelationshipPaginationModelTypeUnsupported = RelationshipPaginationModelTypeUnsupported("unknown")
	ErrRelationshipPaginationQueryFailed          = RelationshipPaginationQueryFailed(stdErrors.New("unknown error"))

	// Relay errors
	ErrRelayNotFound = RelayNotFound("unknown")

	// Timeline errors
	ErrTimelineQueryFailed                    = TimelineQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesByPostQueryFailed       = TimelineEntriesByPostQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesByActorQueryFailed      = TimelineEntriesByActorQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesByVisibilityQueryFailed = TimelineEntriesByVisibilityQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesByLanguageQueryFailed   = TimelineEntriesByLanguageQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntryQueryFailed               = TimelineEntryQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesForDeletionQueryFailed  = TimelineEntriesForDeletionQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineExpiredEntriesScanFailed       = TimelineExpiredEntriesScanFailed(stdErrors.New("unknown error"))
	ErrTimelineCountQueryFailed               = TimelineCountQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineEntriesInRangeQueryFailed      = TimelineEntriesInRangeQueryFailed(stdErrors.New("unknown error"))
	ErrTimelineFilteredEntriesQueryFailed     = TimelineFilteredEntriesQueryFailed(stdErrors.New("unknown error"))
	ErrTestMockError                          = TestMockError()

	// Streaming connection errors
	ErrStreamingConnectionUserLimitReached    = StreamingConnectionUserLimitReached("unknown", 10)
	ErrStreamingConnectionGlobalLimitReached  = StreamingConnectionGlobalLimitReached(100)
	ErrStreamingConnectionMessageSizeExceeded = StreamingConnectionMessageSizeExceeded(1000, 500)
	ErrStreamingConnectionRateLimitExceeded   = StreamingConnectionRateLimitExceeded("unknown")
	ErrStreamingConnectionNotFound            = StreamingConnectionNotFound("unknown")

	// Streaming preferences errors
	ErrStreamingUsernameRequired         = StreamingUsernameRequired()
	ErrStreamingDeviceParamsRequired     = StreamingDeviceParamsRequired()
	ErrStreamingConflictResolutionFailed = StreamingConflictResolutionFailed(stdErrors.New("unknown error"))
)

Deprecated error variables - These are maintained for backward compatibility. New code should use the function-based error creation from the centralized system.

View Source
var ErrDatabaseOperation = errors.NewStorageError(errors.CodeInternal, "Database error")

ErrDatabaseOperation is deprecated. Use specific error functions from the centralized system.

View Source
var ErrEntityAlreadyExists = errors.ItemAlreadyExists("entity")

ErrEntityAlreadyExists is deprecated. Use errors.ItemAlreadyExists() or errors.ItemAlreadyExistsWithID() instead.

View Source
var ErrEntityNotFound = errors.ItemNotFound("entity")

ErrEntityNotFound is deprecated. Use errors.ItemNotFound() or errors.ItemNotFoundWithID() instead.

View Source
var ErrEntityNotFoundForUpdate = errors.ItemNotFound("entity")

ErrEntityNotFoundForUpdate is deprecated. Use errors.ItemNotFoundWithID() instead.

View Source
var ErrFailedToCreate = errors.FailedToCreate("entity", stdErrors.New("failed to create entity"))

ErrFailedToCreate is deprecated. Use errors.FailedToCreate() instead.

View Source
var ErrFailedToDelete = errors.FailedToDelete("entity", stdErrors.New("failed to delete entity"))

ErrFailedToDelete is deprecated. Use errors.FailedToDelete() instead.

View Source
var ErrFailedToGet = errors.FailedToGet("entity", stdErrors.New("failed to get entity"))

ErrFailedToGet is deprecated. Use errors.FailedToGet() instead.

View Source
var ErrFailedToQuery = errors.FailedToQuery("entity", stdErrors.New("failed to query entity"))

ErrFailedToQuery is deprecated. Use errors.FailedToQuery() instead.

View Source
var ErrFailedToUpdate = errors.FailedToUpdate("entity", stdErrors.New("failed to update entity"))

ErrFailedToUpdate is deprecated. Use errors.FailedToUpdate() instead.

View Source
var ErrorHandler = NewErrorUtils()

ErrorHandler is the global error utils instance

View Source
var StandardTTLs = struct {
	Session    time.Duration // 24 hours
	OAuthState time.Duration // 10 minutes
	AuthCode   time.Duration // 10 minutes
	Challenge  time.Duration // 5 minutes
	ShortTerm  time.Duration // 1 hour
	MediumTerm time.Duration // 30 days
	LongTerm   time.Duration // 90 days
}{
	Session:    24 * time.Hour,
	OAuthState: 10 * time.Minute,
	AuthCode:   10 * time.Minute,
	Challenge:  5 * time.Minute,
	ShortTerm:  1 * time.Hour,
	MediumTerm: 30 * 24 * time.Hour,
	LongTerm:   90 * 24 * time.Hour,
}

StandardTTLs provides common TTL durations

View Source
var Utils = NewCommonUtils()

Utils provides a global instance for easy access across repositories

Functions

func AccountSearchInvalidWebfingerFormat

func AccountSearchInvalidWebfingerFormat(format string) *errors.AppError

AccountSearchInvalidWebfingerFormat creates an error indicating invalid webfinger format.

func AccountValidationFailed

func AccountValidationFailed(reason string) *errors.AppError

AccountValidationFailed creates an error indicating account validation failed.

func ActiveBudgetsQueryFailed

func ActiveBudgetsQueryFailed(err error) *errors.AppError

ActiveBudgetsQueryFailed creates an error indicating failed to get active budgets.

func ApplyPaginationLimits

func ApplyPaginationLimits[T any](results []T, requestedLimit int) ([]T, bool)

ApplyPaginationLimits applies limit to results and determines if there are more pages

func AuditLogQueryHelper

func AuditLogQueryHelper(
	ctx context.Context,
	db core.DB,
	indexName string,
	pkValue string,
	limit int,
	startTime, endTime time.Time,
	entityName string,
) ([]*models.AuthAuditLog, error)

AuditLogQueryHelper is a shared helper for audit log queries with time range

func BatchGet

func BatchGet[T any](ctx context.Context, q *QueryUtils, keys []struct{ PK, SK string }) ([]T, error)

BatchGet performs a batch get operation for multiple items

func CSRFTokenAlreadyExists

func CSRFTokenAlreadyExists(token string) *errors.AppError

CSRFTokenAlreadyExists creates an error indicating token already exists.

func CSRFTokenExpired

func CSRFTokenExpired(token string) *errors.AppError

CSRFTokenExpired creates an error indicating expired CSRF token.

func CSRFTokenInvalid

func CSRFTokenInvalid(token string) *errors.AppError

CSRFTokenInvalid creates an error indicating invalid CSRF token.

func CSRFTooManyTokens

func CSRFTooManyTokens(userID string, count int) *errors.AppError

CSRFTooManyTokens creates an error indicating too many active CSRF tokens for user.

func ConvertAndPaginateAuditLogs

func ConvertAndPaginateAuditLogs[M interface{}](
	models []M,
	_ AuditLogConversionConfig,
	converter func(M) *storage.AuditLog,
	cursorExtractor func(M) string,
) ([]*storage.AuditLog, string)

ConvertAndPaginateAuditLogs converts audit log models to storage types with pagination This eliminates duplication in GetAuditLogsByAdmin, GetAuditLogsByTarget

func ConvertAndPaginateReports

func ConvertAndPaginateReports[M interface{}](
	models []M,
	limit int,
	_ ReportConversionConfig,
	converter func(M) *storage.Report,
	cursorExtractor func(M) string,
) ([]*storage.Report, string, error)

ConvertAndPaginateReports converts report models to storage types with pagination This eliminates duplication in GetReportsByStatus, GetReportsByCategory, etc.

func CreateNextCursor

func CreateNextCursor(lastEvaluatedKey map[string]interface{}, lastScore float64, lastTimestamp time.Time, lastID string, sortOrder SearchSortOrder) string

CreateNextCursor creates a cursor for the next page based on the last item

func DLQBatchUpdateFailed

func DLQBatchUpdateFailed(err error) *errors.AppError

DLQBatchUpdateFailed creates an error indicating batch update failed.

func DLQMessageNotFound

func DLQMessageNotFound(messageID string) *errors.AppError

DLQMessageNotFound creates an error indicating DLQ message not found.

func DLQMessageNotReprocessable

func DLQMessageNotReprocessable(messageID string, reason string) *errors.AppError

DLQMessageNotReprocessable creates an error indicating message cannot be reprocessed.

func DLQServiceRequired

func DLQServiceRequired() *errors.AppError

DLQServiceRequired creates an error indicating service is required for DLQ search.

func DNSCacheEntryRequired

func DNSCacheEntryRequired() *errors.AppError

DNSCacheEntryRequired creates an error indicating DNS cache entry cannot be nil.

func DNSCacheGetFailed

func DNSCacheGetFailed(err error) *errors.AppError

DNSCacheGetFailed creates an error indicating failed to get DNS cache entry.

func DNSCacheInvalidateFailed

func DNSCacheInvalidateFailed(err error) *errors.AppError

DNSCacheInvalidateFailed creates an error indicating failed to invalidate DNS cache entry.

func DNSCacheSetFailed

func DNSCacheSetFailed(err error) *errors.AppError

DNSCacheSetFailed creates an error indicating failed to set DNS cache entry.

func DeleteEntityWithLogging

func DeleteEntityWithLogging[M BaseModel](
	ctx context.Context,
	r *BaseRepository[M],
	pk, sk string,
	entityType string,
	identifiers map[string]string,
) error

DeleteEntityWithLogging performs safe delete operations with consistent error handling and logging This eliminates duplication in delete operations across repositories

func DeviceNotFound

func DeviceNotFound(deviceID string) *errors.AppError

DeviceNotFound creates an error indicating device was not found.

func DeviceValidationFailed

func DeviceValidationFailed(reason string) *errors.AppError

DeviceValidationFailed creates an error indicating device validation failed.

func EncodeCursor

func EncodeCursor(data *CursorData) string

EncodeCursor creates a cursor string from cursor data

func ExpiredMediaMetadataQueryFailed

func ExpiredMediaMetadataQueryFailed(err error) *errors.AppError

ExpiredMediaMetadataQueryFailed creates an error indicating failed to find expired media metadata.

func FailedGetEndMetric

func FailedGetEndMetric(err error) *errors.AppError

FailedGetEndMetric creates an error indicating failed to get end metric.

func FailedGetEngagementByDate

func FailedGetEngagementByDate(err error) *errors.AppError

FailedGetEngagementByDate creates an error indicating failed to get engagement by date range.

func FailedGetEngagementMetrics

func FailedGetEngagementMetrics(err error) *errors.AppError

FailedGetEngagementMetrics creates an error indicating failed to get engagement metrics.

func FailedGetExistingCounter

func FailedGetExistingCounter(err error) *errors.AppError

FailedGetExistingCounter creates an error indicating failed to get existing counter.

func FailedGetInstanceMetrics

func FailedGetInstanceMetrics(err error) *errors.AppError

FailedGetInstanceMetrics creates an error indicating failed to get instance metrics.

func FailedGetModerationAnalytics

func FailedGetModerationAnalytics(err error) *errors.AppError

FailedGetModerationAnalytics creates an error indicating failed to get existing moderation analytics.

func FailedGetModerationData

func FailedGetModerationData(err error) *errors.AppError

FailedGetModerationData creates an error indicating failed to get moderation analytics.

func FailedGetQueryCount

func FailedGetQueryCount(err error) *errors.AppError

FailedGetQueryCount creates an error indicating failed to get query count.

func FailedGetStartMetric

func FailedGetStartMetric(err error) *errors.AppError

FailedGetStartMetric creates an error indicating failed to get start metric.

func FailedGetStats

func FailedGetStats(err error) *errors.AppError

FailedGetStats creates an error indicating failed to get stats.

func FailedGetTopContent

func FailedGetTopContent(err error) *errors.AppError

FailedGetTopContent creates an error indicating failed to get top engaged content.

func FailedGetTopQueries

func FailedGetTopQueries(err error) *errors.AppError

FailedGetTopQueries creates an error indicating failed to get top queries.

func FailedGetTrendingTags

func FailedGetTrendingTags(err error) *errors.AppError

FailedGetTrendingTags creates an error indicating failed to get trending hashtags.

func FailedIndexByEngagement

func FailedIndexByEngagement(err error) *errors.AppError

FailedIndexByEngagement creates an error indicating failed to index by engagement.

func FailedQuerySessionEvents

func FailedQuerySessionEvents(err error) *errors.AppError

FailedQuerySessionEvents creates an error indicating failed to query session events.

func FailedQueryStaleTrends

func FailedQueryStaleTrends(err error) *errors.AppError

FailedQueryStaleTrends creates an error indicating failed to query stale trends.

func FailedRecordEngagement

func FailedRecordEngagement(err error) *errors.AppError

FailedRecordEngagement creates an error indicating failed to record engagement.

func FailedRecordInstanceMetric

func FailedRecordInstanceMetric(err error) *errors.AppError

FailedRecordInstanceMetric creates an error indicating failed to record instance metric.

func FailedRecordManifest

func FailedRecordManifest(err error) *errors.AppError

FailedRecordManifest creates an error indicating failed to record manifest generation.

func FailedRecordMediaEvent

func FailedRecordMediaEvent(err error) *errors.AppError

FailedRecordMediaEvent creates an error indicating failed to record media event.

func FailedRecordModerationAction

func FailedRecordModerationAction(err error) *errors.AppError

FailedRecordModerationAction creates an error indicating failed to record moderation action.

func FailedRecordQualityChange

func FailedRecordQualityChange(err error) *errors.AppError

FailedRecordQualityChange creates an error indicating failed to record quality change.

func FailedSaveCounter

func FailedSaveCounter(err error) *errors.AppError

FailedSaveCounter creates an error indicating failed to save counter.

func FailedUpdateTrendingTag

func FailedUpdateTrendingTag(err error) *errors.AppError

FailedUpdateTrendingTag creates an error indicating failed to update trending hashtag.

func FederationActivityNotFound

func FederationActivityNotFound(activityID string) *errors.AppError

FederationActivityNotFound creates an error indicating federation activity not found.

func FederationActivityValidationFailed

func FederationActivityValidationFailed(reason string) *errors.AppError

FederationActivityValidationFailed creates an error indicating federation activity validation failed.

func FederationBudgetCreateFailed

func FederationBudgetCreateFailed(err error) *errors.AppError

FederationBudgetCreateFailed creates an error indicating failed to create/update federation budget.

func FederationBudgetNotFound

func FederationBudgetNotFound(budgetID string) *errors.AppError

FederationBudgetNotFound creates an error indicating federation budget not found.

func FederationBudgetQueryFailed

func FederationBudgetQueryFailed(err error) *errors.AppError

FederationBudgetQueryFailed creates an error indicating failed to get federation budget.

func FederationCostActivityQueryFailed

func FederationCostActivityQueryFailed(err error) *errors.AppError

FederationCostActivityQueryFailed creates an error indicating failed to get federation costs by activity type.

func FederationCostQueryFailed

func FederationCostQueryFailed(err error) *errors.AppError

FederationCostQueryFailed creates an error indicating failed to get federation costs.

func FederationCostRecordFailed

func FederationCostRecordFailed(err error) *errors.AppError

FederationCostRecordFailed creates an error indicating failed to record federation cost.

func FederationInstanceBatchCreateChunkFailed

func FederationInstanceBatchCreateChunkFailed(err error) *errors.AppError

FederationInstanceBatchCreateChunkFailed creates an error indicating failed in batch create chunk.

func FederationInstanceBatchCreateFailed

func FederationInstanceBatchCreateFailed(err error) *errors.AppError

FederationInstanceBatchCreateFailed creates an error indicating failed to batch create instances.

func FederationInstanceBatchGetFailed

func FederationInstanceBatchGetFailed(err error) *errors.AppError

FederationInstanceBatchGetFailed creates an error indicating failed in batch get chunk.

func FederationInstanceBatchUpdateHealthChunkFailed

func FederationInstanceBatchUpdateHealthChunkFailed(err error) *errors.AppError

FederationInstanceBatchUpdateHealthChunkFailed creates an error indicating failed in batch update health chunk.

func FederationInstanceBatchUpdateHealthFailed

func FederationInstanceBatchUpdateHealthFailed(err error) *errors.AppError

FederationInstanceBatchUpdateHealthFailed creates an error indicating failed to batch update instances health.

func FederationInstanceBatchUpdateUsageChunkFailed

func FederationInstanceBatchUpdateUsageChunkFailed(err error) *errors.AppError

FederationInstanceBatchUpdateUsageChunkFailed creates an error indicating failed in batch update usage chunk.

func FederationInstanceBatchUpdateUsageFailed

func FederationInstanceBatchUpdateUsageFailed(err error) *errors.AppError

FederationInstanceBatchUpdateUsageFailed creates an error indicating failed to batch update instances usage.

func FederationInstanceCursorInvalid

func FederationInstanceCursorInvalid(cursor string) *errors.AppError

FederationInstanceCursorInvalid creates an error indicating invalid cursor format.

func FederationInstanceCursorTooLong

func FederationInstanceCursorTooLong(cursorLength int) *errors.AppError

FederationInstanceCursorTooLong creates an error indicating cursor is too long.

func FederationInstanceHealthQueryFailed

func FederationInstanceHealthQueryFailed(err error) *errors.AppError

FederationInstanceHealthQueryFailed creates an error indicating failed to get health history.

func FederationInstanceHealthStoreFailed

func FederationInstanceHealthStoreFailed(err error) *errors.AppError

FederationInstanceHealthStoreFailed creates an error indicating failed to store health history.

func FederationInstanceLimitNegative

func FederationInstanceLimitNegative(limit int) *errors.AppError

FederationInstanceLimitNegative creates an error indicating limit cannot be negative.

func FederationInstanceLimitTooLarge

func FederationInstanceLimitTooLarge(limit int) *errors.AppError

FederationInstanceLimitTooLarge creates an error indicating limit is too large.

func FederationInstanceListFailed

func FederationInstanceListFailed(err error) *errors.AppError

FederationInstanceListFailed creates an error indicating failed to list all instances.

func FederationInstanceSearchFailed

func FederationInstanceSearchFailed(err error) *errors.AppError

FederationInstanceSearchFailed creates an error indicating failed to search federation instances.

func FederationInstanceUsageUpdateFailed

func FederationInstanceUsageUpdateFailed(err error) *errors.AppError

FederationInstanceUsageUpdateFailed creates an error indicating failed to get current instances for usage update.

func GenericQuery

func GenericQuery[T any](ctx context.Context, q *QueryUtils, pk, sk string) (*T, error)

GenericQuery performs a type-safe query with automatic struct mapping

func HashtagBatchUnknownModelType

func HashtagBatchUnknownModelType(modelType string) *errors.AppError

HashtagBatchUnknownModelType creates an error indicating unknown hashtag model type.

func InvalidHashtagTrendType

func InvalidHashtagTrendType(actualType string) *errors.AppError

InvalidHashtagTrendType creates an error indicating invalid hashtag trend type.

func InvalidLinkTrendType

func InvalidLinkTrendType(actualType string) *errors.AppError

InvalidLinkTrendType creates an error indicating invalid link trend type.

func InvalidQueryForCount

func InvalidQueryForCount(query string) *errors.AppError

InvalidQueryForCount creates an error indicating invalid query for count retrieval.

func InvalidQueryForCounting

func InvalidQueryForCounting(query string) *errors.AppError

InvalidQueryForCounting creates an error indicating invalid query for counting.

func InvalidQueryParameters

func InvalidQueryParameters(reason string) *errors.AppError

InvalidQueryParameters creates an error indicating invalid query parameters.

func InvalidStatusTrendType

func InvalidStatusTrendType(actualType string) *errors.AppError

InvalidStatusTrendType creates an error indicating invalid status trend type.

func IsRepositoryConflictError

func IsRepositoryConflictError(err error) bool

IsRepositoryConflictError checks if an error indicates a repository conflict (already exists).

func IsRepositoryNotFoundError

func IsRepositoryNotFoundError(err error) bool

IsRepositoryNotFoundError checks if an error indicates a repository item was not found.

func ListAggregatedByPeriod

func ListAggregatedByPeriod[T BaseModel](
	ctx context.Context,
	db core.DB,
	config AggregatedQueryConfig,
	period, entityType string,
	startTime, endTime time.Time,
	limit int,
	cursor string,
) ([]T, string, error)

ListAggregatedByPeriod performs time-range queries for aggregated data This eliminates duplication between cost tracking and metrics repositories

func MapDynamoDBError

func MapDynamoDBError(err error) error

MapDynamoDBError maps DynamoDB/DynamORM errors to storage errors using the centralized error system.

func MapErrorWithContext

func MapErrorWithContext(err error, context string) error

MapErrorWithContext wraps an error with additional context using the centralized error system.

func MarkerSaveFailed

func MarkerSaveFailed(err error) *errors.AppError

MarkerSaveFailed creates an error indicating failed to save marker.

func MediaMetadataNotFound

func MediaMetadataNotFound(mediaID string) *errors.AppError

MediaMetadataNotFound creates an error indicating media metadata not found.

func MediaMetadataPrepareFailed

func MediaMetadataPrepareFailed(err error) *errors.AppError

MediaMetadataPrepareFailed creates an error indicating failed to prepare media metadata.

func MediaMetadataQueryFailed

func MediaMetadataQueryFailed(err error) *errors.AppError

MediaMetadataQueryFailed creates an error indicating failed to get media metadata.

func MediaMetadataStatusQueryFailed

func MediaMetadataStatusQueryFailed(err error) *errors.AppError

MediaMetadataStatusQueryFailed creates an error indicating failed to get media metadata by status.

func ModerationMetricsDecisionSamplesQueryFailed

func ModerationMetricsDecisionSamplesQueryFailed(err error) *errors.AppError

ModerationMetricsDecisionSamplesQueryFailed creates an error indicating failed to get decision samples.

func ModerationMetricsEntriesQueryFailed

func ModerationMetricsEntriesQueryFailed(err error) *errors.AppError

ModerationMetricsEntriesQueryFailed creates an error indicating failed to get metrics entries.

func ModerationMetricsFalsePositivesQueryFailed

func ModerationMetricsFalsePositivesQueryFailed(err error) *errors.AppError

ModerationMetricsFalsePositivesQueryFailed creates an error indicating failed to get false positives.

func ModerationMetricsTopPatternsQueryFailed

func ModerationMetricsTopPatternsQueryFailed(err error) *errors.AppError

ModerationMetricsTopPatternsQueryFailed creates an error indicating failed to get top patterns.

func NewRepositoryError

func NewRepositoryError(code errors.ErrorCode, message string) *errors.AppError

NewRepositoryError creates a new repository error with Storage category.

func NewRepositoryInternalError

func NewRepositoryInternalError(code errors.ErrorCode, message string, internal error) *errors.AppError

NewRepositoryInternalError creates a repository error with internal details.

func NormalizePaginationLimit

func NormalizePaginationLimit(limit int) int

NormalizePaginationLimit ensures pagination limit is within valid bounds

func NormalizeRedirectURI

func NormalizeRedirectURI(uri string) string

NormalizeRedirectURI normalizes a redirect URI for comparison

func NotificationUnknownPreferenceType

func NotificationUnknownPreferenceType(preferenceType string) *errors.AppError

NotificationUnknownPreferenceType creates an error indicating unknown notification preference type.

func OAuthClientAlreadyExists

func OAuthClientAlreadyExists(clientID string) *errors.AppError

OAuthClientAlreadyExists creates an error indicating OAuth client already exists.

func OAuthClientNameRequired

func OAuthClientNameRequired() *errors.AppError

OAuthClientNameRequired creates an error indicating client name is required.

func OAuthNoUpdatesProvided

func OAuthNoUpdatesProvided() *errors.AppError

OAuthNoUpdatesProvided creates an error indicating no updates were provided.

func OAuthRedirectURIsRequired

func OAuthRedirectURIsRequired() *errors.AppError

OAuthRedirectURIsRequired creates an error indicating redirect URIs are required.

func OAuthStateExpired

func OAuthStateExpired(state string) *errors.AppError

OAuthStateExpired creates an error indicating OAuth state has expired.

func PaginationCursorData

func PaginationCursorData(cursor string, reason string) *errors.AppError

PaginationCursorData creates an error indicating invalid cursor data.

func PaginationCursorFormat

func PaginationCursorFormat(cursor string) *errors.AppError

PaginationCursorFormat creates an error indicating invalid cursor format.

func PaginationCursorInvalid

func PaginationCursorInvalid(cursor string) *errors.AppError

PaginationCursorInvalid creates an error indicating invalid cursor.

func PaginationParametersInvalid

func PaginationParametersInvalid(reason string) *errors.AppError

PaginationParametersInvalid creates an error indicating invalid pagination parameters.

func QueryAndConvert

func QueryAndConvert[M any, S any](
	_ context.Context,
	q *QueryUtils,
	queryFunc func() ([]M, error),
	convertFunc func(M) S,
	operationName string,
	operationParam string,
) ([]S, error)

QueryAndConvert performs a database query and converts the results to storage types This eliminates the common pattern of: query → error check → convert loop → return

func QueryCollectionAddFailed

func QueryCollectionAddFailed(collection string, err error) *errors.AppError

QueryCollectionAddFailed creates an error indicating failed to add to collection.

func QueryCollectionWithConversion

func QueryCollectionWithConversion[M BaseModel, R any](
	ctx context.Context,
	r *BaseRepository[M],
	config CollectionQueryConfig,
	entityID string,
	limit int,
	cursor string,
	converter func([]M) ([]R, error),
) ([]R, string, error)

QueryCollectionWithConversion performs paginated collection queries with type conversion This eliminates duplication in social relationship queries (likes, blocks, follows, etc.)

func QueryExecutionFailed

func QueryExecutionFailed(query string, err error) *errors.AppError

QueryExecutionFailed creates an error indicating query execution failed.

func QueryHistoryWithDateRange

func QueryHistoryWithDateRange[M BaseModel](
	ctx context.Context,
	r *BaseRepository[M],
	config HistoryQueryConfig,
	days int,
) ([]any, error)

QueryHistoryWithDateRange performs time-range queries for metrics/history data This eliminates duplication in GetStorageHistory, GetUserGrowthHistory, etc.

func QueryMetricsByTimeRange

func QueryMetricsByTimeRange[M BaseModel](
	ctx context.Context,
	r *BaseRepository[M],
	config MetricsQueryConfig,
	entityName string,
	startTime, endTime time.Time,
) ([]M, error)

QueryMetricsByTimeRange performs time-range queries for metric records This eliminates duplication in GetMetricsByService, GetMetricsByType, GetMetricsByAggregationLevel

func QueryOperationFailed

func QueryOperationFailed(operation string, err error) *errors.AppError

QueryOperationFailed creates an error indicating query operation failed.

func QueryValidationFailed

func QueryValidationFailed(reason string) *errors.AppError

QueryValidationFailed creates an error indicating query validation failed.

func QueryWithPKAndSKPrefix

func QueryWithPKAndSKPrefix[M any, S any](
	ctx context.Context,
	q *QueryUtils,
	modelFactory func() *M,
	pkValue, skPrefix string,
	useFilter bool,
	convertFunc func(M) S,
	operationName string,
	operationParam string,
) ([]S, error)

QueryWithPKAndSKPrefix eliminates the PK/SK prefix query duplication pattern This consolidates the common "Where PK = X, Where/Filter SK BEGINS_WITH Y" pattern

func QuoteCountQueryFailed

func QuoteCountQueryFailed(err error) *errors.AppError

QuoteCountQueryFailed creates an error indicating failed to get quote count.

func QuotePermissionsCreateFailed

func QuotePermissionsCreateFailed(err error) *errors.AppError

QuotePermissionsCreateFailed creates an error indicating failed to create quote permissions.

func QuotePermissionsDeleteFailed

func QuotePermissionsDeleteFailed(err error) *errors.AppError

QuotePermissionsDeleteFailed creates an error indicating failed to delete quote permissions.

func QuotePermissionsGetFailed

func QuotePermissionsGetFailed(err error) *errors.AppError

QuotePermissionsGetFailed creates an error indicating failed to get quote permissions.

func QuotePermissionsUpdateFailed

func QuotePermissionsUpdateFailed(err error) *errors.AppError

QuotePermissionsUpdateFailed creates an error indicating failed to update quote permissions.

func QuoteRelationshipCreateFailed

func QuoteRelationshipCreateFailed(err error) *errors.AppError

QuoteRelationshipCreateFailed creates an error indicating failed to create quote relationship.

func QuoteRelationshipDeleteFailed

func QuoteRelationshipDeleteFailed(err error) *errors.AppError

QuoteRelationshipDeleteFailed creates an error indicating failed to delete quote relationship.

func QuoteRelationshipGetFailed

func QuoteRelationshipGetFailed(err error) *errors.AppError

QuoteRelationshipGetFailed creates an error indicating failed to get quote relationship.

func QuoteRelationshipQueryFailed

func QuoteRelationshipQueryFailed(err error) *errors.AppError

QuoteRelationshipQueryFailed creates an error indicating failed to query quote relationships.

func QuoteRelationshipUpdateFailed

func QuoteRelationshipUpdateFailed(err error) *errors.AppError

QuoteRelationshipUpdateFailed creates an error indicating failed to update quote relationship.

func RelationshipPaginationModelTypeUnsupported

func RelationshipPaginationModelTypeUnsupported(modelType string) *errors.AppError

RelationshipPaginationModelTypeUnsupported creates an error indicating unsupported model type.

func RelationshipPaginationQueryFailed

func RelationshipPaginationQueryFailed(err error) *errors.AppError

RelationshipPaginationQueryFailed creates an error indicating failed to get relationship data.

func RelayNotFound

func RelayNotFound(relayID string) *errors.AppError

RelayNotFound creates an error indicating relay not found.

func ScheduledJobCostAggregationFailed

func ScheduledJobCostAggregationFailed(err error) *errors.AppError

ScheduledJobCostAggregationFailed creates an error indicating failed to list job costs for aggregation.

func ScheduledJobCostBeforeCreateFailed

func ScheduledJobCostBeforeCreateFailed(reason string) *errors.AppError

ScheduledJobCostBeforeCreateFailed creates an error indicating before create validation failed.

func ScheduledJobCostBeforeUpdateFailed

func ScheduledJobCostBeforeUpdateFailed(reason string) *errors.AppError

ScheduledJobCostBeforeUpdateFailed creates an error indicating before update validation failed.

func ScheduledJobCostNotFound

func ScheduledJobCostNotFound(jobID string) *errors.AppError

ScheduledJobCostNotFound creates an error indicating scheduled job cost record not found.

func SessionValidationFailed

func SessionValidationFailed(reason string) *errors.AppError

SessionValidationFailed creates an error indicating session validation failed.

func ShouldContinuePagination

func ShouldContinuePagination(resultCount, requestedLimit, totalProcessed, maxScan int) bool

ShouldContinuePagination determines if pagination should continue based on results and limits

func SortResults

func SortResults[T any](results []T, sortOrder SearchSortOrder, getScore func(T) float64, getTimestamp func(T) time.Time, getID func(T) string)

SortResults sorts results based on the specified sort order

func StatusRepoDependencyMissing

func StatusRepoDependencyMissing() *errors.AppError

StatusRepoDependencyMissing creates an error indicating status repository dependency is missing.

func StreamingConflictResolutionFailed

func StreamingConflictResolutionFailed(err error) *errors.AppError

StreamingConflictResolutionFailed creates an error indicating failed to resolve preference conflict.

func StreamingConnectionGlobalLimitReached

func StreamingConnectionGlobalLimitReached(limit int) *errors.AppError

StreamingConnectionGlobalLimitReached creates an error indicating maximum total connections reached.

func StreamingConnectionMessageSizeExceeded

func StreamingConnectionMessageSizeExceeded(size, limit int64) *errors.AppError

StreamingConnectionMessageSizeExceeded creates an error indicating message size exceeds limit.

func StreamingConnectionNotFound

func StreamingConnectionNotFound(connectionID string) *errors.AppError

StreamingConnectionNotFound creates an error indicating connection not found.

func StreamingConnectionRateLimitExceeded

func StreamingConnectionRateLimitExceeded(connectionID string) *errors.AppError

StreamingConnectionRateLimitExceeded creates an error indicating rate limit exceeded.

func StreamingConnectionUserLimitReached

func StreamingConnectionUserLimitReached(userID string, limit int) *errors.AppError

StreamingConnectionUserLimitReached creates an error indicating user has reached maximum connections.

func StreamingDeviceParamsRequired

func StreamingDeviceParamsRequired() *errors.AppError

StreamingDeviceParamsRequired creates an error indicating username and deviceID are required.

func StreamingUsernameRequired

func StreamingUsernameRequired() *errors.AppError

StreamingUsernameRequired creates an error indicating username is required.

func TestMockError

func TestMockError() *errors.AppError

TestMockError creates a test mock error for testing purposes.

func TimelineCountQueryFailed

func TimelineCountQueryFailed(err error) *errors.AppError

TimelineCountQueryFailed creates an error indicating failed to count timeline entries.

func TimelineEntriesByActorQueryFailed

func TimelineEntriesByActorQueryFailed(err error) *errors.AppError

TimelineEntriesByActorQueryFailed creates an error indicating failed to get timeline entries by actor.

func TimelineEntriesByLanguageQueryFailed

func TimelineEntriesByLanguageQueryFailed(err error) *errors.AppError

TimelineEntriesByLanguageQueryFailed creates an error indicating failed to get timeline entries by language.

func TimelineEntriesByPostQueryFailed

func TimelineEntriesByPostQueryFailed(err error) *errors.AppError

TimelineEntriesByPostQueryFailed creates an error indicating failed to get timeline entries by post.

func TimelineEntriesByVisibilityQueryFailed

func TimelineEntriesByVisibilityQueryFailed(err error) *errors.AppError

TimelineEntriesByVisibilityQueryFailed creates an error indicating failed to get timeline entries by visibility.

func TimelineEntriesForDeletionQueryFailed

func TimelineEntriesForDeletionQueryFailed(err error) *errors.AppError

TimelineEntriesForDeletionQueryFailed creates an error indicating failed to get timeline entries for deletion.

func TimelineEntriesInRangeQueryFailed

func TimelineEntriesInRangeQueryFailed(err error) *errors.AppError

TimelineEntriesInRangeQueryFailed creates an error indicating failed to get timeline entries in range.

func TimelineEntryQueryFailed

func TimelineEntryQueryFailed(err error) *errors.AppError

TimelineEntryQueryFailed creates an error indicating failed to get timeline entry.

func TimelineExpiredEntriesScanFailed

func TimelineExpiredEntriesScanFailed(err error) *errors.AppError

TimelineExpiredEntriesScanFailed creates an error indicating failed to scan for expired timeline entries.

func TimelineFilteredEntriesQueryFailed

func TimelineFilteredEntriesQueryFailed(err error) *errors.AppError

TimelineFilteredEntriesQueryFailed creates an error indicating failed to get filtered timeline entries.

func TimelineQueryFailed

func TimelineQueryFailed(err error) *errors.AppError

TimelineQueryFailed creates an error indicating failed to get timeline entries.

func ValidateRedirectURI

func ValidateRedirectURI(registeredURIs []string, redirectURI string) bool

ValidateRedirectURI validates that a redirect URI matches one of the registered URIs

func WalletValidationFailed

func WalletValidationFailed(reason string) *errors.AppError

WalletValidationFailed creates an error indicating wallet validation failed.

func WebAuthnCredentialNotFound

func WebAuthnCredentialNotFound(credentialID string) *errors.AppError

WebAuthnCredentialNotFound creates an error indicating WebAuthn credential was not found.

func WebAuthnValidationFailed

func WebAuthnValidationFailed(reason string) *errors.AppError

WebAuthnValidationFailed creates an error indicating WebAuthn validation failed.

func WebSocketCostMiddleware

func WebSocketCostMiddleware(costTracker *WebSocketCostTracker) apptheory.Middleware

WebSocketCostMiddleware enforces per-user websocket budget limits and records operation cost telemetry.

func WrapRepositoryError

func WrapRepositoryError(err error, code errors.ErrorCode, message string) *errors.AppError

WrapRepositoryError wraps an existing error as a repository error.

Types

type AIAnalysisEvent

type AIAnalysisEvent struct {
	ID           string
	ObjectID     string
	ObjectType   string
	AnalysisType string
	Results      map[string]interface{}
	Confidence   float64
	ModelVersion string
	ProcessedAt  time.Time
}

AIAnalysisEvent represents an AI analysis event

type AIAnalysisSubscription

type AIAnalysisSubscription struct {
	// contains filtered or unexported fields
}

AIAnalysisSubscription represents a subscription to AI analysis events

func (*AIAnalysisSubscription) Close

func (s *AIAnalysisSubscription) Close() error

Close closes the subscription

func (*AIAnalysisSubscription) Events

func (s *AIAnalysisSubscription) Events() <-chan *AIAnalysisEvent

Events returns the channel of AI analysis events

type AICostDataPoint

type AICostDataPoint struct {
	Timestamp    time.Time `json:"timestamp"`
	TotalCost    float64   `json:"total_cost"`
	Operations   int64     `json:"operations"`
	InputTokens  int64     `json:"input_tokens"`
	OutputTokens int64     `json:"output_tokens"`
	AvgLatencyMs float64   `json:"avg_latency_ms"`
	SuccessRate  float64   `json:"success_rate"`
}

AICostDataPoint represents a single data point in cost trends

type AICostRepository

type AICostRepository struct {
	*EnhancedBaseRepository[*models.AICost]
}

AICostRepository implements AI cost tracking operations using enhanced patterns

func NewAICostRepository

func NewAICostRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AICostRepository

NewAICostRepository creates a new AI cost repository with enhanced functionality

func (*AICostRepository) CreateAICost

func (r *AICostRepository) CreateAICost(ctx context.Context, aiCost *models.AICost) error

CreateAICost creates a new AI cost record

func (*AICostRepository) CreateOrUpdateAggregatedCost

func (r *AICostRepository) CreateOrUpdateAggregatedCost(ctx context.Context, aggregatedCost *models.AIAggregatedCost) error

CreateOrUpdateAggregatedCost creates or updates aggregated cost records

func (*AICostRepository) GetAICost

func (r *AICostRepository) GetAICost(ctx context.Context, operationID string) (*models.AICost, error)

GetAICost retrieves an AI cost record by operation ID

func (*AICostRepository) GetAICostSummary

func (r *AICostRepository) GetAICostSummary(ctx context.Context, startTime, endTime time.Time, operationType string) (*AICostSummary, error)

GetAICostSummary retrieves aggregated AI cost metrics for a time period

func (*AICostRepository) GetAICostTrends

func (r *AICostRepository) GetAICostTrends(ctx context.Context, startTime, endTime time.Time, period string) (*AICostTrends, error)

GetAICostTrends retrieves cost trends over time with sophisticated analysis

func (*AICostRepository) GetAICostsByOperationType

func (r *AICostRepository) GetAICostsByOperationType(ctx context.Context, operationType string, startTime time.Time, limit int) ([]*models.AICost, error)

GetAICostsByOperationType retrieves AI cost records by operation type

func (*AICostRepository) GetAICostsByTimeRange

func (r *AICostRepository) GetAICostsByTimeRange(ctx context.Context, startTime, endTime time.Time, operationType string, limit int) ([]*models.AICost, error)

GetAICostsByTimeRange retrieves AI cost records within a time range

func (*AICostRepository) GetAggregatedCosts

func (r *AICostRepository) GetAggregatedCosts(ctx context.Context, period string, startTime, endTime time.Time) ([]*models.AIAggregatedCost, error)

GetAggregatedCosts retrieves aggregated cost data for analysis

func (*AICostRepository) GetTopCostlyOperations

func (r *AICostRepository) GetTopCostlyOperations(ctx context.Context, costTier string, startTime, endTime time.Time, limit int) ([]*models.AICost, error)

GetTopCostlyOperations retrieves the most expensive AI operations

type AICostSummary

type AICostSummary struct {
	StartTime            time.Time      `json:"start_time"`
	EndTime              time.Time      `json:"end_time"`
	OperationType        string         `json:"operation_type"`
	TotalOperations      int64          `json:"total_operations"`
	SuccessfulOperations int64          `json:"successful_operations"`
	SuccessRate          float64        `json:"success_rate"`
	TotalCostMicroCents  int64          `json:"total_cost_micro_cents"`
	TotalCostDollars     float64        `json:"total_cost_dollars"`
	AvgCostMicroCents    int64          `json:"avg_cost_micro_cents"`
	TotalInputTokens     int64          `json:"total_input_tokens"`
	TotalOutputTokens    int64          `json:"total_output_tokens"`
	CostPerInputToken    float64        `json:"cost_per_input_token"`
	CostPerOutputToken   float64        `json:"cost_per_output_token"`
	AvgLatencyMs         float64        `json:"avg_latency_ms"`
	AvgComplexityScore   float64        `json:"avg_complexity_score"`
	ModelBreakdown       map[string]int `json:"model_breakdown"`
	OperationBreakdown   map[string]int `json:"operation_breakdown"`
}

AICostSummary represents aggregated AI cost metrics

type AICostTrendAnalysis

type AICostTrendAnalysis struct {
	TrendDirection  string      `json:"trend_direction"` // increasing, decreasing, stable
	GrowthRate      float64     `json:"growth_rate"`     // Percentage growth rate
	PeakTime        time.Time   `json:"peak_time"`
	LowTime         time.Time   `json:"low_time"`
	PeakCost        float64     `json:"peak_cost"`
	LowCost         float64     `json:"low_cost"`
	Volatility      float64     `json:"volatility"`       // Cost volatility measure
	Confidence      float64     `json:"confidence"`       // Statistical confidence in trend
	SeasonalFactors []string    `json:"seasonal_factors"` // Detected seasonal patterns
	PredictedCost   float64     `json:"predicted_cost"`   // Predicted next period cost
	Anomalies       []time.Time `json:"anomalies"`        // Detected anomalous periods
}

AICostTrendAnalysis represents sophisticated trend analysis

type AICostTrends

type AICostTrends struct {
	Period     string               `json:"period"`
	StartTime  time.Time            `json:"start_time"`
	EndTime    time.Time            `json:"end_time"`
	DataPoints []AICostDataPoint    `json:"data_points"`
	Analysis   *AICostTrendAnalysis `json:"analysis"`
}

AICostTrends represents cost trends over time

type AIRepository

type AIRepository struct {
	*EnhancedBaseRepository[*models.AIAnalysis]
}

AIRepository handles AI analysis data persistence with enhanced repository integration

func NewAIRepository

func NewAIRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AIRepository

NewAIRepository creates a new AI repository with enhanced functionality

func (*AIRepository) AnalyzeContent

func (r *AIRepository) AnalyzeContent(ctx context.Context, content string, modelType string) (*ai.AIAnalysis, error)

AnalyzeContent performs comprehensive AI content analysis using ML processing pipelines This is the core AI business logic method that must be preserved

func (*AIRepository) GetAnalysis

func (r *AIRepository) GetAnalysis(ctx context.Context, objectID string) (*ai.AIAnalysis, error)

GetAnalysis retrieves the most recent AI analysis for an object using AI-specific business logic

func (*AIRepository) GetAnalysisByID

func (r *AIRepository) GetAnalysisByID(ctx context.Context, objectID, analysisID string) (*ai.AIAnalysis, error)

GetAnalysisByID retrieves a specific AI analysis by ID using BaseRepository

func (*AIRepository) GetContentClassifications

func (r *AIRepository) GetContentClassifications(ctx context.Context, contentID string) ([]string, error)

GetContentClassifications retrieves AI-powered content categorization Important for intelligent content organization

func (*AIRepository) GetStats

func (r *AIRepository) GetStats(ctx context.Context, period string) (*ai.AIStats, error)

GetStats retrieves AI analysis statistics for a given period using AI-specific analytics logic

func (*AIRepository) MonitorAIHealth

func (r *AIRepository) MonitorAIHealth(_ context.Context) error

MonitorAIHealth performs health checks on AI processing systems Critical for maintaining AI service reliability

func (*AIRepository) ProcessMLFeedback

func (r *AIRepository) ProcessMLFeedback(_ context.Context, analysisID string, feedback map[string]interface{}) error

ProcessMLFeedback handles feedback for continuous learning systems Essential for AI model improvement and adaptation

func (*AIRepository) QueueForAnalysis

func (r *AIRepository) QueueForAnalysis(ctx context.Context, objectID string) error

QueueForAnalysis marks an object for AI analysis using AI-specific queueing logic

func (*AIRepository) SaveAnalysis

func (r *AIRepository) SaveAnalysis(ctx context.Context, analysis *ai.AIAnalysis) error

SaveAnalysis stores an AI analysis result using AI-specific business logic

func (*AIRepository) SubscribeToAnalysisEvents

func (r *AIRepository) SubscribeToAnalysisEvents(_ context.Context, userID string, objectID *string) (*AIAnalysisSubscription, error)

SubscribeToAnalysisEvents creates a subscription channel for AI analysis events Note: This now returns a channel that will be populated by events from the EventBus The actual event publishing happens in the service layer when SaveAnalysis is called

func (*AIRepository) UpdateModelPerformance

func (r *AIRepository) UpdateModelPerformance(_ context.Context, modelID string, performanceMetrics map[string]float64) error

UpdateModelPerformance tracks AI model performance with accuracy metrics Critical for ML model management and continuous learning

type AccountRepository

type AccountRepository struct {
	// Use EnhancedBaseRepository for comprehensive functionality
	*EnhancedBaseRepository[*models.User]
	// contains filtered or unexported fields
}

AccountRepository unifies User and Actor operations into a single repository This represents the complete account entity with both authentication and federation aspects

func NewAccountRepository

func NewAccountRepository(db core.DB, tableName string, domain string, logger *zap.Logger) *AccountRepository

NewAccountRepository creates a new unified account repository

func NewAccountRepositoryWithCostTracking

func NewAccountRepositoryWithCostTracking(db core.DB, tableName string, domain string, logger *zap.Logger, costService *cost.TrackingService) *AccountRepository

NewAccountRepositoryWithCostTracking creates a new account repository with cost tracking

func (*AccountRepository) AddBookmark

func (r *AccountRepository) AddBookmark(ctx context.Context, username, objectID string) error

AddBookmark bookmarks an object for a user

func (*AccountRepository) AddToTimeline

func (r *AccountRepository) AddToTimeline(ctx context.Context, username string, entry *storage.TimelineEntry) error

AddToTimeline adds an entry to a user's home timeline

func (*AccountRepository) ApproveAccount

func (r *AccountRepository) ApproveAccount(ctx context.Context, username string) error

ApproveAccount approves a pending user account

func (*AccountRepository) Block

func (r *AccountRepository) Block(ctx context.Context, blockerUsername, blockedUsername string) error

Block creates a block relationship

func (*AccountRepository) CacheRemoteActor

func (r *AccountRepository) CacheRemoteActor(ctx context.Context, actor *activitypub.Actor) error

CacheRemoteActor caches a remote actor for search

func (*AccountRepository) CleanupExpiredAdvancedTokens

func (r *AccountRepository) CleanupExpiredAdvancedTokens(ctx context.Context) (int, error)

CleanupExpiredAdvancedTokens removes expired tokens (maintenance task)

func (*AccountRepository) ClearLoginAttempts

func (r *AccountRepository) ClearLoginAttempts(ctx context.Context, key string) error

ClearLoginAttempts clears all login attempts for a key

func (*AccountRepository) CreateAccount

func (r *AccountRepository) CreateAccount(ctx context.Context, account *storage.Account) error

CreateAccount creates both User and Actor entities atomically using enhanced patterns This ensures consistency between authentication and federation data

func (*AccountRepository) CreateAccountLegacy

func (r *AccountRepository) CreateAccountLegacy(ctx context.Context, username, email, passwordHash string, approved bool, actor *activitypub.Actor, _ string) error

CreateAccountLegacy ensures consistency between authentication and federation data.

func (*AccountRepository) CreateAccountNote

func (r *AccountRepository) CreateAccountNote(ctx context.Context, note *storage.AccountNote) error

CreateAccountNote creates or updates a private note on an account

func (*AccountRepository) CreateAccountPin

func (r *AccountRepository) CreateAccountPin(ctx context.Context, pin *storage.AccountPin) error

CreateAccountPin creates a new account pin

func (*AccountRepository) CreateAdvancedRefreshToken

func (r *AccountRepository) CreateAdvancedRefreshToken(ctx context.Context, userID string, deviceName string, ipAddress string) (*models.AuthRefreshToken, error)

CreateAdvancedRefreshToken generates and stores a new refresh token with family-based security

func (*AccountRepository) CreateAuthorizationCode

func (r *AccountRepository) CreateAuthorizationCode(ctx context.Context, code *storage.AuthorizationCode) error

CreateAuthorizationCode creates a new OAuth authorization code

func (*AccountRepository) CreateDevice

func (r *AccountRepository) CreateDevice(ctx context.Context, device *storage.Device) error

CreateDevice creates a new device record

func (*AccountRepository) CreateFollowRefactored

func (r *AccountRepository) CreateFollowRefactored(ctx context.Context, followerUsername, followedUsername string) error

CreateFollowRefactored is an example refactored CreateFollow method using utilities

func (*AccountRepository) CreateOAuthClient

func (r *AccountRepository) CreateOAuthClient(ctx context.Context, client *storage.OAuthClient) error

CreateOAuthClient creates a new OAuth client

func (*AccountRepository) CreateOAuthDeviceSession added in v1.1.2

func (r *AccountRepository) CreateOAuthDeviceSession(ctx context.Context, session *storage.OAuthDeviceSession) error

CreateOAuthDeviceSession stores a new OAuth device authorization session.

func (*AccountRepository) CreatePasswordReset

func (r *AccountRepository) CreatePasswordReset(ctx context.Context, reset *storage.PasswordReset) error

CreatePasswordReset creates a password reset request

func (*AccountRepository) CreatePasswordResetToken

func (r *AccountRepository) CreatePasswordResetToken(ctx context.Context, username, email string) (string, error)

CreatePasswordResetToken creates a password reset token for a user

func (*AccountRepository) CreateRefreshToken

func (r *AccountRepository) CreateRefreshToken(ctx context.Context, token *storage.RefreshToken) error

CreateRefreshToken creates a new OAuth refresh token

func (*AccountRepository) CreateSession

func (r *AccountRepository) CreateSession(ctx context.Context, username, ipAddress, userAgent string) (*storage.Session, error)

CreateSession creates a new session for a user

func (*AccountRepository) CreateSessionFromStruct

func (r *AccountRepository) CreateSessionFromStruct(ctx context.Context, session *storage.Session) error

CreateSessionFromStruct creates a new user session from storage.Session struct

func (*AccountRepository) CreateWebAuthnChallenge

func (r *AccountRepository) CreateWebAuthnChallenge(ctx context.Context, challenge *storage.WebAuthnChallenge) error

CreateWebAuthnChallenge creates a WebAuthn challenge for authentication

func (*AccountRepository) CreateWebAuthnCredential

func (r *AccountRepository) CreateWebAuthnCredential(ctx context.Context, credential *storage.WebAuthnCredential) error

CreateWebAuthnCredential creates a new WebAuthn credential for a user

func (*AccountRepository) DeleteAccount

func (r *AccountRepository) DeleteAccount(ctx context.Context, username string) error

DeleteAccount removes both User and Actor entities

func (*AccountRepository) DeleteAccountPin

func (r *AccountRepository) DeleteAccountPin(ctx context.Context, username, targetActorID string) error

DeleteAccountPin removes an account pin

func (*AccountRepository) DeleteAuthorizationCode

func (r *AccountRepository) DeleteAuthorizationCode(ctx context.Context, code string) error

DeleteAuthorizationCode deletes an OAuth authorization code

func (*AccountRepository) DeleteOAuthClient

func (r *AccountRepository) DeleteOAuthClient(ctx context.Context, clientID string) error

DeleteOAuthClient deletes an OAuth client

func (*AccountRepository) DeleteOAuthState

func (r *AccountRepository) DeleteOAuthState(ctx context.Context, state string) error

DeleteOAuthState deletes OAuth state

func (*AccountRepository) DeleteRecoveryToken

func (r *AccountRepository) DeleteRecoveryToken(ctx context.Context, key string) error

DeleteRecoveryToken deletes a recovery token

func (*AccountRepository) DeleteRefreshToken

func (r *AccountRepository) DeleteRefreshToken(ctx context.Context, token string) error

DeleteRefreshToken deletes an OAuth refresh token

func (*AccountRepository) DeleteRefreshTokensByUsernameAndClientID added in v1.1.6

func (r *AccountRepository) DeleteRefreshTokensByUsernameAndClientID(ctx context.Context, username, clientID string) (int, error)

DeleteRefreshTokensByUsernameAndClientID deletes all OAuth refresh tokens for the given user+client pair. This is intended for revoking delegated/agent tokens where only refresh-token invalidation is required.

func (*AccountRepository) DeleteSession

func (r *AccountRepository) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession deletes a session

func (*AccountRepository) DeleteWalletChallenge

func (r *AccountRepository) DeleteWalletChallenge(ctx context.Context, challengeID string) error

DeleteWalletChallenge removes a wallet challenge

func (*AccountRepository) DeleteWalletCredential

func (r *AccountRepository) DeleteWalletCredential(ctx context.Context, username, address string) error

DeleteWalletCredential removes a wallet credential by username and address

func (*AccountRepository) DeleteWalletCredentialByAddress

func (r *AccountRepository) DeleteWalletCredentialByAddress(ctx context.Context, username, address string) error

DeleteWalletCredentialByAddress removes a wallet credential by username and address

func (*AccountRepository) DeleteWebAuthnChallenge

func (r *AccountRepository) DeleteWebAuthnChallenge(ctx context.Context, challenge string) error

DeleteWebAuthnChallenge removes a WebAuthn challenge

func (*AccountRepository) DeleteWebAuthnCredential

func (r *AccountRepository) DeleteWebAuthnCredential(ctx context.Context, credentialID string) error

DeleteWebAuthnCredential removes a WebAuthn credential

func (*AccountRepository) Follow

func (r *AccountRepository) Follow(ctx context.Context, followerUsername, followedUsername string) error

Follow creates a follow relationship between users

func (*AccountRepository) GetAccount

func (r *AccountRepository) GetAccount(ctx context.Context, username string) (*storage.Account, error)

GetAccount retrieves complete account information (User + Actor)

func (*AccountRepository) GetAccountByEmail

func (r *AccountRepository) GetAccountByEmail(ctx context.Context, email string) (*storage.Account, error)

GetAccountByEmail retrieves an account by email address (updated to match interface)

func (*AccountRepository) GetAccountByURL

func (r *AccountRepository) GetAccountByURL(ctx context.Context, actorURL string) (*storage.Account, error)

GetAccountByURL retrieves an account by its ActivityPub URL

func (*AccountRepository) GetAccountFeatures

func (r *AccountRepository) GetAccountFeatures(ctx context.Context, username string) (map[string]bool, error)

GetAccountFeatures retrieves account feature flags

func (*AccountRepository) GetAccountPin

func (r *AccountRepository) GetAccountPin(ctx context.Context, username, targetActorID string) (*storage.AccountPin, error)

GetAccountPin retrieves a specific account pin by actor ID

func (*AccountRepository) GetAccountPins

func (r *AccountRepository) GetAccountPins(ctx context.Context, username string) ([]*storage.AccountPin, error)

GetAccountPins retrieves all account pins for a user

func (*AccountRepository) GetAccountPreferences

func (r *AccountRepository) GetAccountPreferences(ctx context.Context, username string) (map[string]interface{}, error)

GetAccountPreferences retrieves all preferences for an account

func (*AccountRepository) GetAccountSuggestions

func (r *AccountRepository) GetAccountSuggestions(ctx context.Context, username string, limit int) ([]*storage.AccountSuggestion, error)

GetAccountSuggestions returns suggested accounts for a user to follow

func (*AccountRepository) GetAccountsByUsernames

func (r *AccountRepository) GetAccountsByUsernames(ctx context.Context, usernames []string) ([]*storage.Account, error)

GetAccountsByUsernames retrieves multiple accounts by their usernames

func (*AccountRepository) GetAccountsCount

func (r *AccountRepository) GetAccountsCount(ctx context.Context) (int64, error)

GetAccountsCount retrieves the total number of accounts

func (*AccountRepository) GetActiveAdvancedTokensForUser

func (r *AccountRepository) GetActiveAdvancedTokensForUser(ctx context.Context, userID string) ([]models.AuthRefreshToken, error)

GetActiveAdvancedTokensForUser retrieves all active (non-expired, non-revoked) tokens for a user

func (*AccountRepository) GetActiveUsers

func (r *AccountRepository) GetActiveUsers(ctx context.Context, since time.Time, limit int) ([]*storage.User, error)

GetActiveUsers returns recently active users

func (*AccountRepository) GetActor

func (r *AccountRepository) GetActor(ctx context.Context, username string) (*activitypub.Actor, error)

GetActor retrieves an actor by username

func (*AccountRepository) GetActorByUsername

func (r *AccountRepository) GetActorByUsername(ctx context.Context, username string) (*activitypub.Actor, error)

GetActorByUsername is an alias for GetActor (for compatibility)

func (*AccountRepository) GetActorPrivateKey

func (r *AccountRepository) GetActorPrivateKey(ctx context.Context, username string) (string, error)

GetActorPrivateKey retrieves an actor's private key

func (*AccountRepository) GetAdvancedRefreshToken

func (r *AccountRepository) GetAdvancedRefreshToken(ctx context.Context, token string) (*models.AuthRefreshToken, error)

GetAdvancedRefreshToken retrieves an advanced refresh token by token value

func (*AccountRepository) GetAdvancedTokenStats

func (r *AccountRepository) GetAdvancedTokenStats(ctx context.Context, userID string) (*TokenStats, error)

GetAdvancedTokenStats returns statistics about tokens for monitoring

func (*AccountRepository) GetAdvancedTokensByFamily

func (r *AccountRepository) GetAdvancedTokensByFamily(ctx context.Context, family string) ([]models.AuthRefreshToken, error)

GetAdvancedTokensByFamily retrieves all tokens in a family

func (*AccountRepository) GetAdvancedTokensByUser

func (r *AccountRepository) GetAdvancedTokensByUser(ctx context.Context, userID string) ([]models.AuthRefreshToken, error)

GetAdvancedTokensByUser retrieves all tokens for a user

func (*AccountRepository) GetAllUsersForWallet

func (r *AccountRepository) GetAllUsersForWallet(ctx context.Context, walletType, address string) ([]string, error)

GetAllUsersForWallet retrieves all users linked to a specific wallet

func (*AccountRepository) GetAuthorizationCode

func (r *AccountRepository) GetAuthorizationCode(ctx context.Context, code string) (*storage.AuthorizationCode, error)

GetAuthorizationCode retrieves an OAuth authorization code

func (*AccountRepository) GetBlocks

func (r *AccountRepository) GetBlocks(ctx context.Context, username string) ([]*storage.Block, error)

GetBlocks retrieves all users blocked by a user

func (*AccountRepository) GetBookmarkedStatuses

func (r *AccountRepository) GetBookmarkedStatuses(ctx context.Context, username string, opts interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.Status], error)

GetBookmarkedStatuses retrieves paginated bookmarked statuses for a user

func (*AccountRepository) GetBookmarks

func (r *AccountRepository) GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*storage.Bookmark, string, error)

GetBookmarks retrieves paginated bookmarks for a user

func (*AccountRepository) GetConversations

func (r *AccountRepository) GetConversations(ctx context.Context, username string, limit int, maxID, sinceID string) ([]*storage.Conversation, error)

GetConversations retrieves conversations for a user

func (*AccountRepository) GetDevice

func (r *AccountRepository) GetDevice(ctx context.Context, deviceID string) (*storage.Device, error)

GetDevice retrieves a device by ID

func (*AccountRepository) GetFeaturedAccounts

GetFeaturedAccounts retrieves featured accounts

func (*AccountRepository) GetFieldVerification

func (r *AccountRepository) GetFieldVerification(ctx context.Context, username, fieldName string) (*storage.ActorField, error)

GetFieldVerification retrieves field verification info for a user

func (*AccountRepository) GetFollowRequestState

func (r *AccountRepository) GetFollowRequestState(ctx context.Context, requesterID, targetID string) (string, error)

GetFollowRequestState retrieves the state of a follow request

func (*AccountRepository) GetFollowers

func (r *AccountRepository) GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Actor, string, error)

GetFollowers retrieves a paginated list of accepted followers for a user.

func (*AccountRepository) GetFollowing

func (r *AccountRepository) GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Actor, string, error)

GetFollowing retrieves paginated list of users that a user follows

func (*AccountRepository) GetHashtagTimeline

func (r *AccountRepository) GetHashtagTimeline(ctx context.Context, hashtag string, limit int, maxID, sinceID string) ([]*storage.TimelineEntry, error)

GetHashtagTimeline retrieves timeline entries for a hashtag

func (*AccountRepository) GetHomeTimeline

func (r *AccountRepository) GetHomeTimeline(ctx context.Context, username string, limit int, maxID, sinceID string) ([]*storage.TimelineEntry, error)

GetHomeTimeline retrieves the home timeline for a user

func (*AccountRepository) GetInactiveUsers

func (r *AccountRepository) GetInactiveUsers(ctx context.Context, inactiveSince time.Time, limit int) ([]*storage.User, error)

GetInactiveUsers returns users who haven't been active recently

func (*AccountRepository) GetLinkedProviders

func (r *AccountRepository) GetLinkedProviders(ctx context.Context, username string) ([]string, error)

GetLinkedProviders gets all linked OAuth providers for a user

func (*AccountRepository) GetListTimeline

func (r *AccountRepository) GetListTimeline(ctx context.Context, username, listID string, limit int, maxID, sinceID string) ([]*storage.TimelineEntry, error)

GetListTimeline retrieves timeline entries for a list

func (*AccountRepository) GetLocalTimeline

func (r *AccountRepository) GetLocalTimeline(ctx context.Context, limit int, maxID, sinceID string) ([]*storage.TimelineEntry, error)

GetLocalTimeline retrieves the local public timeline

func (*AccountRepository) GetLoginAttemptCount

func (r *AccountRepository) GetLoginAttemptCount(ctx context.Context, key string, since time.Time) (int, error)

GetLoginAttemptCount gets the number of login attempts since a given time

func (*AccountRepository) GetLoginHistory

GetLoginHistory retrieves login history for a user

func (*AccountRepository) GetMutes

func (r *AccountRepository) GetMutes(ctx context.Context, username string) ([]*storage.Mute, error)

GetMutes retrieves all users muted by a user

func (*AccountRepository) GetOAuthApp

func (r *AccountRepository) GetOAuthApp(ctx context.Context, clientID string) (*storage.OAuthApp, error)

GetOAuthApp retrieves an OAuth application by client ID (alias for GetOAuthClient)

func (*AccountRepository) GetOAuthClient

func (r *AccountRepository) GetOAuthClient(ctx context.Context, clientID string) (*storage.OAuthClient, error)

GetOAuthClient retrieves an OAuth client by client ID

func (*AccountRepository) GetOAuthDeviceSession added in v1.1.2

func (r *AccountRepository) GetOAuthDeviceSession(ctx context.Context, deviceCodeHash string) (*storage.OAuthDeviceSession, error)

GetOAuthDeviceSession loads an OAuth device session by its device_code hash.

func (*AccountRepository) GetOAuthDeviceSessionByUserCode added in v1.1.2

func (r *AccountRepository) GetOAuthDeviceSessionByUserCode(ctx context.Context, userCode string) (*storage.OAuthDeviceSession, error)

GetOAuthDeviceSessionByUserCode loads an OAuth device session by its user_code (used by the web approval flow).

func (*AccountRepository) GetOAuthState

func (r *AccountRepository) GetOAuthState(ctx context.Context, state string) (*storage.OAuthState, error)

GetOAuthState retrieves OAuth state

func (*AccountRepository) GetPasswordReset

func (r *AccountRepository) GetPasswordReset(ctx context.Context, token string) (*storage.PasswordReset, error)

GetPasswordReset retrieves a password reset by token

func (*AccountRepository) GetPinnedAccounts

func (r *AccountRepository) GetPinnedAccounts(ctx context.Context, username string) ([]*activitypub.Actor, error)

GetPinnedAccounts retrieves pinned accounts for a user

func (*AccountRepository) GetPreference

func (r *AccountRepository) GetPreference(ctx context.Context, username, key string) (string, error)

GetPreference retrieves a specific user preference

func (*AccountRepository) GetPublicTimeline

func (r *AccountRepository) GetPublicTimeline(ctx context.Context, limit int, maxID, sinceID string, onlyMedia bool) ([]*storage.TimelineEntry, error)

GetPublicTimeline retrieves the federated public timeline

func (*AccountRepository) GetRecentLoginAttempts

func (r *AccountRepository) GetRecentLoginAttempts(ctx context.Context, username string, since time.Time) ([]*storage.LoginAttempt, error)

GetRecentLoginAttempts retrieves recent login attempts for a user

func (*AccountRepository) GetRecoveryToken

func (r *AccountRepository) GetRecoveryToken(ctx context.Context, key string) (map[string]interface{}, error)

GetRecoveryToken retrieves a recovery token

func (*AccountRepository) GetRefreshToken

func (r *AccountRepository) GetRefreshToken(ctx context.Context, token string) (*storage.RefreshToken, error)

GetRefreshToken retrieves an OAuth refresh token

func (*AccountRepository) GetSession

func (r *AccountRepository) GetSession(ctx context.Context, sessionID string) (*storage.Session, error)

GetSession retrieves a session by ID

func (*AccountRepository) GetSessionByRefreshToken

func (r *AccountRepository) GetSessionByRefreshToken(ctx context.Context, refreshToken string) (*storage.Session, error)

GetSessionByRefreshToken finds a session by refresh token

func (*AccountRepository) GetSuggestedAccounts

GetSuggestedAccounts retrieves suggested accounts to follow

func (*AccountRepository) GetTimelineMarkers

func (r *AccountRepository) GetTimelineMarkers(ctx context.Context, username string, timelines []string) (map[string]*storage.Marker, error)

GetTimelineMarkers retrieves timeline position markers for a user

func (*AccountRepository) GetTrendingActors

func (r *AccountRepository) GetTrendingActors(ctx context.Context, limit int) ([]*activitypub.Actor, error)

GetTrendingActors returns actors that are currently trending

func (*AccountRepository) GetUser

func (r *AccountRepository) GetUser(ctx context.Context, username string) (*storage.User, error)

GetUser retrieves user authentication data

func (*AccountRepository) GetUserAppConsent

func (r *AccountRepository) GetUserAppConsent(ctx context.Context, userID, appID string) (*storage.UserAppConsent, error)

GetUserAppConsent retrieves user consent for an OAuth app

func (*AccountRepository) GetUserByEmail

func (r *AccountRepository) GetUserByEmail(_ context.Context, email string) (*storage.User, error)

GetUserByEmail is OBSOLETE - email is forbidden This function exists for backwards compatibility but always returns an error

func (*AccountRepository) GetUserByEmailRefactored

func (r *AccountRepository) GetUserByEmailRefactored(ctx context.Context, email string) (*storage.User, error)

GetUserByEmailRefactored is an example refactored GetUserByEmail method using utilities

func (*AccountRepository) GetUserByRecoveryCode

func (r *AccountRepository) GetUserByRecoveryCode(ctx context.Context, recoveryCode string) (*storage.User, error)

GetUserByRecoveryCode retrieves a user by recovery code (for email-free auth)

func (*AccountRepository) GetUserDevices

func (r *AccountRepository) GetUserDevices(ctx context.Context, username string) ([]*storage.Device, error)

GetUserDevices gets all devices for a user

func (*AccountRepository) GetUserRefactored

func (r *AccountRepository) GetUserRefactored(ctx context.Context, username string) (*storage.User, error)

GetUserRefactored demonstrates an example refactored GetUser method using utilities

func (*AccountRepository) GetUserSessions

func (r *AccountRepository) GetUserSessions(ctx context.Context, username string) ([]*storage.Session, error)

GetUserSessions retrieves all active sessions for a user

func (*AccountRepository) GetUserWalletCredentials

func (r *AccountRepository) GetUserWalletCredentials(ctx context.Context, username string) ([]*storage.WalletCredential, error)

GetUserWalletCredentials retrieves all wallet credentials for a user

func (*AccountRepository) GetUserWallets

func (r *AccountRepository) GetUserWallets(ctx context.Context, username string) ([]*storage.WalletCredential, error)

GetUserWallets retrieves all wallet credentials for a user

func (*AccountRepository) GetUserWebAuthnCredentials

func (r *AccountRepository) GetUserWebAuthnCredentials(ctx context.Context, userID string) ([]*storage.WebAuthnCredential, error)

GetUserWebAuthnCredentials retrieves all WebAuthn credentials for a user

func (*AccountRepository) GetWalletByAddress

func (r *AccountRepository) GetWalletByAddress(ctx context.Context, walletType, address string) (*storage.WalletCredential, error)

GetWalletByAddress retrieves a wallet credential by address and type This uses the index to find any user with this wallet, then filters by type if specified

func (*AccountRepository) GetWalletChallenge

func (r *AccountRepository) GetWalletChallenge(ctx context.Context, challengeID string) (*storage.WalletChallenge, error)

GetWalletChallenge retrieves a wallet challenge by challenge ID

func (*AccountRepository) GetWalletCredential

func (r *AccountRepository) GetWalletCredential(ctx context.Context, address string) (*storage.WalletCredential, error)

GetWalletCredential retrieves a wallet credential by address

func (*AccountRepository) GetWebAuthnChallenge

func (r *AccountRepository) GetWebAuthnChallenge(ctx context.Context, challenge string) (*storage.WebAuthnChallenge, error)

GetWebAuthnChallenge retrieves a WebAuthn challenge by challenge value

func (*AccountRepository) GetWebAuthnCredential

func (r *AccountRepository) GetWebAuthnCredential(ctx context.Context, credentialID string) (*storage.WebAuthnCredential, error)

GetWebAuthnCredential retrieves a WebAuthn credential by ID

func (*AccountRepository) InvalidateAllSessions

func (r *AccountRepository) InvalidateAllSessions(ctx context.Context, username string) error

InvalidateAllSessions invalidates all sessions for a user

func (*AccountRepository) InvalidateSession

func (r *AccountRepository) InvalidateSession(ctx context.Context, username, sessionID string) error

InvalidateSession invalidates a specific session

func (*AccountRepository) IsAccountPinned

func (r *AccountRepository) IsAccountPinned(ctx context.Context, username, targetActorID string) (bool, error)

IsAccountPinned checks if an account is pinned by a user

func (*AccountRepository) IsBlocked

func (r *AccountRepository) IsBlocked(ctx context.Context, blockerUsername, blockedUsername string) (bool, error)

IsBlocked checks if one user has blocked another

func (*AccountRepository) IsBlockedDomain

func (r *AccountRepository) IsBlockedDomain(ctx context.Context, userID, domain string) (bool, error)

IsBlockedDomain checks if a domain is blocked by a user

func (*AccountRepository) IsConversationMuted

func (r *AccountRepository) IsConversationMuted(ctx context.Context, username, conversationID string) (bool, error)

IsConversationMuted checks if a conversation is muted

func (*AccountRepository) IsFollowing

func (r *AccountRepository) IsFollowing(ctx context.Context, followerUsername, followedUsername string) (bool, error)

IsFollowing checks if one user follows another

func (*AccountRepository) IsMuted

func (r *AccountRepository) IsMuted(ctx context.Context, muterUsername, mutedUsername string) (bool, bool, error)

IsMuted checks if one user has muted another

func (*AccountRepository) IsRateLimited

func (r *AccountRepository) IsRateLimited(ctx context.Context, key string) (bool, time.Time, error)

IsRateLimited checks if a key is currently rate limited

func (*AccountRepository) ListOAuthClients

func (r *AccountRepository) ListOAuthClients(ctx context.Context, limit int, cursor string) ([]*storage.OAuthClient, string, error)

ListOAuthClients lists OAuth clients with deterministic cursor-based pagination.

func (*AccountRepository) MarkWalletChallengeSpent

func (r *AccountRepository) MarkWalletChallengeSpent(ctx context.Context, challengeID string) error

MarkWalletChallengeSpent marks a challenge as spent (second verification)

func (*AccountRepository) MarkWalletChallengeUsed

func (r *AccountRepository) MarkWalletChallengeUsed(ctx context.Context, challengeID string) error

MarkWalletChallengeUsed marks a challenge as used (first verification)

func (*AccountRepository) Mute

func (r *AccountRepository) Mute(ctx context.Context, muterUsername, mutedUsername string, notifications bool, _ time.Duration) error

Mute creates a mute relationship

func (*AccountRepository) MuteConversation

func (r *AccountRepository) MuteConversation(ctx context.Context, username, conversationID string) error

MuteConversation mutes a conversation for a user

func (*AccountRepository) PinAccount

func (r *AccountRepository) PinAccount(ctx context.Context, username, pinnedUsername string) error

PinAccount pins an account for a user

func (*AccountRepository) RecordLogin

func (r *AccountRepository) RecordLogin(ctx context.Context, attempt *storage.LoginAttempt) error

RecordLogin records a login attempt

func (*AccountRepository) RecordLoginAttempt

func (r *AccountRepository) RecordLoginAttempt(ctx context.Context, key string, success bool) error

RecordLoginAttempt records a login attempt for rate limiting

func (*AccountRepository) RemoveBookmark

func (r *AccountRepository) RemoveBookmark(ctx context.Context, username, objectID string) error

RemoveBookmark removes a bookmark

func (*AccountRepository) RemoveFromTimeline

func (r *AccountRepository) RemoveFromTimeline(ctx context.Context, username, objectID string) error

RemoveFromTimeline removes an entry from a user's timeline

func (*AccountRepository) ResetPassword

func (r *AccountRepository) ResetPassword(ctx context.Context, token, newPasswordHash string) error

ResetPassword resets a user's password using a valid token

func (*AccountRepository) RevokeAdvancedTokenFamily

func (r *AccountRepository) RevokeAdvancedTokenFamily(ctx context.Context, family string, reason string) error

RevokeAdvancedTokenFamily revokes all tokens in a family (security measure)

func (*AccountRepository) RevokeAdvancedUserTokens

func (r *AccountRepository) RevokeAdvancedUserTokens(ctx context.Context, userID string, reason string) error

RevokeAdvancedUserTokens revokes all tokens for a user (e.g., on logout)

func (*AccountRepository) RotateAdvancedRefreshToken

func (r *AccountRepository) RotateAdvancedRefreshToken(ctx context.Context, oldTokenValue string, ipAddress string) (*models.AuthRefreshToken, error)

RotateAdvancedRefreshToken rotates a refresh token (creates new one, revokes old one)

func (*AccountRepository) SaveUserAppConsent

func (r *AccountRepository) SaveUserAppConsent(ctx context.Context, consent *storage.UserAppConsent) error

SaveUserAppConsent saves user consent for an OAuth app

func (*AccountRepository) SearchAccounts

SearchAccounts searches for accounts matching a query

func (*AccountRepository) SearchActors

func (r *AccountRepository) SearchActors(ctx context.Context, query string, limit int, offset int, following bool, username string) ([]*activitypub.Actor, error)

SearchActors searches for actors by username or display name

func (*AccountRepository) SearchByWebfinger

func (r *AccountRepository) SearchByWebfinger(ctx context.Context, webfinger string) (*activitypub.Actor, error)

SearchByWebfinger searches for an actor by webfinger address

func (*AccountRepository) SetBookmarkRepository

func (r *AccountRepository) SetBookmarkRepository(bookmarkRepo *BookmarkRepository)

SetBookmarkRepository wires the bookmark repository for dual-write operations

func (*AccountRepository) SetEncryptor

func (r *AccountRepository) SetEncryptor(encryptor marshalers.Encryptor)

SetEncryptor overrides the encryptor used for actor private keys. When unset, the repository uses KMS based on runtime configuration.

func (*AccountRepository) SetStatusRepository

func (r *AccountRepository) SetStatusRepository(statusRepo interfaces.StatusRepository)

SetStatusRepository sets the status repository dependency for cross-repository operations

func (*AccountRepository) SetStorage

func (r *AccountRepository) SetStorage(_ interface{})

SetStorage is deprecated - storage dependency removed in Phase 5.6

func (*AccountRepository) SilenceAccount

func (r *AccountRepository) SilenceAccount(ctx context.Context, username string, reason string) error

SilenceAccount silences a user account with a reason

func (*AccountRepository) StoreOAuthState

func (r *AccountRepository) StoreOAuthState(ctx context.Context, state string, data *storage.OAuthState) error

StoreOAuthState stores OAuth state for CSRF protection

func (*AccountRepository) StoreOAuthStateRefactored

func (r *AccountRepository) StoreOAuthStateRefactored(ctx context.Context, state string, data *storage.OAuthState) error

StoreOAuthStateRefactored is an example refactored OAuth state creation using utilities

func (*AccountRepository) StoreRecoveryToken

func (r *AccountRepository) StoreRecoveryToken(ctx context.Context, key string, data map[string]interface{}) error

StoreRecoveryToken stores a recovery token

func (*AccountRepository) StoreWalletChallenge

func (r *AccountRepository) StoreWalletChallenge(ctx context.Context, challenge *storage.WalletChallenge) error

StoreWalletChallenge stores a wallet-based authentication challenge

func (*AccountRepository) StoreWalletCredential

func (r *AccountRepository) StoreWalletCredential(ctx context.Context, credential *storage.WalletCredential) error

StoreWalletCredential stores a wallet-based credential

func (*AccountRepository) StoreWebAuthnChallenge

func (r *AccountRepository) StoreWebAuthnChallenge(ctx context.Context, challenge *storage.WebAuthnChallenge) error

StoreWebAuthnChallenge stores a WebAuthn challenge

func (*AccountRepository) StoreWebAuthnCredential

func (r *AccountRepository) StoreWebAuthnCredential(ctx context.Context, credential *storage.WebAuthnCredential) error

StoreWebAuthnCredential stores a WebAuthn credential

func (*AccountRepository) SuspendAccount

func (r *AccountRepository) SuspendAccount(ctx context.Context, username string, reason string) error

SuspendAccount suspends a user account with a reason

func (*AccountRepository) Unblock

func (r *AccountRepository) Unblock(ctx context.Context, blockerUsername, blockedUsername string) error

Unblock removes a block relationship

func (*AccountRepository) Unfollow

func (r *AccountRepository) Unfollow(ctx context.Context, followerUsername, followedUsername string) error

Unfollow removes a follow relationship between users

func (*AccountRepository) Unmute

func (r *AccountRepository) Unmute(ctx context.Context, muterUsername, mutedUsername string) error

Unmute removes a mute relationship

func (*AccountRepository) UnmuteConversation

func (r *AccountRepository) UnmuteConversation(ctx context.Context, username, conversationID string) error

UnmuteConversation unmutes a conversation for a user

func (*AccountRepository) UnpinAccount

func (r *AccountRepository) UnpinAccount(ctx context.Context, username, pinnedUsername string) error

UnpinAccount unpins an account for a user

func (*AccountRepository) UnsilenceAccount

func (r *AccountRepository) UnsilenceAccount(ctx context.Context, username string) error

UnsilenceAccount removes silence from a user account

func (*AccountRepository) UnsuspendAccount

func (r *AccountRepository) UnsuspendAccount(ctx context.Context, username string) error

UnsuspendAccount removes suspension from a user account

func (*AccountRepository) UpdateAccount

func (r *AccountRepository) UpdateAccount(ctx context.Context, account *storage.Account) error

UpdateAccount updates account data (updated to match interface)

func (*AccountRepository) UpdateAccountFeatures

func (r *AccountRepository) UpdateAccountFeatures(ctx context.Context, username string, features map[string]bool) error

UpdateAccountFeatures updates account feature flags

func (*AccountRepository) UpdateAccountPreferences

func (r *AccountRepository) UpdateAccountPreferences(ctx context.Context, username string, preferences map[string]interface{}) error

UpdateAccountPreferences updates user preferences

func (*AccountRepository) UpdateAdvancedTokenLastUsed

func (r *AccountRepository) UpdateAdvancedTokenLastUsed(ctx context.Context, tokenValue string, ipAddress string) error

UpdateAdvancedTokenLastUsed updates the last used timestamp for a token

func (*AccountRepository) UpdateDevice

func (r *AccountRepository) UpdateDevice(ctx context.Context, device *storage.Device) error

UpdateDevice updates an existing device

func (*AccountRepository) UpdateLastActivity

func (r *AccountRepository) UpdateLastActivity(ctx context.Context, username string, activity time.Time) error

UpdateLastActivity updates the last activity timestamp for a user

func (*AccountRepository) UpdateLastLogin

func (r *AccountRepository) UpdateLastLogin(ctx context.Context, username string) error

UpdateLastLogin updates the user's last login timestamp

func (*AccountRepository) UpdateLastSeen

func (r *AccountRepository) UpdateLastSeen(ctx context.Context, username string) error

UpdateLastSeen updates the last seen timestamp for a user

func (*AccountRepository) UpdateOAuthClient

func (r *AccountRepository) UpdateOAuthClient(ctx context.Context, clientID string, updates map[string]any) error

UpdateOAuthClient updates an existing OAuth client

func (*AccountRepository) UpdateOAuthClientSecretHash

func (r *AccountRepository) UpdateOAuthClientSecretHash(ctx context.Context, clientID, clientSecretHash string) error

UpdateOAuthClientSecretHash updates the stored secret representation for an OAuth client. The value must be a hash string (e.g. prefixed bcrypt hash) and should never be a plaintext secret.

func (*AccountRepository) UpdateOAuthDeviceSession added in v1.1.2

func (r *AccountRepository) UpdateOAuthDeviceSession(ctx context.Context, session *storage.OAuthDeviceSession) error

UpdateOAuthDeviceSession persists changes to an existing OAuth device session.

func (*AccountRepository) UpdatePassword

func (r *AccountRepository) UpdatePassword(ctx context.Context, username, newPasswordHash string) error

UpdatePassword updates a user's password hash

func (*AccountRepository) UpdateSession

func (r *AccountRepository) UpdateSession(ctx context.Context, sessionID, refreshToken, ipAddress string, lastActivity, expiresAt time.Time) error

UpdateSession updates an existing session with specific fields

func (*AccountRepository) UpdateTimelineMarker

func (r *AccountRepository) UpdateTimelineMarker(ctx context.Context, username, timeline, lastReadID string) error

UpdateTimelineMarker updates the position marker for a timeline

func (*AccountRepository) UpdateUser

func (r *AccountRepository) UpdateUser(ctx context.Context, username string, updates map[string]interface{}) error

UpdateUser updates user authentication data

func (*AccountRepository) UpdateWalletLastUsed

func (r *AccountRepository) UpdateWalletLastUsed(ctx context.Context, username, address string) error

UpdateWalletLastUsed updates when a wallet was last used

func (*AccountRepository) UpdateWebAuthnCredential

func (r *AccountRepository) UpdateWebAuthnCredential(ctx context.Context, credentialID string, signCount uint32) error

UpdateWebAuthnCredential updates a WebAuthn credential

func (*AccountRepository) UpdateWebAuthnLastUsed

func (r *AccountRepository) UpdateWebAuthnLastUsed(ctx context.Context, credentialID string, signCount uint32) error

UpdateWebAuthnLastUsed updates the last used timestamp and sign count for a credential

func (*AccountRepository) UsePasswordReset

func (r *AccountRepository) UsePasswordReset(ctx context.Context, token string) error

UsePasswordReset marks a password reset token as used

func (*AccountRepository) ValidateCredentials

func (r *AccountRepository) ValidateCredentials(ctx context.Context, username, password string) (*storage.Account, error)

ValidateCredentials validates username and password credentials

func (*AccountRepository) ValidatePassword

func (r *AccountRepository) ValidatePassword(ctx context.Context, username, password string) (*storage.User, error)

ValidatePassword validates a user's password and tracks login attempts

func (*AccountRepository) ValidatePasswordResetToken

func (r *AccountRepository) ValidatePasswordResetToken(ctx context.Context, token string) (*storage.PasswordReset, error)

ValidatePasswordResetToken validates a password reset token

type ActivityRepository

type ActivityRepository struct {
	*EnhancedBaseRepository[*models.Activity]
}

ActivityRepository implements activity operations using enhanced repository patterns

func NewActivityRepository

func NewActivityRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ActivityRepository

NewActivityRepository creates a new activity repository with enhanced functionality

func (*ActivityRepository) CreateActivity

func (r *ActivityRepository) CreateActivity(ctx context.Context, activity *activitypub.Activity) error

CreateActivity stores an activity in the database - matches legacy implementation

func (*ActivityRepository) GetActivity

func (r *ActivityRepository) GetActivity(ctx context.Context, id string) (*activitypub.Activity, error)

GetActivity retrieves an activity by ID - matches legacy implementation

func (*ActivityRepository) GetCollection

func (r *ActivityRepository) GetCollection(ctx context.Context, username, collectionType string, limit int, cursor string) (*activitypub.OrderedCollectionPage, error)

GetCollection retrieves a collection for an actor - matches legacy implementation

func (*ActivityRepository) GetHashtagActivity

func (r *ActivityRepository) GetHashtagActivity(ctx context.Context, hashtag string, since time.Time) ([]*storage.Activity, error)

GetHashtagActivity retrieves activities related to a hashtag since a given time

func (*ActivityRepository) GetInboxActivities

func (r *ActivityRepository) GetInboxActivities(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Activity, string, error)

GetInboxActivities returns inbox activities ordered newest-first with opaque pagination cursors.

func (*ActivityRepository) GetOutboxActivities

func (r *ActivityRepository) GetOutboxActivities(ctx context.Context, username string, limit int, cursor string) ([]*activitypub.Activity, string, error)

GetOutboxActivities retrieves activities created by a user - matches legacy implementation

func (*ActivityRepository) GetWeeklyActivity

func (r *ActivityRepository) GetWeeklyActivity(ctx context.Context, weekTimestamp int64) (*storage.WeeklyActivity, error)

GetWeeklyActivity retrieves weekly activity statistics

func (*ActivityRepository) RecordActivity

func (r *ActivityRepository) RecordActivity(ctx context.Context, activityType string, actorID string, timestamp time.Time) error

RecordActivity records general activity metrics

func (*ActivityRepository) RecordFederationActivity

func (r *ActivityRepository) RecordFederationActivity(ctx context.Context, activity *storage.FederationActivity) error

RecordFederationActivity records federation activity metrics

type ActivityTypeCostStats

type ActivityTypeCostStats struct {
	ActivityType          string  `json:"activity_type"`
	Count                 int64   `json:"count"`
	SuccessCount          int64   `json:"success_count"`
	FailureCount          int64   `json:"failure_count"`
	SuccessRate           float64 `json:"success_rate"`
	TotalCostMicroCents   int64   `json:"total_cost_micro_cents"`
	AverageCostMicroCents int64   `json:"average_cost_micro_cents"`
	TotalDataTransferred  int64   `json:"total_data_transferred"`
	AverageResponseTime   float64 `json:"average_response_time"`
}

ActivityTypeCostStats represents cost statistics for a specific activity type

type ActorRepository

type ActorRepository struct {
	*EnhancedBaseRepository[*models.Actor]
	// contains filtered or unexported fields
}

ActorRepository implements actor operations using enhanced DynamORM patterns

func NewActorRepository

func NewActorRepository(db core.DB, tableName string, logger *zap.Logger) *ActorRepository

NewActorRepository creates a new actor repository with enhanced functionality

func NewActorRepositoryWithCostTracking

func NewActorRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ActorRepository

NewActorRepositoryWithCostTracking creates a new actor repository with cost tracking

func (*ActorRepository) CheckAlsoKnownAs

func (r *ActorRepository) CheckAlsoKnownAs(ctx context.Context, username string, targetActorID string) (bool, error)

CheckAlsoKnownAs checks if targetActorID is in the AlsoKnownAs slice for the given username

func (*ActorRepository) CreateActor

func (r *ActorRepository) CreateActor(ctx context.Context, actor *activitypub.Actor, privateKey string) error

CreateActor creates a new actor in DynamoDB

func (*ActorRepository) DeleteActor

func (r *ActorRepository) DeleteActor(ctx context.Context, username string) error

DeleteActor deletes an actor

func (*ActorRepository) GetAccountSuggestions

func (r *ActorRepository) GetAccountSuggestions(ctx context.Context, userID string, limit int) ([]*activitypub.Actor, error)

GetAccountSuggestions gets suggested accounts for a user based on "friends of friends" algorithm

func (*ActorRepository) GetActor

func (r *ActorRepository) GetActor(ctx context.Context, username string) (*activitypub.Actor, error)

GetActor retrieves an actor by username

func (*ActorRepository) GetActorByNumericID

func (r *ActorRepository) GetActorByNumericID(ctx context.Context, numericID string) (*activitypub.Actor, error)

GetActorByNumericID retrieves an actor by numeric ID

func (*ActorRepository) GetActorByUsername

func (r *ActorRepository) GetActorByUsername(ctx context.Context, username string) (*activitypub.Actor, error)

GetActorByUsername retrieves an actor by username

func (*ActorRepository) GetActorMigrationInfo

func (r *ActorRepository) GetActorMigrationInfo(ctx context.Context, username string) (*interfaces.MigrationInfo, error)

GetActorMigrationInfo returns migration information for an actor

func (*ActorRepository) GetActorPrivateKey

func (r *ActorRepository) GetActorPrivateKey(ctx context.Context, username string) (string, error)

GetActorPrivateKey retrieves an actor's private key

func (*ActorRepository) GetActorWithMetadata

func (r *ActorRepository) GetActorWithMetadata(ctx context.Context, username string) (*activitypub.Actor, *storage.ActorMetadata, error)

GetActorWithMetadata retrieves an actor with metadata

func (*ActorRepository) GetCachedRemoteActor

func (r *ActorRepository) GetCachedRemoteActor(ctx context.Context, handle string) (*activitypub.Actor, error)

GetCachedRemoteActor retrieves a cached remote actor by handle

func (*ActorRepository) GetSearchSuggestions

func (r *ActorRepository) GetSearchSuggestions(ctx context.Context, prefix string) ([]storage.SearchSuggestion, error)

GetSearchSuggestions returns search suggestions for autocomplete

func (*ActorRepository) RemoveAccountSuggestion

func (r *ActorRepository) RemoveAccountSuggestion(ctx context.Context, userID, targetID string) error

RemoveAccountSuggestion removes an account from suggestions for a user

func (*ActorRepository) SearchAccounts

func (r *ActorRepository) SearchAccounts(ctx context.Context, query string, limit int, _ bool, _ int) ([]*activitypub.Actor, error)

SearchAccounts searches for actors by username or display name

func (*ActorRepository) SetActorFields

func (r *ActorRepository) SetActorFields(ctx context.Context, username string, fields []storage.ActorField) error

SetActorFields updates the profile fields for an actor

func (*ActorRepository) SetDependencies

func (r *ActorRepository) SetDependencies(deps ActorRepositoryDeps)

SetDependencies sets the dependencies for cross-repository operations

func (*ActorRepository) UpdateActor

func (r *ActorRepository) UpdateActor(ctx context.Context, actor *activitypub.Actor) error

UpdateActor updates an existing actor

func (*ActorRepository) UpdateActorLastStatusTime

func (r *ActorRepository) UpdateActorLastStatusTime(ctx context.Context, username string) error

UpdateActorLastStatusTime updates the last status timestamp

func (*ActorRepository) UpdateAlsoKnownAs

func (r *ActorRepository) UpdateAlsoKnownAs(ctx context.Context, username string, alsoKnownAs []string) error

UpdateAlsoKnownAs updates the AlsoKnownAs field for an actor

func (*ActorRepository) UpdateMovedTo

func (r *ActorRepository) UpdateMovedTo(ctx context.Context, username string, movedTo string) error

UpdateMovedTo updates the MovedTo field for an actor

type ActorRepositoryDeps

type ActorRepositoryDeps interface {
	GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	GetPreference(ctx context.Context, username, key string) (any, error)
	SetPreference(ctx context.Context, username, key string, value any) error
}

ActorRepositoryDeps interface for dependencies - implemented by the storage adapter

type AggregatedQueryConfig

type AggregatedQueryConfig struct {
	PKPrefix    string // PK prefix (e.g., "cost_agg", "metrics_agg")
	LogContext  string // Context for logging (e.g., "cost tracking", "metrics")
	ErrorPrefix string // Error message prefix (e.g., "failed to list aggregated cost tracking")
}

AggregatedQueryConfig configures behavior for aggregated period queries

type AlertRepository

type AlertRepository struct {
	*EnhancedBaseRepository[*models.Alert]
}

AlertRepository provides CRUD operations for alerts using enhanced repository patterns

func NewAlertRepository

func NewAlertRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AlertRepository

NewAlertRepository creates a new alert repository with enhanced functionality

func (*AlertRepository) AcknowledgeAlert

func (r *AlertRepository) AcknowledgeAlert(ctx context.Context, alertID string) error

AcknowledgeAlert marks an alert as acknowledged

func (*AlertRepository) CleanupOldAlerts

func (r *AlertRepository) CleanupOldAlerts(ctx context.Context, olderThan time.Duration) (int, error)

CleanupOldAlerts removes alerts older than the specified duration

func (*AlertRepository) CreateAlert

func (r *AlertRepository) CreateAlert(ctx context.Context, alert *models.Alert) error

CreateAlert creates a new alert

func (*AlertRepository) Delete

func (r *AlertRepository) Delete(ctx context.Context, alertID string) error

Delete deletes an alert

func (*AlertRepository) GetActiveAlerts

func (r *AlertRepository) GetActiveAlerts(ctx context.Context, limit int) ([]*models.Alert, error)

GetActiveAlerts retrieves all currently active (firing) alerts

func (*AlertRepository) GetAlertStats

func (r *AlertRepository) GetAlertStats(ctx context.Context, since time.Time) (*AlertStats, error)

GetAlertStats returns statistics about alerts

func (*AlertRepository) GetAlertsByPriority

func (r *AlertRepository) GetAlertsByPriority(ctx context.Context, status, priority string, since time.Time, limit int) ([]*models.Alert, error)

GetAlertsByPriority retrieves alerts by priority level

func (*AlertRepository) GetAlertsByService

func (r *AlertRepository) GetAlertsByService(ctx context.Context, service string, limit int) ([]*models.Alert, error)

GetAlertsByService retrieves alerts for a specific service

func (*AlertRepository) GetAlertsBySeverity

func (r *AlertRepository) GetAlertsBySeverity(ctx context.Context, service, severity string, since time.Time, limit int) ([]*models.Alert, error)

GetAlertsBySeverity retrieves alerts by severity level

func (*AlertRepository) GetAlertsByType

func (r *AlertRepository) GetAlertsByType(ctx context.Context, alertType string, since time.Time, limit int) ([]*models.Alert, error)

GetAlertsByType retrieves alerts by type within a time range

func (*AlertRepository) GetAlertsNeedingRetry

func (r *AlertRepository) GetAlertsNeedingRetry(ctx context.Context, limit int) ([]*models.Alert, error)

GetAlertsNeedingRetry retrieves alerts that need delivery retry

func (*AlertRepository) GetByID

func (r *AlertRepository) GetByID(ctx context.Context, alertID string) (*models.Alert, error)

GetByID retrieves an alert by its ID

func (*AlertRepository) GetCriticalAlerts

func (r *AlertRepository) GetCriticalAlerts(ctx context.Context, limit int) ([]*models.Alert, error)

GetCriticalAlerts retrieves all critical alerts

func (*AlertRepository) ResolveAlert

func (r *AlertRepository) ResolveAlert(ctx context.Context, alertID string) error

ResolveAlert marks an alert as resolved

func (*AlertRepository) SuppressAlert

func (r *AlertRepository) SuppressAlert(ctx context.Context, alertID string, until time.Time) error

SuppressAlert suppresses an alert until the specified time

func (*AlertRepository) Update

func (r *AlertRepository) Update(ctx context.Context, alert *models.Alert) error

Update updates an existing alert

type AlertStats

type AlertStats struct {
	Period            time.Time      `json:"period"`
	TotalCount        int            `json:"total_count"`
	FiringCount       int            `json:"firing_count"`
	ResolvedCount     int            `json:"resolved_count"`
	AcknowledgedCount int            `json:"acknowledged_count"`
	SuppressedCount   int            `json:"suppressed_count"`
	BySeverity        map[string]int `json:"by_severity"`
	ByType            map[string]int `json:"by_type"`
}

AlertStats represents alert statistics

type AnnouncementRepository

type AnnouncementRepository struct {
	// Use EnhancedBaseRepository for Announcement model
	*EnhancedBaseRepository[*models.Announcement]
	// contains filtered or unexported fields
}

AnnouncementRepository handles announcement operations using enhanced DynamORM patterns

func NewAnnouncementRepository

func NewAnnouncementRepository(db core.DB, tableName string, logger *zap.Logger) *AnnouncementRepository

NewAnnouncementRepository creates a new announcement repository with enhanced functionality

func NewAnnouncementRepositoryWithCostTracking

func NewAnnouncementRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AnnouncementRepository

NewAnnouncementRepositoryWithCostTracking creates a new announcement repository with cost tracking

func (*AnnouncementRepository) AddAnnouncementReaction

func (r *AnnouncementRepository) AddAnnouncementReaction(ctx context.Context, username, announcementID, emojiName string) error

AddAnnouncementReaction adds a user's reaction to an announcement

func (*AnnouncementRepository) CreateAnnouncement

func (r *AnnouncementRepository) CreateAnnouncement(ctx context.Context, announcement *storage.Announcement) error

CreateAnnouncement creates a new announcement

func (*AnnouncementRepository) DeleteAnnouncement

func (r *AnnouncementRepository) DeleteAnnouncement(ctx context.Context, id string) error

DeleteAnnouncement deletes an announcement

func (*AnnouncementRepository) DismissAnnouncement

func (r *AnnouncementRepository) DismissAnnouncement(ctx context.Context, username, announcementID string) error

DismissAnnouncement marks an announcement as dismissed by a user

func (*AnnouncementRepository) GetAnnouncement

func (r *AnnouncementRepository) GetAnnouncement(ctx context.Context, id string) (*storage.Announcement, error)

GetAnnouncement retrieves a single announcement by ID

func (*AnnouncementRepository) GetAnnouncementReactions

func (r *AnnouncementRepository) GetAnnouncementReactions(ctx context.Context, announcementID string) (map[string][]string, error)

GetAnnouncementReactions gets all reactions for an announcement

func (*AnnouncementRepository) GetAnnouncements

func (r *AnnouncementRepository) GetAnnouncements(ctx context.Context, active bool) ([]*storage.Announcement, error)

GetAnnouncements retrieves all announcements (for backward compatibility)

func (*AnnouncementRepository) GetAnnouncementsByAdmin

func (r *AnnouncementRepository) GetAnnouncementsByAdmin(ctx context.Context, adminUsername string, limit int, cursor string) ([]*storage.Announcement, string, error)

GetAnnouncementsByAdmin retrieves announcements created by a specific admin using GSI2

func (*AnnouncementRepository) GetAnnouncementsPaginated

func (r *AnnouncementRepository) GetAnnouncementsPaginated(ctx context.Context, active bool, limit int, cursor string) ([]*storage.Announcement, string, error)

GetAnnouncementsPaginated retrieves announcements with pagination using optimized GSI queries

func (*AnnouncementRepository) GetDismissedAnnouncements

func (r *AnnouncementRepository) GetDismissedAnnouncements(ctx context.Context, username string) ([]string, error)

GetDismissedAnnouncements gets all announcement IDs dismissed by a user

func (*AnnouncementRepository) IsDismissed

func (r *AnnouncementRepository) IsDismissed(ctx context.Context, username, announcementID string) (bool, error)

IsDismissed checks if a user has dismissed an announcement

func (*AnnouncementRepository) RemoveAnnouncementReaction

func (r *AnnouncementRepository) RemoveAnnouncementReaction(ctx context.Context, username, announcementID, emojiName string) error

RemoveAnnouncementReaction removes a user's reaction from an announcement

func (*AnnouncementRepository) UpdateAnnouncement

func (r *AnnouncementRepository) UpdateAnnouncement(ctx context.Context, announcement *storage.Announcement) error

UpdateAnnouncement updates an existing announcement

type ArticleRepository

type ArticleRepository struct {
	*EnhancedBaseRepository[*models.Article]
}

ArticleRepository implements article operations using DynamORM with EnhancedBaseRepository

func NewArticleRepository

func NewArticleRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ArticleRepository

NewArticleRepository creates a new article repository

func (*ArticleRepository) CreateArticle

func (r *ArticleRepository) CreateArticle(ctx context.Context, article *models.Article) error

CreateArticle creates a new article

func (*ArticleRepository) DeleteArticle

func (r *ArticleRepository) DeleteArticle(ctx context.Context, id string) error

DeleteArticle deletes an article

func (*ArticleRepository) GetArticle

func (r *ArticleRepository) GetArticle(ctx context.Context, id string) (*models.Article, error)

GetArticle retrieves an article by ID

func (*ArticleRepository) ListArticles

func (r *ArticleRepository) ListArticles(ctx context.Context, limit int) ([]*models.Article, error)

ListArticles lists articles with pagination

func (*ArticleRepository) ListArticlesByAuthorPaginated

func (r *ArticleRepository) ListArticlesByAuthorPaginated(ctx context.Context, authorActorID string, limit int, cursor string) ([]*models.Article, string, error)

ListArticlesByAuthorPaginated lists articles for a specific author (actor ID) ordered by published time (newest first). Cursor values are CMS index SK values.

func (*ArticleRepository) ListArticlesByCategoryPaginated

func (r *ArticleRepository) ListArticlesByCategoryPaginated(ctx context.Context, categoryID string, limit int, cursor string) ([]*models.Article, string, error)

ListArticlesByCategoryPaginated lists articles for a specific category ordered by published time (newest first). Cursor values are CMS index SK values.

func (*ArticleRepository) ListArticlesBySeriesPaginated

func (r *ArticleRepository) ListArticlesBySeriesPaginated(ctx context.Context, seriesID string, limit int, cursor string) ([]*models.Article, string, error)

ListArticlesBySeriesPaginated lists articles for a specific series (GraphQL series ID) ordered by published time (newest first). Cursor values are CMS index SK values.

func (*ArticleRepository) ListArticlesPaginated

func (r *ArticleRepository) ListArticlesPaginated(ctx context.Context, limit int, cursor string) ([]*models.Article, string, error)

ListArticlesPaginated lists articles ordered by published time (newest first). Cursor values are gsi2SK values.

func (*ArticleRepository) UpdateArticle

func (r *ArticleRepository) UpdateArticle(ctx context.Context, article *models.Article) error

UpdateArticle updates an existing article

type AuditLogConversionConfig

type AuditLogConversionConfig struct {
	GSIField   string // GSI field for cursor (e.g., "gsi1SK", "gsi2SK")
	LogContext string // Context for logging
}

AuditLogConversionConfig configures audit log model to storage type conversion

type AuditRepository

type AuditRepository struct {
	*EnhancedBaseRepository[*models.AuthAuditLog]
}

AuditRepository handles audit log storage operations with enhanced security features

func NewAuditRepository

func NewAuditRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AuditRepository

NewAuditRepository creates a new audit repository with enhanced security features

func (*AuditRepository) CleanupOldLogs

func (r *AuditRepository) CleanupOldLogs(ctx context.Context, retentionDays int) error

CleanupOldLogs removes audit logs older than retention period - COMPLIANCE CRITICAL Note: This is for manual cleanup when TTL is not sufficient for compliance requirements

func (*AuditRepository) GetAuditLogByID

func (r *AuditRepository) GetAuditLogByID(ctx context.Context, id string, date time.Time) (*models.AuthAuditLog, error)

GetAuditLogByID retrieves an audit log by ID and date - SECURITY CRITICAL

func (*AuditRepository) GetIPAuditLogs

func (r *AuditRepository) GetIPAuditLogs(ctx context.Context, ipAddress string, limit int, startTime, endTime time.Time) ([]*models.AuthAuditLog, error)

GetIPAuditLogs retrieves audit logs for a specific IP address - SECURITY CRITICAL

func (*AuditRepository) GetRecentFailedLogins

func (r *AuditRepository) GetRecentFailedLogins(ctx context.Context, username string, duration time.Duration) (int, error)

GetRecentFailedLogins gets recent failed login attempts for a user

func (*AuditRepository) GetRecentIPFailures

func (r *AuditRepository) GetRecentIPFailures(ctx context.Context, ipAddress string, duration time.Duration) (int, error)

GetRecentIPFailures gets recent failures from an IP address

func (*AuditRepository) GetSecurityEvents

func (r *AuditRepository) GetSecurityEvents(ctx context.Context, severity string, startTime, endTime time.Time, limit int, cursor string) ([]*models.AuthAuditLog, string, error)

GetSecurityEvents retrieves security events by severity within a time range - SECURITY CRITICAL

func (*AuditRepository) GetSessionAuditLogs

func (r *AuditRepository) GetSessionAuditLogs(ctx context.Context, sessionID string) ([]*models.AuthAuditLog, error)

GetSessionAuditLogs retrieves audit logs for a specific session - SECURITY CRITICAL

func (*AuditRepository) GetUserAuditLogs

func (r *AuditRepository) GetUserAuditLogs(ctx context.Context, username string, limit int, startTime, endTime time.Time) ([]*models.AuthAuditLog, error)

GetUserAuditLogs retrieves audit logs for a specific user - SECURITY CRITICAL

func (*AuditRepository) StoreAuditEvent

func (r *AuditRepository) StoreAuditEvent(ctx context.Context, eventType, severity, username, userID, ipAddress, userAgent, deviceName, sessionID, requestID string, success bool, failureReason string, metadata map[string]interface{}) error

StoreAuditEvent stores an audit event with full metadata

func (*AuditRepository) StoreAuditLog

func (r *AuditRepository) StoreAuditLog(ctx context.Context, log *models.AuthAuditLog) error

StoreAuditLog stores an audit log entry - SECURITY CRITICAL

type AuthRefreshTokenRepository

type AuthRefreshTokenRepository struct {
	*EnhancedBaseRepository[*models.AuthRefreshToken]
}

AuthRefreshTokenRepository handles auth refresh tokens with enhanced security features

func NewAuthRefreshTokenRepository

func NewAuthRefreshTokenRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AuthRefreshTokenRepository

NewAuthRefreshTokenRepository creates a new auth refresh token repository with enhanced security

func (*AuthRefreshTokenRepository) CreateRefreshToken

func (r *AuthRefreshTokenRepository) CreateRefreshToken(ctx context.Context, userID string, deviceName string, ipAddress string) (*models.AuthRefreshToken, error)

CreateRefreshToken generates and stores a new refresh token

func (*AuthRefreshTokenRepository) GetRefreshToken

func (r *AuthRefreshTokenRepository) GetRefreshToken(ctx context.Context, token string) (*models.AuthRefreshToken, error)

GetRefreshToken retrieves a refresh token by token value

func (*AuthRefreshTokenRepository) GetTokensByFamily

func (r *AuthRefreshTokenRepository) GetTokensByFamily(ctx context.Context, family string) ([]models.AuthRefreshToken, error)

GetTokensByFamily retrieves all tokens in a family

func (*AuthRefreshTokenRepository) GetTokensByUser

func (r *AuthRefreshTokenRepository) GetTokensByUser(ctx context.Context, userID string) ([]models.AuthRefreshToken, error)

GetTokensByUser retrieves all active tokens for a user

func (*AuthRefreshTokenRepository) RevokeTokenFamily

func (r *AuthRefreshTokenRepository) RevokeTokenFamily(ctx context.Context, family string, reason string) error

RevokeTokenFamily revokes all tokens in a family (security breach response)

func (*AuthRefreshTokenRepository) RevokeUserTokens

func (r *AuthRefreshTokenRepository) RevokeUserTokens(ctx context.Context, userID string, reason string) error

RevokeUserTokens revokes all tokens for a user (logout all devices)

func (*AuthRefreshTokenRepository) RotateRefreshToken

func (r *AuthRefreshTokenRepository) RotateRefreshToken(ctx context.Context, oldTokenValue string, ipAddress string) (*models.AuthRefreshToken, error)

RotateRefreshToken implements secure rotation with reuse detection

type AuthRepository

type AuthRepository struct {
	*EnhancedBaseRepository[*models.WebAuthnCredential]
	// contains filtered or unexported fields
}

AuthRepository handles authentication-related storage operations using enhanced patterns

func NewAuthRepository

func NewAuthRepository(db core.DB, tableName string, logger *zap.Logger) *AuthRepository

NewAuthRepository creates a new auth repository with enhanced functionality

func NewAuthRepositoryWithCostTracking

func NewAuthRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *AuthRepository

NewAuthRepositoryWithCostTracking creates a new auth repository with cost tracking

func (*AuthRepository) CreateWebAuthnChallenge

func (r *AuthRepository) CreateWebAuthnChallenge(ctx context.Context, challenge *storage.WebAuthnChallenge) error

CreateWebAuthnChallenge stores a temporary WebAuthn challenge

func (*AuthRepository) CreateWebAuthnCredential

func (r *AuthRepository) CreateWebAuthnCredential(ctx context.Context, credential *storage.WebAuthnCredential) error

CreateWebAuthnCredential creates a new WebAuthn credential

func (*AuthRepository) DeleteWalletChallenge

func (r *AuthRepository) DeleteWalletChallenge(ctx context.Context, challengeID string) error

DeleteWalletChallenge deletes a wallet challenge

func (*AuthRepository) DeleteWalletCredential

func (r *AuthRepository) DeleteWalletCredential(ctx context.Context, username, address string) error

DeleteWalletCredential deletes a wallet credential

func (*AuthRepository) DeleteWebAuthnChallenge

func (r *AuthRepository) DeleteWebAuthnChallenge(ctx context.Context, challengeID string) error

DeleteWebAuthnChallenge deletes a WebAuthn challenge

func (*AuthRepository) DeleteWebAuthnCredential

func (r *AuthRepository) DeleteWebAuthnCredential(ctx context.Context, credentialID string) error

DeleteWebAuthnCredential deletes a WebAuthn credential

func (*AuthRepository) GetUserWallets

func (r *AuthRepository) GetUserWallets(ctx context.Context, username string) ([]*storage.WalletCredential, error)

GetUserWallets retrieves all wallet credentials for a user

func (*AuthRepository) GetUserWebAuthnCredentials

func (r *AuthRepository) GetUserWebAuthnCredentials(ctx context.Context, userID string) ([]*storage.WebAuthnCredential, error)

GetUserWebAuthnCredentials retrieves all WebAuthn credentials for a user

func (*AuthRepository) GetWalletByAddress

func (r *AuthRepository) GetWalletByAddress(ctx context.Context, walletType, address string) (*storage.WalletCredential, error)

GetWalletByAddress retrieves wallet credentials by address

func (*AuthRepository) GetWalletChallenge

func (r *AuthRepository) GetWalletChallenge(ctx context.Context, challengeID string) (*storage.WalletChallenge, error)

GetWalletChallenge retrieves a wallet challenge by ID

func (*AuthRepository) GetWebAuthnChallenge

func (r *AuthRepository) GetWebAuthnChallenge(ctx context.Context, challengeID string) (*storage.WebAuthnChallenge, error)

GetWebAuthnChallenge retrieves a WebAuthn challenge

func (*AuthRepository) GetWebAuthnCredential

func (r *AuthRepository) GetWebAuthnCredential(ctx context.Context, credentialID string) (*storage.WebAuthnCredential, error)

GetWebAuthnCredential retrieves a WebAuthn credential by ID

func (*AuthRepository) StoreWalletChallenge

func (r *AuthRepository) StoreWalletChallenge(ctx context.Context, challenge *storage.WalletChallenge) error

StoreWalletChallenge stores a temporary wallet authentication challenge

func (*AuthRepository) StoreWalletCredential

func (r *AuthRepository) StoreWalletCredential(ctx context.Context, credential *storage.WalletCredential) error

StoreWalletCredential stores a wallet credential linked to a user

func (*AuthRepository) UpdateWebAuthnLastUsed

func (r *AuthRepository) UpdateWebAuthnLastUsed(ctx context.Context, credentialID string, signCount uint32) error

UpdateWebAuthnLastUsed updates the last used timestamp and sign count

type BaseModel

type BaseModel interface {
	UpdateKeys() error
	GetPK() string
	GetSK() string
}

BaseModel interface that all DynamoDB models must implement

type BasePaginatedResult

type BasePaginatedResult[T BaseModel] struct {
	Items      []T    // The retrieved items
	NextCursor string // Cursor for next page (empty if no more pages)
	HasMore    bool   // Whether there are more pages available
}

BasePaginatedResult contains paginated query results from BaseRepository

type BasePaginationOptions

type BasePaginationOptions struct {
	Limit  int    // Maximum number of items to return
	Cursor string // Pagination cursor for next page
	Order  string // Sort order: SortOrderAsc or SortOrderDesc
}

BasePaginationOptions configures pagination behavior for BaseRepository

type BaseRepository

type BaseRepository[T BaseModel] struct {
	// contains filtered or unexported fields
}

BaseRepository provides common CRUD operations for all repositories with integrated cost tracking

func NewBaseRepository

func NewBaseRepository[T BaseModel](db core.DB, tableName string, logger *zap.Logger) *BaseRepository[T]

NewBaseRepository creates a new base repository

func NewBaseRepositoryWithCostTracking

func NewBaseRepositoryWithCostTracking[T BaseModel](db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService, repoName string) *BaseRepository[T]

NewBaseRepositoryWithCostTracking creates a new base repository with integrated cost tracking

func (*BaseRepository[T]) BatchCreate

func (r *BaseRepository[T]) BatchCreate(ctx context.Context, items []T) error

BatchCreate creates multiple items efficiently using DynamoDB batch operations

func (*BaseRepository[T]) BatchCreateHelper

func (r *BaseRepository[T]) BatchCreateHelper(ctx context.Context, items []T, entityType string) error

BatchCreateHelper performs batch creation for any model type with common validation and logging

func (*BaseRepository[T]) BatchDelete

func (r *BaseRepository[T]) BatchDelete(ctx context.Context, keys []struct{ PK, SK string }) error

BatchDelete removes multiple items efficiently using DynamoDB batch operations

func (*BaseRepository[T]) BatchGet

func (r *BaseRepository[T]) BatchGet(ctx context.Context, keys []struct{ PK, SK string }) ([]T, error)

BatchGet retrieves multiple items by their keys

func (*BaseRepository[T]) BatchGetItems

func (r *BaseRepository[T]) BatchGetItems(ctx context.Context, keys []map[string]interface{}) ([]T, error)

BatchGetItems retrieves multiple items by their keys in a single batch operation

func (*BaseRepository[T]) BatchWriteItems

func (r *BaseRepository[T]) BatchWriteItems(ctx context.Context, items []T) error

BatchWriteItems writes multiple items in a single batch operation

func (*BaseRepository[T]) Count

func (r *BaseRepository[T]) Count(ctx context.Context, pk string) (int, error)

Count returns the number of items for a given partition key

func (*BaseRepository[T]) Create

func (r *BaseRepository[T]) Create(ctx context.Context, item T) error

Create stores a new item in the database

func (*BaseRepository[T]) CreateIfNotExists

func (r *BaseRepository[T]) CreateIfNotExists(ctx context.Context, item T) error

CreateIfNotExists stores a new item in the database only if its primary key does not already exist.

func (*BaseRepository[T]) Delete

func (r *BaseRepository[T]) Delete(ctx context.Context, pk, sk string) error

Delete removes an item from the database

func (*BaseRepository[T]) Exists

func (r *BaseRepository[T]) Exists(ctx context.Context, pk, sk string) (bool, error)

Exists checks if an item exists

func (*BaseRepository[T]) FindByPK

func (r *BaseRepository[T]) FindByPK(ctx context.Context, pk string) ([]T, error)

FindByPK retrieves all items with a specific partition key

func (*BaseRepository[T]) FindBySK

func (r *BaseRepository[T]) FindBySK(ctx context.Context, sk string, gsiName string) ([]T, error)

FindBySK retrieves all items with a specific sort key (across all partitions) Note: This requires a GSI with SK as the partition key

func (*BaseRepository[T]) FindWithPagination

func (r *BaseRepository[T]) FindWithPagination(ctx context.Context, pk string, opts BasePaginationOptions) (*BasePaginatedResult[T], error)

FindWithPagination performs paginated queries with cursor support

func (*BaseRepository[T]) Get

func (r *BaseRepository[T]) Get(ctx context.Context, pk, sk string, result T) error

Get retrieves a single item by primary and sort key

func (*BaseRepository[T]) GetCostService

func (r *BaseRepository[T]) GetCostService() *cost.TrackingService

GetCostService returns the cost tracking service for direct access if needed

func (*BaseRepository[T]) GetDB

func (r *BaseRepository[T]) GetDB() core.DB

GetDB returns the underlying database connection for complex queries that can't use BaseRepository methods

func (*BaseRepository[T]) Query

func (r *BaseRepository[T]) Query(ctx context.Context, pk string, limit int) ([]T, error)

Query performs a query operation on a partition key

func (*BaseRepository[T]) QueryBetween

func (r *BaseRepository[T]) QueryBetween(ctx context.Context, pk, startSK, endSK string, limit int) ([]T, error)

QueryBetween performs range queries between two sort key values

func (*BaseRepository[T]) QueryBetweenPaginated

func (r *BaseRepository[T]) QueryBetweenPaginated(ctx context.Context, pk, startSK, endSK string, opts BasePaginationOptions) (*BasePaginatedResult[T], error)

QueryBetweenPaginated performs range queries with cursor support.

func (*BaseRepository[T]) QueryGSI

func (r *BaseRepository[T]) QueryGSI(ctx context.Context, indexName, pk string, limit int) ([]T, error)

QueryGSI performs a query on a Global Secondary Index

func (*BaseRepository[T]) QueryGSIPaginated

func (r *BaseRepository[T]) QueryGSIPaginated(ctx context.Context, indexName, pk string, opts BasePaginationOptions) (*BasePaginatedResult[T], error)

QueryGSIPaginated performs a GSI query with cursor and ordering support.

func (*BaseRepository[T]) QueryGSIWithTimeRangeHelper

func (r *BaseRepository[T]) QueryGSIWithTimeRangeHelper(ctx context.Context, indexName, gsiPK, gsiSK, pkValue string, startTime, endTime time.Time, limit int, cursor string, order string, operationName string) ([]T, string, error)

QueryGSIWithTimeRangeHelper provides common GSI query pattern with time range filtering

func (*BaseRepository[T]) QueryWithFilter

func (r *BaseRepository[T]) QueryWithFilter(ctx context.Context, pk string, filters map[string]interface{}, limit int) ([]T, error)

QueryWithFilter performs queries with additional filter conditions

func (*BaseRepository[T]) QueryWithSKPrefix

func (r *BaseRepository[T]) QueryWithSKPrefix(ctx context.Context, pk, skPrefix string, limit int) ([]T, error)

QueryWithSKPrefix performs a query with a sort key prefix

func (*BaseRepository[T]) QueryWithSKPrefixPaginated

func (r *BaseRepository[T]) QueryWithSKPrefixPaginated(ctx context.Context, pk, skPrefix string, opts BasePaginationOptions) (*BasePaginatedResult[T], error)

QueryWithSKPrefixPaginated performs a prefix query with cursor support.

func (*BaseRepository[T]) SetCostService

func (r *BaseRepository[T]) SetCostService(costService *cost.TrackingService)

SetCostService allows setting or updating the cost service after repository creation

func (*BaseRepository[T]) SetRepoName

func (r *BaseRepository[T]) SetRepoName(repoName string)

SetRepoName allows setting the repository name for better cost tracking identification

func (*BaseRepository[T]) TrackCustomOperation

func (r *BaseRepository[T]) TrackCustomOperation(ctx context.Context, operation cost.DynamoOperation) error

TrackCustomOperation provides a way to track custom operations with specific parameters

func (*BaseRepository[T]) TrackRead

func (r *BaseRepository[T]) TrackRead(ctx context.Context, operationType string, readUnits int64) error

TrackRead provides a simple way to track read operations

func (*BaseRepository[T]) TrackWrite

func (r *BaseRepository[T]) TrackWrite(ctx context.Context, operationType string, writeUnits int64) error

TrackWrite provides a simple way to track write operations

func (*BaseRepository[T]) TransactWrite

func (r *BaseRepository[T]) TransactWrite(ctx context.Context, items []T) error

TransactWrite performs a transaction with multiple write operations

func (*BaseRepository[T]) Update

func (r *BaseRepository[T]) Update(ctx context.Context, item T) error

Update updates an existing item Note: In DynamORM, you need to update the model fields before calling Update() This method is provided for consistency but may need adaptation per repository

type BatchDeleteConfig

type BatchDeleteConfig struct {
	ModelType   string // "hashtag_trend", "trending_hashtag", "hashtag_usage"
	ErrorPrefix string // Error message prefix
	BatchSize   int    // Batch size for deletion
	QueryLimit  int    // Limit for initial query
	FilterField string // Field to filter on (e.g., "UpdatedAt", "UsedAt")
}

BatchDeleteConfig holds configuration for batch deletion operations

type BatchOperationHelper

type BatchOperationHelper struct {
	// contains filtered or unexported fields
}

BatchOperationHelper provides common batch operation patterns

func NewBatchOperationHelper

func NewBatchOperationHelper(db core.DB, tableName string, logger *zap.Logger) *BatchOperationHelper

NewBatchOperationHelper creates a new batch operation helper

func (*BatchOperationHelper) BatchCreateItems

func (h *BatchOperationHelper) BatchCreateItems(ctx context.Context, items []interface{}, itemType string) error

BatchCreateItems creates multiple items efficiently using common patterns

type BlockRepository

type BlockRepository struct {
	*EnhancedBaseRepository[*models.Block]
	// contains filtered or unexported fields
}

BlockRepository implements block operations using enhanced DynamORM patterns

func NewBlockRepository

func NewBlockRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *BlockRepository

NewBlockRepository creates a new block repository with enhanced functionality

func (*BlockRepository) CountBlockedUsers

func (r *BlockRepository) CountBlockedUsers(ctx context.Context, blockerActor string) (int, error)

CountBlockedUsers returns the number of users blocked by the given actor

func (*BlockRepository) CountUsersWhoBlocked

func (r *BlockRepository) CountUsersWhoBlocked(ctx context.Context, blockedActor string) (int, error)

CountUsersWhoBlocked returns the number of users who have blocked the given actor

func (*BlockRepository) CreateBlock

func (r *BlockRepository) CreateBlock(ctx context.Context, blockerActor, blockedActor, activityID string) error

CreateBlock creates a new block relationship

func (*BlockRepository) DeleteBlock

func (r *BlockRepository) DeleteBlock(ctx context.Context, blockerActor, blockedActor string) error

DeleteBlock removes a block relationship (for Undo Block)

func (*BlockRepository) GetBlock

func (r *BlockRepository) GetBlock(ctx context.Context, blockerActor, blockedActor string) (*storage.Block, error)

GetBlock retrieves a specific block relationship

func (*BlockRepository) GetBlockedUsers

func (r *BlockRepository) GetBlockedUsers(ctx context.Context, blockerActor string, limit int, cursor string) ([]string, string, error)

GetBlockedUsers returns a list of users blocked by the given actor

func (*BlockRepository) GetUsersWhoBlocked

func (r *BlockRepository) GetUsersWhoBlocked(ctx context.Context, blockedActor string, limit int, cursor string) ([]string, string, error)

GetUsersWhoBlocked returns a list of users who have blocked the given actor

func (*BlockRepository) IsBlocked

func (r *BlockRepository) IsBlocked(ctx context.Context, blockerActor, blockedActor string) (bool, error)

IsBlocked checks if one actor has blocked another

func (*BlockRepository) IsBlockedBidirectional

func (r *BlockRepository) IsBlockedBidirectional(ctx context.Context, actor1, actor2 string) (bool, error)

IsBlockedBidirectional checks if either actor has blocked the other

type BookmarkRepository

type BookmarkRepository struct {
	*EnhancedBaseRepository[*models.Bookmark]
	// contains filtered or unexported fields
}

BookmarkRepository implements bookmark operations using enhanced DynamORM patterns

func NewBookmarkRepository

func NewBookmarkRepository(db core.DB, tableName string, logger *zap.Logger) *BookmarkRepository

NewBookmarkRepository creates a new bookmark repository with enhanced functionality

func NewBookmarkRepositoryWithCostTracking

func NewBookmarkRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *BookmarkRepository

NewBookmarkRepositoryWithCostTracking creates a new bookmark repository with cost tracking

func (*BookmarkRepository) AddBookmark

func (r *BookmarkRepository) AddBookmark(ctx context.Context, username, objectID string) error

AddBookmark provides Storage interface compatibility

func (*BookmarkRepository) CascadeDeleteObjectBookmarks

func (r *BookmarkRepository) CascadeDeleteObjectBookmarks(ctx context.Context, objectID string) error

CascadeDeleteObjectBookmarks deletes all bookmarks for an object (when object is deleted)

func (*BookmarkRepository) CascadeDeleteUserBookmarks

func (r *BookmarkRepository) CascadeDeleteUserBookmarks(ctx context.Context, username string) error

CascadeDeleteUserBookmarks deletes all bookmarks for a user

func (*BookmarkRepository) CheckBookmarksForStatuses

func (r *BookmarkRepository) CheckBookmarksForStatuses(ctx context.Context, username string, statusIDs []string) (map[string]bool, error)

CheckBookmarksForStatuses returns a map of statusID -> bookmarked for the provided IDs.

func (*BookmarkRepository) CountUserBookmarks

func (r *BookmarkRepository) CountUserBookmarks(ctx context.Context, username string) (int64, error)

CountUserBookmarks returns the total number of bookmarks by a user

func (*BookmarkRepository) CreateBookmark

func (r *BookmarkRepository) CreateBookmark(ctx context.Context, username, objectID string) (*models.Bookmark, error)

CreateBookmark creates a new bookmark using the TIME/OBJECT dual-write pattern.

func (*BookmarkRepository) DeleteBookmark

func (r *BookmarkRepository) DeleteBookmark(ctx context.Context, username, objectID string) error

DeleteBookmark removes both the OBJECT and TIME bookmark records.

func (*BookmarkRepository) GetBookmark

func (r *BookmarkRepository) GetBookmark(ctx context.Context, username, objectID string) (*models.Bookmark, error)

GetBookmark retrieves a specific bookmark

func (*BookmarkRepository) GetBookmarks

func (r *BookmarkRepository) GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*storage.Bookmark, string, error)

GetBookmarks provides Storage interface compatibility - returns storage.Bookmark format

func (*BookmarkRepository) GetUserBookmarks

func (r *BookmarkRepository) GetUserBookmarks(ctx context.Context, username string, limit int, cursor string) ([]*models.Bookmark, string, error)

GetUserBookmarks retrieves all bookmarks for a user with pagination

func (*BookmarkRepository) IsBookmarked

func (r *BookmarkRepository) IsBookmarked(ctx context.Context, username, objectID string) (bool, error)

IsBookmarked checks if a user has bookmarked an object

func (*BookmarkRepository) RemoveBookmark

func (r *BookmarkRepository) RemoveBookmark(ctx context.Context, username, objectID string) error

RemoveBookmark provides Storage interface compatibility

type BudgetCheckResult

type BudgetCheckResult struct {
	Allowed               bool    `json:"allowed"`
	ShouldRateLimit       bool    `json:"should_rate_limit"`
	WarningLevel          string  `json:"warning_level"` // info, warning, error
	Message               string  `json:"message"`
	CurrentUsage          int64   `json:"current_usage"`
	LimitAmount           int64   `json:"limit_amount"`
	LimitPercent          float64 `json:"limit_percent"`
	ProjectedUsagePercent float64 `json:"projected_usage_percent"`
}

BudgetCheckResult represents the result of a budget check

type BudgetPeriodStatus

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

BudgetPeriodStatus represents budget status for a specific period

type BudgetStatus

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

BudgetStatus represents current budget status for a user

type BudgetSummary

type BudgetSummary struct {
	Budget             *models.SearchBudget `json:"budget"`
	CostSummary        *SearchCostSummary   `json:"cost_summary"`
	UtilizationPercent float64              `json:"utilization_percent"`
	Status             string               `json:"status"`
	Recommendations    []string             `json:"recommendations"`
}

BudgetSummary contains budget usage statistics for search operations

type CSRFRepository

type CSRFRepository struct {
	*EnhancedBaseRepository[*models.CSRFToken]
	// contains filtered or unexported fields
}

CSRFRepository handles CSRF token operations using enhanced security patterns

func NewCSRFRepository

func NewCSRFRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *CSRFRepository

NewCSRFRepository creates a new CSRFRepository with enhanced security features

func (*CSRFRepository) CleanExpired

func (r *CSRFRepository) CleanExpired(_ context.Context) error

CleanExpired removes expired tokens - interface compatibility (DynamoDB TTL handles this automatically)

func (*CSRFRepository) CleanupUserTokens

func (r *CSRFRepository) CleanupUserTokens(ctx context.Context, userID string) error

CleanupUserTokens removes old/used tokens for a user - CSRF PROTECTION: prevents token accumulation DoS

func (*CSRFRepository) Delete

func (r *CSRFRepository) Delete(ctx context.Context, token string) error

Delete removes a CSRF token - uses BaseRepository

func (*CSRFRepository) Get

func (r *CSRFRepository) Get(ctx context.Context, token string) (string, string, time.Time, bool, error)

Get retrieves a CSRF token - CSRF PROTECTION: preserves exact legacy validation logic

func (*CSRFRepository) GetUserActiveTokenCount

func (r *CSRFRepository) GetUserActiveTokenCount(ctx context.Context, userID string) (int, error)

GetUserActiveTokenCount returns the number of active tokens for a user - CSRF PROTECTION: DoS prevention

func (*CSRFRepository) Store

func (r *CSRFRepository) Store(ctx context.Context, token string, userID string, expiresAt time.Time) error

Store saves a CSRF token with expiration - CSRF PROTECTION: preserves exact legacy behavior

func (*CSRFRepository) ValidateAndConsume

func (r *CSRFRepository) ValidateAndConsume(ctx context.Context, token string, userID string) error

ValidateAndConsume validates a token and marks it as used atomically - CSRF PROTECTION: critical validation logic preserved

type CachedHashtagMetrics

type CachedHashtagMetrics struct {
	Metrics     *EnhancedHashtagMetrics `json:"metrics"`
	GeneratedAt time.Time               `json:"generated_at"`
	ValidUntil  time.Time               `json:"valid_until"`
}

CachedHashtagMetrics represents cached metrics for a hashtag

type CachedTrendingResult

type CachedTrendingResult struct {
	Results     []*storage.TrendingHashtag `json:"results"`
	GeneratedAt time.Time                  `json:"generated_at"`
	Parameters  map[string]interface{}     `json:"parameters"`
	HitCount    int64                      `json:"hit_count"`
}

CachedTrendingResult represents a cached trending calculation result

type CachingService

type CachingService interface {
	Get(ctx context.Context, key string, dest interface{}) error
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	InvalidatePattern(ctx context.Context, pattern string) error
}

CachingService provides repository-level caching

type CategoryRepository

type CategoryRepository struct {
	*EnhancedBaseRepository[*models.Category]
}

CategoryRepository implements category operations

func NewCategoryRepository

func NewCategoryRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *CategoryRepository

NewCategoryRepository creates a new category repository

func (*CategoryRepository) CreateCategory

func (r *CategoryRepository) CreateCategory(ctx context.Context, category *models.Category) error

CreateCategory creates a new category

func (*CategoryRepository) GetCategory

func (r *CategoryRepository) GetCategory(ctx context.Context, id string) (*models.Category, error)

GetCategory retrieves a category by ID

func (*CategoryRepository) ListCategories

func (r *CategoryRepository) ListCategories(ctx context.Context, parentID *string, limit int) ([]*models.Category, error)

ListCategories lists all categories (optionally filtered by parent)

func (*CategoryRepository) UpdateArticleCount

func (r *CategoryRepository) UpdateArticleCount(ctx context.Context, categoryID string, delta int) error

UpdateArticleCount atomically increments/decrements a category's ArticleCount. Missing categories are treated as a no-op to avoid breaking writes when legacy/stale IDs exist.

type CategorySummaryStats

type CategorySummaryStats struct {
	Category                string
	ExecutionCount          int64
	SuccessfulExecutions    int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostPerExecution float64
	SuccessRate             float64
}

CategorySummaryStats represents summary statistics for a category

type ChallengeModel

type ChallengeModel interface {
	UpdateKeys() error
}

ChallengeModel interface for any model that has UpdateKeys and can be used in challenge operations

type CircuitBreakerRepository

type CircuitBreakerRepository struct {
	*EnhancedBaseRepository[*models.CircuitBreakerState]
	// contains filtered or unexported fields
}

CircuitBreakerRepository handles circuit breaker state persistence with enhanced patterns

func NewCircuitBreakerRepository

func NewCircuitBreakerRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *CircuitBreakerRepository

NewCircuitBreakerRepository creates a new circuit breaker repository with enhanced functionality

func NewCircuitBreakerRepositoryBasic

func NewCircuitBreakerRepositoryBasic(db core.DB, tableName string, logger *zap.Logger) *CircuitBreakerRepository

NewCircuitBreakerRepositoryBasic creates a new circuit breaker repository without cost tracking (backward compatibility)

func (*CircuitBreakerRepository) DeleteCircuitState

func (r *CircuitBreakerRepository) DeleteCircuitState(ctx context.Context, instanceID string) error

DeleteCircuitState removes circuit state for an instance (for cleanup)

func (*CircuitBreakerRepository) GetAllCircuitStates

func (r *CircuitBreakerRepository) GetAllCircuitStates(ctx context.Context) ([]*models.CircuitBreakerState, error)

GetAllCircuitStates retrieves all circuit states (for monitoring/debugging)

func (*CircuitBreakerRepository) GetCircuitState

func (r *CircuitBreakerRepository) GetCircuitState(ctx context.Context, instanceID string) (*models.CircuitBreakerState, error)

GetCircuitState retrieves the current state of a circuit breaker for an instance CIRCUIT BREAKER RESILIENCE: Returns default closed state if not found - critical for system stability

func (*CircuitBreakerRepository) GetRecentEvents

func (r *CircuitBreakerRepository) GetRecentEvents(ctx context.Context, instanceID string, limit int) ([]*models.CircuitBreakerEvent, error)

GetRecentEvents retrieves recent events for an instance (for debugging)

func (*CircuitBreakerRepository) RecordEvent

RecordEvent records a circuit breaker event for debugging and monitoring CIRCUIT BREAKER RESILIENCE: Non-blocking event recording for debugging/monitoring

func (*CircuitBreakerRepository) RecordMetric

func (r *CircuitBreakerRepository) RecordMetric(ctx context.Context, instanceID string, success bool, err error, errorType string) error

RecordMetric is a convenience method to record success/failure metrics

func (*CircuitBreakerRepository) RecordStateChange

func (r *CircuitBreakerRepository) RecordStateChange(ctx context.Context, instanceID, oldStatus, newStatus, reason string) error

RecordStateChange is a convenience method to record state change events

func (*CircuitBreakerRepository) SaveCircuitState

func (r *CircuitBreakerRepository) SaveCircuitState(ctx context.Context, state *models.CircuitBreakerState) error

SaveCircuitState saves the circuit breaker state atomically CIRCUIT BREAKER RESILIENCE: Maintains atomic create/update semantics to prevent race conditions

func (*CircuitBreakerRepository) UpdateCircuitState

func (r *CircuitBreakerRepository) UpdateCircuitState(ctx context.Context, instanceID string, updateFn func(*models.CircuitBreakerState) error) (*models.CircuitBreakerState, error)

UpdateCircuitState updates an existing circuit state atomically

type CloudWatchMetrics

type CloudWatchMetrics struct {
	MetricName string
	Value      float64
	Unit       string
	Timestamp  time.Time
	Dimensions map[string]string
}

CloudWatchMetrics represents metrics data from CloudWatch (PRESERVED - AWS monitoring integration)

type CloudWatchMetricsRepository

type CloudWatchMetricsRepository struct {
	*EnhancedBaseRepository[*models.CloudWatchMetrics] // Optional caching layer
	// contains filtered or unexported fields
}

CloudWatchMetricsRepository handles querying CloudWatch metrics with optional DynamoDB caching NOTE: This repository primarily uses CloudWatch AWS SDK for metrics collection. BaseRepository integration demonstrates how DynamoDB caching could be added for performance optimization.

func NewCloudWatchMetricsRepository

func NewCloudWatchMetricsRepository(namespace, environment string, logger *zap.Logger) *CloudWatchMetricsRepository

NewCloudWatchMetricsRepository creates a new CloudWatch metrics repository PRESERVE: All CloudWatch functionality - no DynamoDB operations to replace

func NewCloudWatchMetricsRepositoryWithCaching

func NewCloudWatchMetricsRepositoryWithCaching(awsConfig aws.Config, namespace, environment, _ string, _ *zap.Logger, _ *cost.TrackingService, _ interface{}) *CloudWatchMetricsRepository

NewCloudWatchMetricsRepositoryWithCaching creates repository with DynamoDB caching enabled This demonstrates how BaseRepository integration would work for performance optimization

func (*CloudWatchMetricsRepository) CacheMetrics

func (r *CloudWatchMetricsRepository) CacheMetrics(ctx context.Context, serviceName string, metrics *ServiceMetrics) error

CacheMetrics stores metrics in DynamoDB for performance optimization (OPTIONAL enhancement) This demonstrates how BaseRepository could be used for caching CloudWatch data

func (*CloudWatchMetricsRepository) GetCachedMetrics

func (r *CloudWatchMetricsRepository) GetCachedMetrics(ctx context.Context, serviceName string) (*ServiceMetrics, error)

GetCachedMetrics retrieves cached metrics from DynamoDB (OPTIONAL enhancement) This demonstrates how BaseRepository could be used for retrieving cached CloudWatch data

func (*CloudWatchMetricsRepository) GetCostBreakdown

func (r *CloudWatchMetricsRepository) GetCostBreakdown(ctx context.Context, period time.Duration) (*CostBreakdown, error)

GetCostBreakdown retrieves detailed cost breakdown for the specified period PRESERVE: AWS cost analysis - critical for cost monitoring and optimization

func (*CloudWatchMetricsRepository) GetInstanceMetrics

func (r *CloudWatchMetricsRepository) GetInstanceMetrics(ctx context.Context, period time.Duration) (*ServiceMetrics, error)

GetInstanceMetrics retrieves instance-level metrics for the past period PRESERVE: AWS monitoring - critical for instance-level operational visibility

func (*CloudWatchMetricsRepository) GetServiceMetrics

func (r *CloudWatchMetricsRepository) GetServiceMetrics(ctx context.Context, serviceName string, period time.Duration) (*ServiceMetrics, error)

GetServiceMetrics retrieves comprehensive metrics for a service over the specified period PRESERVE: Core CloudWatch business logic - critical for AWS monitoring and operational dashboards

type CollectionQueryConfig

type CollectionQueryConfig struct {
	PKKey       string // What to use as PK value prefix (e.g., "object", "USER", "ACTOR")
	SKKey       string // What to use as SK value prefix (e.g., "likes", "PROFILE", "BLOCKED")
	IndexName   string // GSI index name if using GSI (empty for main table)
	GSIConfig   *GSIQueryConfig
	LogName     string // Name for logging (e.g., "likes", "blocks")
	ErrorPrefix string // Error message prefix (e.g., "get likes", "query blocks")
}

CollectionQueryConfig configures behavior for collection query operations

type CommonQueries

type CommonQueries struct {
	*QueryUtils
}

CommonQueries contains common query patterns used across repositories

func NewCommonQueries

func NewCommonQueries(db core.DB, logger *zap.Logger) *CommonQueries

NewCommonQueries creates a new CommonQueries instance

func (*CommonQueries) GetActiveTokensForUser

func (c *CommonQueries) GetActiveTokensForUser(ctx context.Context, username string) (*QueryResult[map[string]interface{}], error)

GetActiveTokensForUser retrieves active tokens for a user

func (*CommonQueries) GetUserFollowers

func (c *CommonQueries) GetUserFollowers(ctx context.Context, username string, limit int, cursor string) (*QueryResult[map[string]interface{}], error)

GetUserFollowers retrieves followers for a user with pagination

func (*CommonQueries) GetUserFollows

func (c *CommonQueries) GetUserFollows(ctx context.Context, username string, limit int, cursor string) (*QueryResult[map[string]interface{}], error)

GetUserFollows retrieves follows for a user with pagination

type CommonUtils

type CommonUtils struct {
	Keys       *KeyUtils
	GSI        *GSIKeyUtils
	Time       *TimeUtils
	Validation *ValidationUtils
	Pagination *PaginationUtils
}

CommonUtils aggregates all utility types for easy access

func NewCommonUtils

func NewCommonUtils() *CommonUtils

NewCommonUtils creates a new CommonUtils instance with all utilities

type CommunityNoteRepository

type CommunityNoteRepository struct {
	*EnhancedBaseRepository[*models.CommunityNote]
}

CommunityNoteRepository implements community note operations using enhanced repository patterns

func NewCommunityNoteRepository

func NewCommunityNoteRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *CommunityNoteRepository

NewCommunityNoteRepository creates a new community note repository with enhanced functionality

func (*CommunityNoteRepository) CreateCommunityNote

func (r *CommunityNoteRepository) CreateCommunityNote(ctx context.Context, note *storage.CommunityNote) error

CreateCommunityNote creates a new community note - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) CreateCommunityNoteVote

func (r *CommunityNoteRepository) CreateCommunityNoteVote(ctx context.Context, vote *storage.CommunityNoteVote) error

CreateCommunityNoteVote creates a vote on a note - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetCommunityNote

func (r *CommunityNoteRepository) GetCommunityNote(ctx context.Context, noteID string) (*storage.CommunityNote, error)

GetCommunityNote retrieves a note by ID - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetCommunityNoteVotes

func (r *CommunityNoteRepository) GetCommunityNoteVotes(ctx context.Context, noteID string) ([]*storage.CommunityNoteVote, error)

GetCommunityNoteVotes retrieves votes on a specific community note - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetCommunityNotesByAuthor

func (r *CommunityNoteRepository) GetCommunityNotesByAuthor(ctx context.Context, authorID string, limit int, cursor string) ([]*storage.CommunityNote, string, error)

GetCommunityNotesByAuthor retrieves community notes authored by a specific actor - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetUserCommunityNoteVotes

func (r *CommunityNoteRepository) GetUserCommunityNoteVotes(ctx context.Context, userID string, noteIDs []string) (map[string]*storage.CommunityNoteVote, error)

GetUserCommunityNoteVotes retrieves a user's votes on specific notes - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetUserVotingHistory

func (r *CommunityNoteRepository) GetUserVotingHistory(ctx context.Context, userID string, limit int) ([]*storage.CommunityNoteVote, error)

GetUserVotingHistory retrieves a user's voting history for reputation calculation - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) GetVisibleCommunityNotes

func (r *CommunityNoteRepository) GetVisibleCommunityNotes(ctx context.Context, objectID string) ([]*storage.CommunityNote, error)

GetVisibleCommunityNotes retrieves visible notes for an object - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) UpdateCommunityNoteAnalysis

func (r *CommunityNoteRepository) UpdateCommunityNoteAnalysis(ctx context.Context, noteID string, sentiment, objectivity, sourceQuality float64) error

UpdateCommunityNoteAnalysis updates AI analysis results for a note - COMMUNITY NOTES BUSINESS LOGIC

func (*CommunityNoteRepository) UpdateCommunityNoteScore

func (r *CommunityNoteRepository) UpdateCommunityNoteScore(ctx context.Context, noteID string, score float64, status string) error

UpdateCommunityNoteScore updates a note's score and visibility - COMMUNITY NOTES BUSINESS LOGIC

type ContentQuality

type ContentQuality struct {
	MediaPresence  float64 // 0.0-1.0 indicating presence of media attachments
	LinkPresence   float64 // 0.0-1.0 indicating presence of external links
	LanguageCode   string  // Detected language code
	TextLength     int     // Character count of text content
	HashtagDensity float64 // Ratio of hashtags to total words
}

ContentQuality represents analyzed content quality metrics

type ConversationRepository

type ConversationRepository struct {
	*EnhancedBaseRepository[*models.Conversation]
	// contains filtered or unexported fields
}

ConversationRepository handles conversation-related database operations using enhanced patterns

func NewConversationRepository

func NewConversationRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ConversationRepository

NewConversationRepository creates a new conversation repository with enhanced functionality and cost tracking

func (*ConversationRepository) AddParticipant

func (r *ConversationRepository) AddParticipant(ctx context.Context, conversationID, participantID string) error

AddParticipant adds a participant to a conversation (KEEP - Complex participant management)

func (*ConversationRepository) AddStatusToConversation

func (r *ConversationRepository) AddStatusToConversation(ctx context.Context, conversationID, statusID, senderUsername string) error

AddStatusToConversation adds a status/message to a conversation (KEEP - Complex message threading logic)

func (*ConversationRepository) CreateConversation

func (r *ConversationRepository) CreateConversation(ctx context.Context, conversation *models.Conversation, participants []string) error

CreateConversation creates a new conversation with participants (KEEP - Complex conversation business logic)

func (*ConversationRepository) CreateConversationMute

func (r *ConversationRepository) CreateConversationMute(ctx context.Context, mute *storage.ConversationMute) error

CreateConversationMute creates a new conversation mute (KEEP - Mute business logic)

func (*ConversationRepository) DeleteConversation

func (r *ConversationRepository) DeleteConversation(ctx context.Context, id string) error

DeleteConversation deletes a conversation by ID (KEEP - Complex cleanup logic)

func (*ConversationRepository) DeleteConversationMute

func (r *ConversationRepository) DeleteConversationMute(ctx context.Context, username, conversationID string) error

DeleteConversationMute removes a conversation mute (REPLACE with BaseRepository pattern)

func (*ConversationRepository) GetConversation

func (r *ConversationRepository) GetConversation(ctx context.Context, id string) (*models.Conversation, error)

GetConversation retrieves a conversation by ID (REPLACE with BaseRepository)

func (*ConversationRepository) GetConversationByParticipants

func (r *ConversationRepository) GetConversationByParticipants(ctx context.Context, participants []string) (*models.Conversation, error)

GetConversationByParticipants finds a conversation with exact participants (KEEP - Complex participant search logic)

func (*ConversationRepository) GetConversationMessageCount

func (r *ConversationRepository) GetConversationMessageCount(ctx context.Context, conversationID string) (int64, error)

GetConversationMessageCount gets the total number of messages in a conversation (KEEP - Complex counting with caching)

func (*ConversationRepository) GetConversationMessagesByTimeRange

func (r *ConversationRepository) GetConversationMessagesByTimeRange(ctx context.Context, conversationID string, startTime, endTime time.Time, limit int) ([]*models.ConversationMessage, error)

GetConversationMessagesByTimeRange gets messages in a conversation within a time range (KEEP - Complex time range queries)

func (*ConversationRepository) GetConversationParticipants

func (r *ConversationRepository) GetConversationParticipants(ctx context.Context, conversationID string) ([]string, error)

GetConversationParticipants retrieves the list of participants in a conversation (KEEP - Participant retrieval logic)

func (*ConversationRepository) GetConversationStatuses

func (r *ConversationRepository) GetConversationStatuses(ctx context.Context, conversationID string, limit int, cursor string) ([]*storage.ConversationStatus, string, error)

GetConversationStatuses retrieves messages in a conversation with pagination (KEEP - Complex message retrieval)

func (*ConversationRepository) GetMutedConversations

func (r *ConversationRepository) GetMutedConversations(ctx context.Context, username string) ([]string, error)

GetMutedConversations retrieves all muted conversations for a user (KEEP - Complex mute retrieval with expiration cleanup)

func (*ConversationRepository) GetUnreadConversationCount

func (r *ConversationRepository) GetUnreadConversationCount(ctx context.Context, username string) (int, error)

GetUnreadConversationCount gets the count of unread conversations for a user (KEEP - Complex count logic)

func (*ConversationRepository) GetUnreadConversations

GetUnreadConversations retrieves unread conversations for a user (KEEP - Complex filtering logic)

func (*ConversationRepository) GetUnreadMessageCount

func (r *ConversationRepository) GetUnreadMessageCount(ctx context.Context, username string) (int64, error)

GetUnreadMessageCount gets the count of unread messages for a user across all conversations (KEEP - Complex aggregation logic)

func (*ConversationRepository) GetUnreadStatusCount

func (r *ConversationRepository) GetUnreadStatusCount(ctx context.Context, conversationID, username string) (int, error)

GetUnreadStatusCount gets the count of unread statuses in a conversation for a user (KEEP - Complex counting logic)

func (*ConversationRepository) GetUserConversations

GetUserConversations retrieves conversations for a user with pagination (KEEP - Complex pagination logic)

func (*ConversationRepository) IsConversationMuted

func (r *ConversationRepository) IsConversationMuted(ctx context.Context, username, conversationID string) (bool, error)

IsConversationMuted checks if a conversation is muted by a user (KEEP - Mute check logic with expiration)

func (*ConversationRepository) LeaveConversation

func (r *ConversationRepository) LeaveConversation(ctx context.Context, conversationID, username string) error

LeaveConversation removes a participant from a conversation (KEEP - Complex participant management)

func (*ConversationRepository) MarkConversationRead

func (r *ConversationRepository) MarkConversationRead(ctx context.Context, conversationID, username string) error

MarkConversationRead marks a conversation as read for a user (KEEP - Read receipt business logic)

func (*ConversationRepository) MarkConversationUnread

func (r *ConversationRepository) MarkConversationUnread(ctx context.Context, conversationID, userID string) error

MarkConversationUnread marks a conversation as unread for a user (KEEP - Unread notification logic)

func (*ConversationRepository) MarkStatusRead

func (r *ConversationRepository) MarkStatusRead(ctx context.Context, conversationID, _, username string) error

MarkStatusRead marks a specific status as read by a user (KEEP - Read receipt logic)

func (*ConversationRepository) RemoveParticipant

func (r *ConversationRepository) RemoveParticipant(ctx context.Context, conversationID, participantID string) error

RemoveParticipant removes a participant from a conversation (KEEP - Complex participant management)

func (*ConversationRepository) RemoveStatusFromConversation

func (r *ConversationRepository) RemoveStatusFromConversation(ctx context.Context, conversationID, statusID string) error

RemoveStatusFromConversation removes a status from a conversation (KEEP - Complex message removal logic)

func (*ConversationRepository) SearchConversations

SearchConversations searches conversations for a user by query (KEEP - Search logic with filtering)

func (*ConversationRepository) UpdateConversation

func (r *ConversationRepository) UpdateConversation(ctx context.Context, conversation *models.Conversation) error

UpdateConversation updates a conversation (KEEP - Complex conversation update logic)

func (*ConversationRepository) UpdateConversationLastStatus

func (r *ConversationRepository) UpdateConversationLastStatus(ctx context.Context, id, lastStatusID string) error

UpdateConversationLastStatus updates the last status in a conversation (KEEP - Conversation state update logic)

type CostAnomaly

type CostAnomaly struct {
	Timestamp      time.Time `json:"timestamp"`
	ActualCost     float64   `json:"actual_cost"`
	ExpectedCost   float64   `json:"expected_cost"`
	DeviationScore float64   `json:"deviation_score"` // Standard deviations from expected
	AnomalyType    string    `json:"anomaly_type"`    // "spike", "drop", "outlier"
	Severity       string    `json:"severity"`        // "low", "medium", "high", "critical"
	Confidence     float64   `json:"confidence"`      // 0-1
}

CostAnomaly represents a detected cost anomaly

type CostBreakdown

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

CostBreakdown represents cost breakdown data (PRESERVED - AWS cost monitoring)

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 CostForecast

type CostForecast struct {
	ForecastHorizon     int                `json:"forecast_horizon"` // Number of periods ahead
	Predictions         []CostPrediction   `json:"predictions"`
	ConfidenceLevel     float64            `json:"confidence_level"` // e.g., 0.95
	MeanAbsoluteError   float64            `json:"mean_absolute_error"`
	RootMeanSquareError float64            `json:"root_mean_square_error"`
	ModelType           string             `json:"model_type"` // "linear", "exponential", "seasonal"
	SeasonalFactors     map[string]float64 `json:"seasonal_factors,omitempty"`
}

CostForecast represents cost forecasting results

type CostItem

type CostItem struct {
	Operation string
	Count     int
	Cost      float64
}

CostItem represents a single cost item (PRESERVED - AWS cost monitoring)

type CostPrediction

type CostPrediction struct {
	Timestamp     time.Time `json:"timestamp"`
	PredictedCost float64   `json:"predicted_cost"`
	LowerBound    float64   `json:"lower_bound"` // Lower confidence interval
	UpperBound    float64   `json:"upper_bound"` // Upper confidence interval
	StandardError float64   `json:"standard_error"`
}

CostPrediction represents a single cost prediction

type CostTrackable

type CostTrackable interface {
	CostTrackingItem
	GetTotalCostMicroCents() int64
}

CostTrackable interface for items with cost information

type CostTrackingItem

type CostTrackingItem interface {
	GetTimestamp() time.Time
}

CostTrackingItem interface for cost tracking models

type CostTrackingQueryHelper

type CostTrackingQueryHelper struct {
	// contains filtered or unexported fields
}

CostTrackingQueryHelper provides common query patterns for cost tracking

func NewCostTrackingQueryHelper

func NewCostTrackingQueryHelper(db core.DB, tableName string, logger *zap.Logger) *CostTrackingQueryHelper

NewCostTrackingQueryHelper creates a new cost tracking query helper

func (*CostTrackingQueryHelper) GetCostTrackingByTimeRange

func (h *CostTrackingQueryHelper) GetCostTrackingByTimeRange(ctx context.Context, gsiIndex, gsiPKValue, skPrefix string, startTime, endTime time.Time, limit int) ([]*models.NotificationCostTracking, error)

GetCostTrackingByTimeRange retrieves cost tracking records within a time range using common patterns

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 // Positive = increasing, Negative = decreasing (simple)

	// Enhanced statistical analysis
	LinearRegression *LinearRegressionStats `json:"linear_regression,omitempty"`
	StatisticalTests *StatisticalTests      `json:"statistical_tests,omitempty"`
	Anomalies        []CostAnomaly          `json:"anomalies,omitempty"`
	Forecast         *CostForecast          `json:"forecast,omitempty"`
	Seasonality      *SeasonalityAnalysis   `json:"seasonality,omitempty"`
}

CostTrend represents cost trend analysis with statistical analysis

type CursorData

type CursorData struct {
	LastEvaluatedKey map[string]interface{} `json:"last_evaluated_key,omitempty"` // DynamORM's LastEvaluatedKey
	LastScore        float64                `json:"last_score,omitempty"`         // Last item's score for relevance sorting
	LastTimestamp    time.Time              `json:"last_timestamp,omitempty"`     // Last item's timestamp for time sorting
	LastID           string                 `json:"last_id,omitempty"`            // Last item's ID for tie-breaking
	SortOrder        SearchSortOrder        `json:"sort_order"`                   // Sort order used
}

CursorData represents the data stored in a pagination cursor

func DecodeCursor

func DecodeCursor(cursor string) (*CursorData, error)

DecodeCursor parses a cursor string back to cursor data

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 the health status of DLQ for monitoring

type DLQRepository

type DLQRepository struct {
	*EnhancedBaseRepository[*models.DLQMessage]
}

DLQRepository handles dead letter queue message operations using enhanced patterns

func NewDLQRepository

func NewDLQRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *DLQRepository

NewDLQRepository creates a new DLQ repository with enhanced functionality

func NewDLQRepositorySimple

func NewDLQRepositorySimple(db core.DB, tableName string, logger *zap.Logger) *DLQRepository

NewDLQRepositorySimple creates a new DLQ repository without cost tracking (backward compatibility)

func (*DLQRepository) AnalyzeFailurePatterns

func (r *DLQRepository) AnalyzeFailurePatterns(ctx context.Context, service string, days int) (map[string]*DLQSimilarityGroup, error)

AnalyzeFailurePatterns analyzes DLQ messages to identify common failure patterns

func (*DLQRepository) BatchUpdateDLQMessages

func (r *DLQRepository) BatchUpdateDLQMessages(ctx context.Context, messages []*models.DLQMessage) error

BatchUpdateDLQMessages updates multiple DLQ messages

func (*DLQRepository) CleanupExpiredMessages

func (r *DLQRepository) CleanupExpiredMessages(ctx context.Context, before time.Time) (int, error)

CleanupExpiredMessages deletes expired DLQ messages (DLQ-specific cleanup logic)

func (*DLQRepository) CreateDLQMessage

func (r *DLQRepository) CreateDLQMessage(ctx context.Context, message *models.DLQMessage) error

CreateDLQMessage creates a new DLQ message using BaseRepository

func (*DLQRepository) DeleteDLQMessage

func (r *DLQRepository) DeleteDLQMessage(ctx context.Context, message *models.DLQMessage) error

DeleteDLQMessage deletes a DLQ message using BaseRepository

func (*DLQRepository) GetDLQAnalytics

func (r *DLQRepository) GetDLQAnalytics(ctx context.Context, service string, timeRange DLQTimeRange) (*DLQAnalytics, error)

GetDLQAnalytics returns analytics data for DLQ messages

func (*DLQRepository) GetDLQMessage

func (r *DLQRepository) GetDLQMessage(ctx context.Context, id string) (*models.DLQMessage, error)

GetDLQMessage retrieves a DLQ message by ID (complex query - needs custom implementation)

func (*DLQRepository) GetDLQMessagesByErrorType

func (r *DLQRepository) GetDLQMessagesByErrorType(ctx context.Context, errorType string, limit int, cursor string) ([]*models.DLQMessage, string, error)

GetDLQMessagesByErrorType retrieves DLQ messages by error type with pagination (DLQ-specific business logic)

func (*DLQRepository) GetDLQMessagesByService

func (r *DLQRepository) GetDLQMessagesByService(ctx context.Context, service string, date time.Time, limit int, cursor string) ([]*models.DLQMessage, string, error)

GetDLQMessagesByService retrieves DLQ messages for a specific service with pagination (DLQ-specific business logic)

func (*DLQRepository) GetDLQMessagesByServiceDateRange

func (r *DLQRepository) GetDLQMessagesByServiceDateRange(ctx context.Context, service string, startDate, endDate time.Time, limit int) ([]*models.DLQMessage, error)

GetDLQMessagesByServiceDateRange retrieves DLQ messages for a service across multiple dates

func (*DLQRepository) GetDLQMessagesByStatus

func (r *DLQRepository) GetDLQMessagesByStatus(ctx context.Context, service, status string, limit int, cursor string) ([]*models.DLQMessage, string, error)

GetDLQMessagesByStatus retrieves messages by status (DLQ-specific status querying)

func (*DLQRepository) GetDLQMessagesForReprocessing

func (r *DLQRepository) GetDLQMessagesForReprocessing(ctx context.Context, service string, status string, limit int, cursor string) ([]*models.DLQMessage, string, error)

GetDLQMessagesForReprocessing retrieves messages that can be reprocessed (DLQ-specific retry logic)

func (*DLQRepository) GetDLQTrends

func (r *DLQRepository) GetDLQTrends(ctx context.Context, service string, days int) (*DLQTrends, error)

GetDLQTrends returns trend data for DLQ messages over time

func (*DLQRepository) GetRetryableMessages

func (r *DLQRepository) GetRetryableMessages(ctx context.Context, service string, limit int) ([]*models.DLQMessage, error)

GetRetryableMessages returns messages that are ready for retry based on backoff schedule

func (*DLQRepository) GetSimilarMessages

func (r *DLQRepository) GetSimilarMessages(ctx context.Context, similarityHash string, limit int) ([]*models.DLQMessage, error)

GetSimilarMessages finds messages with the same similarity hash (DLQ-specific similarity analysis)

func (*DLQRepository) MonitorDLQHealth

func (r *DLQRepository) MonitorDLQHealth(ctx context.Context, service string) (*DLQHealthStatus, error)

MonitorDLQHealth provides health metrics for DLQ monitoring and alerting

func (*DLQRepository) RetryFailedMessage

func (r *DLQRepository) RetryFailedMessage(ctx context.Context, messageID string) error

RetryFailedMessage attempts to reprocess a DLQ message with exponential backoff

func (*DLQRepository) SearchDLQMessages

func (r *DLQRepository) SearchDLQMessages(ctx context.Context, filter *DLQSearchFilter) ([]*models.DLQMessage, string, error)

SearchDLQMessages searches DLQ messages with various filters (DLQ-specific search functionality)

func (*DLQRepository) SendToDeadLetterQueue

func (r *DLQRepository) SendToDeadLetterQueue(ctx context.Context, service, messageID, messageBody, errorType, errorMessage string, isPermanent bool) error

SendToDeadLetterQueue creates and stores a DLQ message with proper error categorization

func (*DLQRepository) UpdateDLQMessage

func (r *DLQRepository) UpdateDLQMessage(ctx context.Context, message *models.DLQMessage) error

UpdateDLQMessage updates an existing DLQ message using BaseRepository

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 analytics

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 struct {
	*EnhancedBaseRepository[*models.DNSCache]
	// contains filtered or unexported fields
}

DNSCacheRepository handles DNS cache operations with enhanced patterns

func NewDNSCacheRepository

func NewDNSCacheRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *DNSCacheRepository

NewDNSCacheRepository creates a new DNS cache repository with enhanced functionality

func (*DNSCacheRepository) GetDNSCache

func (r *DNSCacheRepository) GetDNSCache(ctx context.Context, hostname string) (*storage.DNSCacheEntry, error)

GetDNSCache retrieves a cached DNS lookup result Pattern: PK=DNSCACHE#hostname, SK=ENTRY

func (*DNSCacheRepository) InvalidateDNSCache

func (r *DNSCacheRepository) InvalidateDNSCache(ctx context.Context, hostname string) error

InvalidateDNSCache removes a DNS cache entry Pattern: PK=DNSCACHE#hostname, SK=ENTRY

func (*DNSCacheRepository) SetDNSCache

func (r *DNSCacheRepository) SetDNSCache(ctx context.Context, entry *storage.DNSCacheEntry) error

SetDNSCache stores a DNS lookup result in the cache Pattern: PK=DNSCACHE#hostname, SK=ENTRY

type DailyAggregate

type DailyAggregate struct {
	Date             time.Time
	TotalRequests    int64
	UniqueUsers      int64
	TotalReads       int64
	TotalWrites      int64
	TotalDurationMs  int64
	TotalCostDollars float64
}

DailyAggregate represents aggregated costs for a single day

type DailyCostSummary

type DailyCostSummary struct {
	Domain                 string                            `json:"domain"`
	Date                   time.Time                         `json:"date"`
	TotalActivities        int64                             `json:"total_activities"`
	TotalCostMicroCents    int64                             `json:"total_cost_micro_cents"`
	TotalDataTransferBytes int64                             `json:"total_data_transfer_bytes"`
	AverageResponseTime    float64                           `json:"average_response_time"`
	SuccessRate            float64                           `json:"success_rate"`
	AverageCostPerActivity float64                           `json:"average_cost_per_activity"`
	ActivityTypeBreakdown  map[string]*ActivityTypeCostStats `json:"activity_type_breakdown"`
}

DailyCostSummary represents a daily cost summary for a domain

type DeadLetterMessage

type DeadLetterMessage struct {
	PK            string                 `theorydb:"pk" json:"pk"`
	SK            string                 `theorydb:"sk" json:"sk"`
	MessageID     string                 `json:"message_id"`
	OriginalType  string                 `json:"original_type"`
	OriginalID    string                 `json:"original_id"`
	ErrorMessage  string                 `json:"error_message"`
	ErrorType     string                 `json:"error_type"`
	AttemptCount  int                    `json:"attempt_count"`
	LastAttemptAt time.Time              `json:"last_attempt_at"`
	Payload       map[string]interface{} `json:"payload"`
	CreatedAt     time.Time              `json:"created_at"`
	TTL           int64                  `json:"ttl,omitempty" theorydb:"ttl"`
}

DeadLetterMessage represents a message that failed processing

func (*DeadLetterMessage) GetPK

func (d *DeadLetterMessage) GetPK() string

GetPK returns the partition key

func (*DeadLetterMessage) GetSK

func (d *DeadLetterMessage) GetSK() string

GetSK returns the sort key

func (*DeadLetterMessage) UpdateKeys

func (d *DeadLetterMessage) UpdateKeys() error

UpdateKeys sets the partition and sort keys

type DeadLetterRepository

type DeadLetterRepository interface {
	Create(ctx context.Context, message *models.DeadLetterMessage) error
	GetByType(ctx context.Context, messageType string, limit int) ([]*models.DeadLetterMessage, error)
}

DeadLetterRepository provides operations for dead letter messages

type DefaultEventService

type DefaultEventService struct {
	// contains filtered or unexported fields
}

DefaultEventService provides basic event emission

func NewDefaultEventService

func NewDefaultEventService() *DefaultEventService

NewDefaultEventService creates a new event service

func (*DefaultEventService) AddHandler

func (e *DefaultEventService) AddHandler(handler EventHandler)

AddHandler adds an event handler

func (*DefaultEventService) Emit

func (e *DefaultEventService) Emit(ctx context.Context, event Event) error

Emit emits an event synchronously

type DefaultPermissionService

type DefaultPermissionService struct {
	// contains filtered or unexported fields
}

DefaultPermissionService provides standard permission checking logic

func NewDefaultPermissionService

func NewDefaultPermissionService() *DefaultPermissionService

NewDefaultPermissionService creates a new permission service

func (*DefaultPermissionService) CheckPermissions

func (p *DefaultPermissionService) CheckPermissions(ctx context.Context, actor string, action string, resource BaseModel) error

CheckPermissions checks if an actor has permission to perform an action on a resource

func (*DefaultPermissionService) HasPermission

func (p *DefaultPermissionService) HasPermission(_ context.Context, actor string, permission string) bool

HasPermission checks if an actor has a specific permission

type DefaultValidationService

type DefaultValidationService struct {
	// contains filtered or unexported fields
}

DefaultValidationService provides standard validation logic

func NewDefaultValidationService

func NewDefaultValidationService() *DefaultValidationService

NewDefaultValidationService creates a new validation service

func (*DefaultValidationService) ValidateBusinessRules

func (v *DefaultValidationService) ValidateBusinessRules(ctx context.Context, model BaseModel, action string) error

ValidateBusinessRules validates business logic rules

func (*DefaultValidationService) ValidateModel

func (v *DefaultValidationService) ValidateModel(_ context.Context, model BaseModel) error

ValidateModel validates a model's structure and constraints

func (*DefaultValidationService) ValidateRequiredFields

func (v *DefaultValidationService) ValidateRequiredFields(_ context.Context, model BaseModel) error

ValidateRequiredFields validates that required fields are present

type DeliveryMethodSpending

type DeliveryMethodSpending struct {
	Method                string
	Count                 int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
	AverageCostDollars    float64
}

DeliveryMethodSpending represents spending for a specific delivery method

type DeliveryMethodSummaryStats

type DeliveryMethodSummaryStats struct {
	Method                string
	Count                 int64
	SuccessfulDeliveries  int64
	FailedDeliveries      int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
	AverageCostDollars    float64
	SuccessRate           float64
}

DeliveryMethodSummaryStats represents cost statistics for a delivery method

type DeviceProvider

type DeviceProvider interface {
	GetUserDevices(ctx context.Context, username string) ([]*storage.Device, error)
}

DeviceProvider interface for getting user devices

type DomainAllowConverter

type DomainAllowConverter struct{}

DomainAllowConverter converts models.DomainAllow to storage.DomainAllow

func (DomainAllowConverter) Convert

Convert transforms a models.DomainAllow into a storage.DomainAllow

func (DomainAllowConverter) GetGSI1SK

GetGSI1SK returns the GSI1 sort key for the given DomainAllow model

type DomainBlockRepository

type DomainBlockRepository struct {
	*EnhancedBaseRepository[*models.UserDomainBlock] // Enhanced BaseRepository for user domain blocks
	// contains filtered or unexported fields
}

DomainBlockRepository implements domain block operations using enhanced DynamORM patterns

func NewDomainBlockRepository

func NewDomainBlockRepository(db core.DB, tableName string, logger *zap.Logger) *DomainBlockRepository

NewDomainBlockRepository creates a new domain block repository with enhanced functionality

func NewDomainBlockRepositoryWithCostTracking

func NewDomainBlockRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *DomainBlockRepository

NewDomainBlockRepositoryWithCostTracking creates a new domain block repository with cost tracking

func (*DomainBlockRepository) AddDomainBlock

func (r *DomainBlockRepository) AddDomainBlock(ctx context.Context, username, domain string) error

AddDomainBlock adds a domain to the user's block list

func (*DomainBlockRepository) CreateDomainAllow

func (r *DomainBlockRepository) CreateDomainAllow(ctx context.Context, allow *storage.DomainAllow) error

CreateDomainAllow adds a domain to the allowlist

func (*DomainBlockRepository) CreateDomainBlock

func (r *DomainBlockRepository) CreateDomainBlock(ctx context.Context, block *storage.InstanceDomainBlock) error

CreateDomainBlock creates a new instance-level domain block

func (*DomainBlockRepository) CreateEmailDomainBlock

func (r *DomainBlockRepository) CreateEmailDomainBlock(ctx context.Context, block *storage.EmailDomainBlock) error

CreateEmailDomainBlock creates an email domain block

func (*DomainBlockRepository) CreateInstanceDomainBlock

func (r *DomainBlockRepository) CreateInstanceDomainBlock(ctx context.Context, block *storage.InstanceDomainBlock) error

CreateInstanceDomainBlock creates an instance-level domain block

func (*DomainBlockRepository) DeleteDomainAllow

func (r *DomainBlockRepository) DeleteDomainAllow(ctx context.Context, id string) error

DeleteDomainAllow removes a domain from the allowlist

func (*DomainBlockRepository) DeleteDomainBlock

func (r *DomainBlockRepository) DeleteDomainBlock(ctx context.Context, id string) error

DeleteDomainBlock removes a domain block

func (*DomainBlockRepository) DeleteEmailDomainBlock

func (r *DomainBlockRepository) DeleteEmailDomainBlock(ctx context.Context, id string) error

DeleteEmailDomainBlock deletes an email domain block

func (*DomainBlockRepository) DeleteInstanceDomainBlock

func (r *DomainBlockRepository) DeleteInstanceDomainBlock(ctx context.Context, domain string) error

DeleteInstanceDomainBlock deletes a domain block

func (*DomainBlockRepository) GetDomainAllows

func (r *DomainBlockRepository) GetDomainAllows(ctx context.Context, limit int, cursor string) ([]*storage.DomainAllow, string, error)

GetDomainAllows retrieves domain allows (for allowlist mode)

func (*DomainBlockRepository) GetDomainBlock

GetDomainBlock retrieves a specific domain block by ID

func (*DomainBlockRepository) GetDomainBlocks

func (r *DomainBlockRepository) GetDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.InstanceDomainBlock, string, error)

GetDomainBlocks retrieves instance-level domain blocks with pagination

func (*DomainBlockRepository) GetEmailDomainBlocks

func (r *DomainBlockRepository) GetEmailDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.EmailDomainBlock, string, error)

GetEmailDomainBlocks retrieves email domain blocks with pagination

func (*DomainBlockRepository) GetInstanceDomainBlock

func (r *DomainBlockRepository) GetInstanceDomainBlock(ctx context.Context, domain string) (*storage.InstanceDomainBlock, error)

GetInstanceDomainBlock retrieves a domain block by domain

func (*DomainBlockRepository) GetInstanceDomainBlockByID

func (r *DomainBlockRepository) GetInstanceDomainBlockByID(ctx context.Context, id string) (*storage.InstanceDomainBlock, error)

GetInstanceDomainBlockByID retrieves a domain block by ID

func (*DomainBlockRepository) GetUserDomainBlocks

func (r *DomainBlockRepository) GetUserDomainBlocks(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetUserDomainBlocks retrieves all domains blocked by a user

func (*DomainBlockRepository) IsBlockedDomain

func (r *DomainBlockRepository) IsBlockedDomain(ctx context.Context, username, domain string) (bool, error)

IsBlockedDomain checks if a domain is blocked by a user

func (*DomainBlockRepository) IsDomainBlocked

func (r *DomainBlockRepository) IsDomainBlocked(ctx context.Context, domain string) (bool, *storage.InstanceDomainBlock, error)

IsDomainBlocked checks if a domain is blocked at the instance level

func (*DomainBlockRepository) IsInstanceDomainBlocked

func (r *DomainBlockRepository) IsInstanceDomainBlocked(ctx context.Context, domain string) (bool, *storage.InstanceDomainBlock, error)

IsInstanceDomainBlocked checks if a domain is blocked at the instance level

func (*DomainBlockRepository) ListInstanceDomainBlocks

func (r *DomainBlockRepository) ListInstanceDomainBlocks(ctx context.Context, limit int, cursor string) ([]*storage.InstanceDomainBlock, string, error)

ListInstanceDomainBlocks lists all instance domain blocks with pagination

func (*DomainBlockRepository) RemoveDomainBlock

func (r *DomainBlockRepository) RemoveDomainBlock(ctx context.Context, username, domain string) error

RemoveDomainBlock removes a domain from the user's block list

func (*DomainBlockRepository) UpdateDomainBlock

func (r *DomainBlockRepository) UpdateDomainBlock(ctx context.Context, id string, updates map[string]any) error

UpdateDomainBlock updates an existing domain block

func (*DomainBlockRepository) UpdateInstanceDomainBlock

func (r *DomainBlockRepository) UpdateInstanceDomainBlock(ctx context.Context, domain string, updates map[string]any) error

UpdateInstanceDomainBlock updates an existing domain block

type DomainConverter

type DomainConverter[M any, S any] interface {
	Convert(M) S
	GetGSI1SK(M) string
}

DomainConverter defines how to convert model items to storage items

type DomainDeleteConfig

type DomainDeleteConfig struct {
	ModelType   string // "email_domain_block", "domain_allow"
	ErrorPrefix string // Error message prefix for operations
}

DomainDeleteConfig holds configuration for domain deletion operations

type DomainItem

type DomainItem interface {
	GetID() string
	GetPK() string
	GetSK() string
}

DomainItem interface for models that support domain-based operations

type DomainModel

type DomainModel interface {
	UpdateKeys() error
	GetDomain() string
}

DomainModel interface defines methods required for domain models

type DomainPaginationConfig

type DomainPaginationConfig struct {
	GSIPKValue  string // Value for GSI1PK, e.g. "DOMAIN_BLOCKS", "EMAIL_DOMAIN_BLOCKS", "DOMAIN_ALLOWS"
	ErrorPrefix string // Prefix for error messages
}

DomainPaginationConfig holds configuration for paginated domain queries

type DomainStats

type DomainStats struct {
	Domain           string
	StartTime        time.Time
	EndTime          time.Time
	TotalCount       int
	SuccessCount     int
	ErrorCount       int
	InboundVolume    int64
	OutboundVolume   int64
	AvgResponseTime  float64
	ActivityTypes    map[string]int
	UniqueActors     map[string]bool
	UniqueActorCount int
}

DomainStats represents aggregated statistics for a domain

type DraftRepository

type DraftRepository struct {
	*EnhancedBaseRepository[*models.Draft]
}

DraftRepository implements draft operations

func NewDraftRepository

func NewDraftRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *DraftRepository

NewDraftRepository creates a new draft repository

func (*DraftRepository) CreateDraft

func (r *DraftRepository) CreateDraft(ctx context.Context, draft *models.Draft) error

CreateDraft creates a new draft

func (*DraftRepository) DeleteDraft

func (r *DraftRepository) DeleteDraft(ctx context.Context, authorID, draftID string) error

DeleteDraft deletes a draft

func (*DraftRepository) GetDraft

func (r *DraftRepository) GetDraft(ctx context.Context, authorID, draftID string) (*models.Draft, error)

GetDraft retrieves a draft by author ID and draft ID

func (*DraftRepository) ListDraftsByAuthor

func (r *DraftRepository) ListDraftsByAuthor(ctx context.Context, authorID string, limit int) ([]*models.Draft, error)

ListDraftsByAuthor lists drafts for an author

func (*DraftRepository) ListDraftsByAuthorPaginated

func (r *DraftRepository) ListDraftsByAuthorPaginated(ctx context.Context, authorID string, limit int, cursor string) ([]*models.Draft, string, error)

ListDraftsByAuthorPaginated lists drafts for an author with cursor pagination. Cursor values are either full SK values (ID#...) or raw draft IDs.

func (*DraftRepository) ListScheduledDraftsDuePaginated

func (r *DraftRepository) ListScheduledDraftsDuePaginated(ctx context.Context, dueBefore time.Time, limit int, cursor string) ([]*models.Draft, string, error)

ListScheduledDraftsDuePaginated lists drafts that are scheduled to publish at or before the provided time. Cursor values are gsi4SK values.

func (*DraftRepository) UpdateDraft

func (r *DraftRepository) UpdateDraft(ctx context.Context, draft *models.Draft) error

UpdateDraft updates an existing draft

type EmailDomainBlockConverter

type EmailDomainBlockConverter struct{}

EmailDomainBlockConverter converts models.EmailDomainBlock to storage.EmailDomainBlock

func (EmailDomainBlockConverter) Convert

Convert transforms a models.EmailDomainBlock into a storage.EmailDomainBlock

func (EmailDomainBlockConverter) GetGSI1SK

GetGSI1SK returns the GSI1 sort key for the given EmailDomainBlock model

type EmojiRepository

type EmojiRepository struct {
	*EnhancedBaseRepository[*models.EmojiModel]
}

EmojiRepository handles custom emoji operations using enhanced DynamORM patterns

func NewEmojiRepository

func NewEmojiRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *EmojiRepository

NewEmojiRepository creates a new emoji repository with enhanced functionality and cost tracking

func (*EmojiRepository) CreateCustomEmoji

func (r *EmojiRepository) CreateCustomEmoji(ctx context.Context, emoji *storage.CustomEmoji) error

CreateCustomEmoji creates a new custom emoji

func (*EmojiRepository) DeleteCustomEmoji

func (r *EmojiRepository) DeleteCustomEmoji(ctx context.Context, shortcode string) error

DeleteCustomEmoji deletes a custom emoji

func (*EmojiRepository) GetCustomEmoji

func (r *EmojiRepository) GetCustomEmoji(ctx context.Context, shortcode string) (*storage.CustomEmoji, error)

GetCustomEmoji retrieves a custom emoji by shortcode

func (*EmojiRepository) GetCustomEmojis

func (r *EmojiRepository) GetCustomEmojis(ctx context.Context) ([]*storage.CustomEmoji, error)

GetCustomEmojis retrieves all custom emojis (not disabled)

func (*EmojiRepository) GetCustomEmojisByCategory

func (r *EmojiRepository) GetCustomEmojisByCategory(ctx context.Context, category string) ([]*storage.CustomEmoji, error)

GetCustomEmojisByCategory retrieves custom emojis by category

func (*EmojiRepository) GetPopularEmojis

func (r *EmojiRepository) GetPopularEmojis(ctx context.Context, domain string, limit int) ([]*storage.CustomEmoji, error)

GetPopularEmojis retrieves emojis by popularity score, optionally filtered by domain

func (*EmojiRepository) GetRemoteEmoji

func (r *EmojiRepository) GetRemoteEmoji(ctx context.Context, shortcode, domain string) (*storage.CustomEmoji, error)

GetRemoteEmoji retrieves a remote emoji by shortcode and domain

func (*EmojiRepository) IncrementEmojiUsage

func (r *EmojiRepository) IncrementEmojiUsage(ctx context.Context, shortcode string) error

IncrementEmojiUsage increments the usage count for an emoji

func (*EmojiRepository) SearchEmojis

func (r *EmojiRepository) SearchEmojis(ctx context.Context, query string, limit int) ([]*storage.CustomEmoji, error)

SearchEmojis performs sophisticated emoji searches with relevance scoring

func (*EmojiRepository) UpdateCustomEmoji

func (r *EmojiRepository) UpdateCustomEmoji(ctx context.Context, emoji *storage.CustomEmoji) error

UpdateCustomEmoji updates an existing custom emoji

type EnhancedBaseRepository

type EnhancedBaseRepository[T BaseModel] struct {
	*BaseRepository[T] // Embed existing functionality
	// contains filtered or unexported fields
}

EnhancedBaseRepository provides comprehensive CRUD + business logic patterns

func NewEnhancedBaseRepository

func NewEnhancedBaseRepository[T BaseModel](
	db core.DB,
	tableName string,
	logger *zap.Logger,
	costService *cost.TrackingService,
	repoName string,
	entityName string,
) *EnhancedBaseRepository[T]

NewEnhancedBaseRepository creates a new enhanced base repository

func (*EnhancedBaseRepository[T]) CountWhere

func (r *EnhancedBaseRepository[T]) CountWhere(ctx context.Context, conditions map[string]interface{}) (int64, error)

CountWhere counts entities matching specific conditions

func (*EnhancedBaseRepository[T]) FindByMultipleFields

func (r *EnhancedBaseRepository[T]) FindByMultipleFields(ctx context.Context, filters map[string]interface{}) ([]T, error)

FindByMultipleFields performs queries with multiple field filters

func (*EnhancedBaseRepository[T]) FindWithCache

func (r *EnhancedBaseRepository[T]) FindWithCache(ctx context.Context, pk string, cacheTTL time.Duration) ([]T, error)

FindWithCache retrieves entities with caching support

func (*EnhancedBaseRepository[T]) GetEntityName

func (r *EnhancedBaseRepository[T]) GetEntityName() string

GetEntityName returns the friendly name for this repository's entities

func (*EnhancedBaseRepository[T]) GetWithCache

func (r *EnhancedBaseRepository[T]) GetWithCache(ctx context.Context, pk, sk string, result T, cacheTTL time.Duration) error

GetWithCache retrieves a single entity with caching support

func (*EnhancedBaseRepository[T]) HasCaching

func (r *EnhancedBaseRepository[T]) HasCaching() bool

HasCaching returns true if caching service is configured

func (*EnhancedBaseRepository[T]) HasEvents

func (r *EnhancedBaseRepository[T]) HasEvents() bool

HasEvents returns true if event service is configured

func (*EnhancedBaseRepository[T]) HasPermissions

func (r *EnhancedBaseRepository[T]) HasPermissions() bool

HasPermissions returns true if permission service is configured

func (*EnhancedBaseRepository[T]) HasValidation

func (r *EnhancedBaseRepository[T]) HasValidation() bool

HasValidation returns true if validation service is configured

func (*EnhancedBaseRepository[T]) SetCachingService

func (r *EnhancedBaseRepository[T]) SetCachingService(caching CachingService)

SetCachingService sets the caching service

func (*EnhancedBaseRepository[T]) SetEventService

func (r *EnhancedBaseRepository[T]) SetEventService(events EventService)

SetEventService sets the event service

func (*EnhancedBaseRepository[T]) SetPermissionService

func (r *EnhancedBaseRepository[T]) SetPermissionService(permissions PermissionService)

SetPermissionService sets the permission service

func (*EnhancedBaseRepository[T]) SetValidationService

func (r *EnhancedBaseRepository[T]) SetValidationService(validator ValidationService)

SetValidationService sets the validation service

func (*EnhancedBaseRepository[T]) ValidateAndBatchCreate

func (r *EnhancedBaseRepository[T]) ValidateAndBatchCreate(ctx context.Context, items []T) error

ValidateAndBatchCreate creates multiple items with validation

func (*EnhancedBaseRepository[T]) ValidateAndCreate

func (r *EnhancedBaseRepository[T]) ValidateAndCreate(ctx context.Context, model T) error

ValidateAndCreate performs validation and creates with event emission

func (*EnhancedBaseRepository[T]) ValidateAndDelete

func (r *EnhancedBaseRepository[T]) ValidateAndDelete(ctx context.Context, pk, sk string) error

ValidateAndDelete performs permission checks and deletes with event emission

func (*EnhancedBaseRepository[T]) ValidateAndUpdate

func (r *EnhancedBaseRepository[T]) ValidateAndUpdate(ctx context.Context, model T) error

ValidateAndUpdate performs validation and updates with event emission

type EnhancedHashtagMetrics

type EnhancedHashtagMetrics struct {
	// Basic info
	HashtagName string    `json:"hashtag_name"`
	FirstSeen   time.Time `json:"first_seen"`
	LastUsed    time.Time `json:"last_used"`

	// Aggregate metrics
	TotalUsage      int64   `json:"total_usage"`
	UniqueUsers     int64   `json:"unique_users"`
	TotalEngagement int64   `json:"total_engagement"`
	AverageTrust    float64 `json:"average_trust"`

	// Time-windowed data
	WindowMetrics map[string]*EnhancedWindowMetrics `json:"window_metrics"`

	// Calculated scores
	Velocity      float64 `json:"velocity"`       // Usage per hour
	Acceleration  float64 `json:"acceleration"`   // Change in velocity
	DiversityRate float64 `json:"diversity_rate"` // Unique users / total usage
	QualityScore  float64 `json:"quality_score"`  // Content quality indicator
	SpamScore     float64 `json:"spam_score"`     // Spam likelihood
	NoveltyScore  float64 `json:"novelty_score"`  // Newness factor
}

EnhancedHashtagMetrics provides comprehensive metrics for trending calculation

type EnhancedPatternRepository

type EnhancedPatternRepository struct {
	*EnhancedBaseRepository[*models.EnhancedModerationPattern]
}

EnhancedPatternRepository handles enhanced moderation pattern storage operations

func NewEnhancedPatternRepository

func NewEnhancedPatternRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *EnhancedPatternRepository

NewEnhancedPatternRepository creates a new enhanced pattern repository with enhanced functionality

func (*EnhancedPatternRepository) AnalyzeContentPatterns

func (r *EnhancedPatternRepository) AnalyzeContentPatterns(ctx context.Context, content string, patterns []*models.EnhancedModerationPattern) (*PatternAnalysis, error)

AnalyzeContentPatterns performs ML-based content analysis using enhanced patterns

func (*EnhancedPatternRepository) CleanupExpiredPatterns

func (r *EnhancedPatternRepository) CleanupExpiredPatterns(ctx context.Context) (int, error)

CleanupExpiredPatterns removes patterns that have expired

func (*EnhancedPatternRepository) CreatePattern

CreatePattern creates a new enhanced moderation pattern

func (*EnhancedPatternRepository) CreateTestResult

func (r *EnhancedPatternRepository) CreateTestResult(ctx context.Context, result *models.PatternTestResult) error

CreateTestResult records pattern test results

func (*EnhancedPatternRepository) DeletePattern

func (r *EnhancedPatternRepository) DeletePattern(ctx context.Context, patternID string) error

DeletePattern soft deletes a pattern by marking it inactive

func (*EnhancedPatternRepository) DetectSpamPatterns

func (r *EnhancedPatternRepository) DetectSpamPatterns(ctx context.Context, content string, senderInfo *SenderInfo) (*SpamDetectionResult, error)

DetectSpamPatterns performs adaptive spam detection with false positive reduction

func (*EnhancedPatternRepository) GetActivePatterns

func (r *EnhancedPatternRepository) GetActivePatterns(ctx context.Context, limit int) ([]*models.EnhancedModerationPattern, error)

GetActivePatterns retrieves all active patterns ordered by priority

func (*EnhancedPatternRepository) GetLatestTestResult

func (r *EnhancedPatternRepository) GetLatestTestResult(ctx context.Context, patternID, testType string) (*models.PatternTestResult, error)

GetLatestTestResult gets the most recent test result for a pattern and test type

func (*EnhancedPatternRepository) GetOptimalPatterns

func (r *EnhancedPatternRepository) GetOptimalPatterns(ctx context.Context, category string, maxPatterns int) ([]*models.EnhancedModerationPattern, error)

GetOptimalPatterns retrieves patterns optimized for performance and accuracy

func (*EnhancedPatternRepository) GetPattern

GetPattern retrieves an enhanced pattern by ID

func (*EnhancedPatternRepository) GetPatternCache

func (r *EnhancedPatternRepository) GetPatternCache(ctx context.Context, patternID, patternType string) (*models.PatternCache, error)

GetPatternCache retrieves cached pattern data

func (*EnhancedPatternRepository) GetPatternStatistics

func (r *EnhancedPatternRepository) GetPatternStatistics(ctx context.Context) (map[string]interface{}, error)

GetPatternStatistics returns aggregate statistics for patterns

func (*EnhancedPatternRepository) GetPatternsByCategory

func (r *EnhancedPatternRepository) GetPatternsByCategory(ctx context.Context, category string, limit int) ([]*models.EnhancedModerationPattern, error)

GetPatternsByCategory retrieves patterns by category ordered by effectiveness

func (*EnhancedPatternRepository) GetPatternsByType

func (r *EnhancedPatternRepository) GetPatternsByType(ctx context.Context, patternType string, limit int) ([]*models.EnhancedModerationPattern, error)

GetPatternsByType retrieves patterns by type ordered by effectiveness

func (*EnhancedPatternRepository) GetPerformanceMetrics

func (r *EnhancedPatternRepository) GetPerformanceMetrics(ctx context.Context, patternID, startDate, endDate string) ([]*models.PatternPerformanceMetric, error)

GetPerformanceMetrics retrieves performance metrics for a pattern and date range

func (*EnhancedPatternRepository) GetTestResults

func (r *EnhancedPatternRepository) GetTestResults(ctx context.Context, patternID string, testType string, limit int) ([]*models.PatternTestResult, error)

GetTestResults retrieves test results for a pattern

func (*EnhancedPatternRepository) InvalidatePatternCache

func (r *EnhancedPatternRepository) InvalidatePatternCache(ctx context.Context, patternID, patternType string) error

InvalidatePatternCache removes cached pattern data

func (*EnhancedPatternRepository) LearnFromFeedback

func (r *EnhancedPatternRepository) LearnFromFeedback(ctx context.Context, feedbackBatch []*PatternFeedback) error

LearnFromFeedback implements continuous improvement based on user feedback

func (*EnhancedPatternRepository) RecordMatch

func (r *EnhancedPatternRepository) RecordMatch(ctx context.Context, patternID string, isMatch bool, isTruePositive bool, matchTime float64) error

RecordMatch records a pattern match and updates statistics

func (*EnhancedPatternRepository) RecordPerformanceMetric

func (r *EnhancedPatternRepository) RecordPerformanceMetric(ctx context.Context, metric *models.PatternPerformanceMetric) error

RecordPerformanceMetric records detailed performance metrics

func (*EnhancedPatternRepository) SetPatternCache

func (r *EnhancedPatternRepository) SetPatternCache(ctx context.Context, cache *models.PatternCache) error

SetPatternCache stores compiled pattern data in cache

func (*EnhancedPatternRepository) UpdatePattern

UpdatePattern updates an existing enhanced pattern

func (*EnhancedPatternRepository) UpdatePatternEffectiveness

func (r *EnhancedPatternRepository) UpdatePatternEffectiveness(ctx context.Context, patternID string, feedback *PatternFeedback) error

UpdatePatternEffectiveness updates pattern effectiveness based on feedback and accuracy tracking

type EnhancedTrendingScore

type EnhancedTrendingScore struct {
	OverallScore    float64            `json:"overall_score"`
	ComponentScores map[string]float64 `json:"component_scores"`
	Timestamp       time.Time          `json:"timestamp"`
}

EnhancedTrendingScore represents the calculated trending score with breakdown in the enhanced engine

type EnhancedWindowMetrics

type EnhancedWindowMetrics struct {
	StartTime       time.Time       `json:"start_time"`
	EndTime         time.Time       `json:"end_time"`
	Duration        time.Duration   `json:"duration"`
	UsageCount      int64           `json:"usage_count"`
	UniqueUsers     int64           `json:"unique_users"`
	TotalEngagement int64           `json:"total_engagement"`
	AverageTrust    float64         `json:"average_trust"`
	Velocity        float64         `json:"velocity"`    // Usage per hour in this window
	GrowthRate      float64         `json:"growth_rate"` // Growth vs previous window
	UserGrowth      float64         `json:"user_growth"` // User growth vs previous window
	QualityMetrics  *QualityMetrics `json:"quality_metrics"`
}

EnhancedWindowMetrics represents metrics for a specific time window in the enhanced engine

type ErrorUtils

type ErrorUtils struct{}

ErrorUtils provides utilities for standardizing error handling across repositories This is maintained for backward compatibility while using the centralized error system.

func NewErrorUtils

func NewErrorUtils() *ErrorUtils

NewErrorUtils creates a new ErrorUtils instance

func (*ErrorUtils) HandleCreateError

func (e *ErrorUtils) HandleCreateError(err error, entityType, identifier string) error

HandleCreateError standardizes error handling for Create operations

func (*ErrorUtils) HandleDeleteError

func (e *ErrorUtils) HandleDeleteError(err error, entityType, _ string) error

HandleDeleteError standardizes error handling for Delete operations

func (*ErrorUtils) HandleGetError

func (e *ErrorUtils) HandleGetError(err error, entityType, identifier string) error

HandleGetError standardizes error handling for Get operations

func (*ErrorUtils) HandleNotFound

func (e *ErrorUtils) HandleNotFound(err error, entityType, identifier string) error

HandleNotFound converts DynamORM not found errors to domain-specific errors

func (*ErrorUtils) HandleQueryError

func (e *ErrorUtils) HandleQueryError(err error, entityType, queryType string) error

HandleQueryError standardizes error handling for Query operations

func (*ErrorUtils) HandleUpdateError

func (e *ErrorUtils) HandleUpdateError(err error, entityType, identifier string) error

HandleUpdateError standardizes error handling for Update operations

func (*ErrorUtils) IsConditionalCheckFailed

func (e *ErrorUtils) IsConditionalCheckFailed(err error) bool

IsConditionalCheckFailed checks if error is a conditional check failure

func (*ErrorUtils) IsNotFound

func (e *ErrorUtils) IsNotFound(err error) bool

IsNotFound checks if error is a not found error

type Event

type Event struct {
	Type      string      `json:"type"`
	Entity    string      `json:"entity"`
	EntityID  string      `json:"entity_id"`
	Action    string      `json:"action"`
	Data      interface{} `json:"data"`
	Timestamp time.Time   `json:"timestamp"`
	Actor     string      `json:"actor,omitempty"`
}

Event represents a repository event

func NewCreatedEvent

func NewCreatedEvent(model BaseModel) Event

NewCreatedEvent creates an event for entity creation

func NewDeletedEvent

func NewDeletedEvent(pk, sk string) Event

NewDeletedEvent creates an event for entity deletion

func NewEvent

func NewEvent(eventType, entity, entityID, action string, data interface{}) Event

NewEvent creates a new repository event

func NewUpdatedEvent

func NewUpdatedEvent(model BaseModel) Event

NewUpdatedEvent creates an event for entity updates

type EventHandler

type EventHandler interface {
	Handle(ctx context.Context, event Event) error
}

EventHandler handles emitted events

type EventService

type EventService interface {
	Emit(ctx context.Context, event Event) error
}

EventService provides standardized event emission

type ExportRepository

type ExportRepository struct {
	// contains filtered or unexported fields
}

ExportRepository handles export-related database operations using DynamORM

func NewExportRepository

func NewExportRepository(db core.DB, tableName string, logger *zap.Logger) *ExportRepository

NewExportRepository creates a new export repository

func (*ExportRepository) CreateExport

func (r *ExportRepository) CreateExport(_ context.Context, export *models.Export) error

CreateExport creates a new export record

func (*ExportRepository) CreateExportCostTracking

func (r *ExportRepository) CreateExportCostTracking(_ context.Context, costTracking *models.ExportCostTracking) error

CreateExportCostTracking creates a new export cost tracking record

func (*ExportRepository) GetExport

func (r *ExportRepository) GetExport(_ context.Context, exportID string) (*models.Export, error)

GetExport retrieves an export by ID

func (*ExportRepository) GetExportCostSummary

func (r *ExportRepository) GetExportCostSummary(ctx context.Context, username string, startDate, endDate time.Time) (*models.ExportCostSummary, error)

GetExportCostSummary calculates cost summary for a user's exports

func (*ExportRepository) GetExportCostTracking

func (r *ExportRepository) GetExportCostTracking(_ context.Context, exportID string) ([]*models.ExportCostTracking, error)

GetExportCostTracking retrieves export cost tracking records for an export

func (*ExportRepository) GetExportCostsByDateRange

func (r *ExportRepository) GetExportCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)

GetExportCostsByDateRange retrieves export costs for all users within a date range

func (*ExportRepository) GetExportsForUser

func (r *ExportRepository) GetExportsForUser(ctx context.Context, username string, limit int, cursor string) ([]*models.Export, string, error)

GetExportsForUser retrieves all exports for a user

func (*ExportRepository) GetHighCostExports

func (r *ExportRepository) GetHighCostExports(ctx context.Context, thresholdMicroCents int64, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)

GetHighCostExports returns export operations that exceed a cost threshold

func (*ExportRepository) GetUserExportCosts

func (r *ExportRepository) GetUserExportCosts(ctx context.Context, username string, startDate, endDate time.Time, limit int) ([]*models.ExportCostTracking, error)

GetUserExportCosts retrieves export costs for a user within a date range

func (*ExportRepository) GetUserExportsByStatus

func (r *ExportRepository) GetUserExportsByStatus(ctx context.Context, username string, statuses []string) ([]*models.Export, error)

GetUserExportsByStatus retrieves exports for a user filtered by status

func (*ExportRepository) UpdateExportStatus

func (r *ExportRepository) UpdateExportStatus(ctx context.Context, exportID, status string, completionData map[string]any, errorMsg string) error

UpdateExportStatus updates the status and metadata of an export

type Feature

type Feature struct {
	PK          string    `dynamodbav:"PK"`
	SK          string    `dynamodbav:"SK"`
	ID          string    `dynamodbav:"id"`
	Name        string    `dynamodbav:"name"`
	Description string    `dynamodbav:"description"`
	Enabled     bool      `dynamodbav:"enabled"`
	Percentage  int       `dynamodbav:"percentage"` // For gradual rollout
	UserGroups  []string  `dynamodbav:"user_groups"`
	CreatedAt   time.Time `dynamodbav:"created_at"`
	UpdatedAt   time.Time `dynamodbav:"updated_at"`
	CreatedBy   string    `dynamodbav:"created_by"`
}

Feature represents a feature flag or feature configuration

func (*Feature) GetPK

func (f *Feature) GetPK() string

GetPK returns the partition key

func (*Feature) GetSK

func (f *Feature) GetSK() string

GetSK returns the sort key

func (*Feature) UpdateKeys

func (f *Feature) UpdateKeys() error

UpdateKeys updates the GSI keys for the feature

type FeatureRepository

type FeatureRepository struct {
	*EnhancedBaseRepository[*Feature]
	// contains filtered or unexported fields
}

FeatureRepository manages feature flags using EnhancedBaseRepository This demonstrates a complete repository implementation with EnhancedBaseRepository

func NewFeatureRepository

func NewFeatureRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *FeatureRepository

NewFeatureRepository creates a new feature repository

func (*FeatureRepository) AddUserGroup

func (r *FeatureRepository) AddUserGroup(ctx context.Context, name, group string) error

AddUserGroup adds a user group to the feature

func (*FeatureRepository) CreateFeature

func (r *FeatureRepository) CreateFeature(ctx context.Context, name, description, createdBy string) (*Feature, error)

CreateFeature creates a new feature flag

func (*FeatureRepository) DeleteFeature

func (r *FeatureRepository) DeleteFeature(ctx context.Context, name string) error

DeleteFeature removes a feature flag

func (*FeatureRepository) DisableFeature

func (r *FeatureRepository) DisableFeature(ctx context.Context, name string) error

DisableFeature disables a feature flag

func (*FeatureRepository) EnableFeature

func (r *FeatureRepository) EnableFeature(ctx context.Context, name string, percentage int) error

EnableFeature enables a feature flag

func (*FeatureRepository) GetFeature

func (r *FeatureRepository) GetFeature(ctx context.Context, name string) (*Feature, error)

GetFeature retrieves a feature by name

func (*FeatureRepository) GetFeatureCount

func (r *FeatureRepository) GetFeatureCount(ctx context.Context) (int, error)

GetFeatureCount returns the total number of features

func (*FeatureRepository) IsFeatureEnabled

func (r *FeatureRepository) IsFeatureEnabled(ctx context.Context, name, userGroup string) (bool, error)

IsFeatureEnabled checks if a feature is enabled for a user

func (*FeatureRepository) ListEnabledFeatures

func (r *FeatureRepository) ListEnabledFeatures(ctx context.Context) ([]*Feature, error)

ListEnabledFeatures lists only enabled features

func (*FeatureRepository) ListFeatures

func (r *FeatureRepository) ListFeatures(ctx context.Context) ([]*Feature, error)

ListFeatures lists all features

type FeaturedTagRepository

type FeaturedTagRepository struct {
	*EnhancedBaseRepository[*models.FeaturedTag]
}

FeaturedTagRepository implements featured tag operations using enhanced DynamORM patterns

func NewFeaturedTagRepository

func NewFeaturedTagRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *FeaturedTagRepository

NewFeaturedTagRepository creates a new featured tag repository with enhanced functionality and cost tracking

func (*FeaturedTagRepository) CreateFeaturedTag

func (r *FeaturedTagRepository) CreateFeaturedTag(ctx context.Context, tag *storage.FeaturedTag) error

CreateFeaturedTag creates a new featured tag for a user

func (*FeaturedTagRepository) DeleteFeaturedTag

func (r *FeaturedTagRepository) DeleteFeaturedTag(ctx context.Context, username, name string) error

DeleteFeaturedTag removes a featured tag

func (*FeaturedTagRepository) GetFeaturedTags

func (r *FeaturedTagRepository) GetFeaturedTags(ctx context.Context, username string) ([]*storage.FeaturedTag, error)

GetFeaturedTags returns all featured tags for a user

func (*FeaturedTagRepository) GetTagSuggestions

func (r *FeaturedTagRepository) GetTagSuggestions(ctx context.Context, username string, limit int) ([]string, error)

GetTagSuggestions returns suggested tags based on user's usage

type FederationActivityRepository

type FederationActivityRepository struct {
	*EnhancedBaseRepository[*models.FederationActivity]
}

FederationActivityRepository handles federation activity persistence using enhanced patterns

func NewFederationActivityRepository

func NewFederationActivityRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *FederationActivityRepository

NewFederationActivityRepository creates a new federation activity repository with enhanced functionality

func (*FederationActivityRepository) GetDomainStats

func (r *FederationActivityRepository) GetDomainStats(ctx context.Context, domain string, startTime, endTime time.Time) (*DomainStats, error)

GetDomainStats gets aggregated statistics for a domain - federation analytics and metrics preserved

func (*FederationActivityRepository) GetFederationActivity

func (r *FederationActivityRepository) GetFederationActivity(ctx context.Context, domain, id string) (*models.FederationActivity, error)

GetFederationActivity retrieves a federation activity by ID and domain using GSI

func (*FederationActivityRepository) GetInstanceInfo

func (r *FederationActivityRepository) GetInstanceInfo(ctx context.Context, domain string) (*models.InstanceInfo, error)

GetInstanceInfo retrieves instance information - federation instance discovery preserved

func (*FederationActivityRepository) GetRecentActivities

func (r *FederationActivityRepository) GetRecentActivities(ctx context.Context, since time.Time, limit int) ([]*models.FederationActivity, error)

GetRecentActivities gets recent activities across all domains - federation monitoring preserved

func (*FederationActivityRepository) ListByActor

func (r *FederationActivityRepository) ListByActor(ctx context.Context, actorID string, startTime, endTime time.Time, limit int) ([]*models.FederationActivity, error)

ListByActor lists federation activities by actor - ActivityPub actor tracking preserved

func (*FederationActivityRepository) ListByDomain

func (r *FederationActivityRepository) ListByDomain(ctx context.Context, domain string, startTime, endTime time.Time, limit int) ([]*models.FederationActivity, error)

ListByDomain lists federation activities for a specific domain - federation analytics logic preserved

func (*FederationActivityRepository) ListByType

func (r *FederationActivityRepository) ListByType(ctx context.Context, activityType string, startTime, endTime time.Time, limit int) ([]*models.FederationActivity, error)

ListByType lists federation activities by type - ActivityPub protocol compliance queries preserved

func (*FederationActivityRepository) RecordFederationActivity

func (r *FederationActivityRepository) RecordFederationActivity(ctx context.Context, activity *models.FederationActivity) error

RecordFederationActivity creates a new federation activity with ActivityPub protocol logging

func (*FederationActivityRepository) UpdateInstanceInfo

func (r *FederationActivityRepository) UpdateInstanceInfo(ctx context.Context, info *models.InstanceInfo) error

UpdateInstanceInfo updates or creates instance information - federation instance tracking preserved

type FederationCostRepository

type FederationCostRepository struct {
	*EnhancedBaseRepository[*models.FederationCostTracking]
	// contains filtered or unexported fields
}

FederationCostRepository handles federation cost tracking operations using enhanced DynamORM patterns

func NewFederationCostRepository

NewFederationCostRepository creates a new federation cost repository with enhanced functionality

func NewFederationCostRepositoryFromBase

func NewFederationCostRepositoryFromBase(baseRepo *BaseRepository[*models.FederationCostTracking], budgetRepo *BaseRepository[*models.FederationBudget], costService *cost.TrackingService) *FederationCostRepository

NewFederationCostRepositoryFromBase creates a federation cost repository from BaseRepository instances (compatibility)

func (*FederationCostRepository) CheckBudgetLimits

func (r *FederationCostRepository) CheckBudgetLimits(ctx context.Context, domain, period, activityType, _ string, estimatedCost int64) (*BudgetCheckResult, error)

CheckBudgetLimits checks if an activity would exceed budget limits PRESERVED: CRITICAL budget enforcement logic - this is the core cost control mechanism for federation

func (*FederationCostRepository) CreateOrUpdateBudget

func (r *FederationCostRepository) CreateOrUpdateBudget(ctx context.Context, budget *models.FederationBudget) error

CreateOrUpdateBudget creates or updates a federation budget for a domain using BaseRepository

func (*FederationCostRepository) GetActiveBudgets

func (r *FederationCostRepository) GetActiveBudgets(ctx context.Context, limit int) ([]*models.FederationBudget, error)

GetActiveBudgets retrieves all active budgets PRESERVED: Critical budget monitoring - GSI queries for active budget tracking

func (*FederationCostRepository) GetBudget

func (r *FederationCostRepository) GetBudget(ctx context.Context, domain, period string) (*models.FederationBudget, error)

GetBudget retrieves a federation budget for a domain and period using BaseRepository

func (*FederationCostRepository) GetBudgetsNeedingAlerts

func (r *FederationCostRepository) GetBudgetsNeedingAlerts(ctx context.Context, limit int) ([]*models.FederationBudget, error)

GetBudgetsNeedingAlerts retrieves budgets that need alerts sent PRESERVED: Critical budget monitoring - alert threshold detection for cost management

func (*FederationCostRepository) GetBudgetsOverLimit

func (r *FederationCostRepository) GetBudgetsOverLimit(ctx context.Context, limit int) ([]*models.FederationBudget, error)

GetBudgetsOverLimit retrieves budgets that are over their limits PRESERVED: Critical budget monitoring - budget limit violation detection for cost control

func (*FederationCostRepository) GetDailyCostSummary

func (r *FederationCostRepository) GetDailyCostSummary(ctx context.Context, domain string, date time.Time) (*DailyCostSummary, error)

GetDailyCostSummary retrieves daily cost summary for a domain PRESERVED: Critical cost tracking business logic - complex cost aggregation and analytics

func (*FederationCostRepository) GetFederationCosts

func (r *FederationCostRepository) GetFederationCosts(ctx context.Context, domain string, startTime, endTime time.Time, limit int) ([]*models.FederationCostTracking, error)

GetFederationCosts retrieves federation costs for a domain within a time range PRESERVED: Critical cost tracking business logic - time-based GSI queries with domain filtering

func (*FederationCostRepository) GetFederationCostsByActivityType

func (r *FederationCostRepository) GetFederationCostsByActivityType(ctx context.Context, activityType string, startTime, endTime time.Time, limit int) ([]*models.FederationCostTracking, error)

GetFederationCostsByActivityType retrieves federation costs by activity type within a time range PRESERVED: Critical cost tracking business logic - activity type GSI queries for cost analysis

func (*FederationCostRepository) RecordFederationCost

func (r *FederationCostRepository) RecordFederationCost(ctx context.Context, cost *models.FederationCostTracking) error

RecordFederationCost records a federation cost tracking entry using enhanced patterns

func (*FederationCostRepository) ResetPeriodBudgets

func (r *FederationCostRepository) ResetPeriodBudgets(ctx context.Context, period string, newPeriodStart, newPeriodEnd time.Time) error

ResetPeriodBudgets resets budget usage for a new period PRESERVED: Critical budget lifecycle management - period reset functionality for cost control cycles

func (*FederationCostRepository) UpdateBudgetUsage

func (r *FederationCostRepository) UpdateBudgetUsage(ctx context.Context, domain, period, activityType, direction string, cost int64) error

UpdateBudgetUsage updates the usage for a federation budget PRESERVED: Critical budget enforcement logic - cost attribution, limit checking, status updates

type FederationInstanceRepository

type FederationInstanceRepository struct {
	*EnhancedBaseRepository[*models.FederationInstanceRegistry]
}

FederationInstanceRepository handles federation instance operations using enhanced repository patterns

func NewFederationInstanceRepository

func NewFederationInstanceRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *FederationInstanceRepository

NewFederationInstanceRepository creates a new federation instance repository with enhanced functionality

func (*FederationInstanceRepository) BatchCreateInstances

func (r *FederationInstanceRepository) BatchCreateInstances(ctx context.Context, instances []*types.Instance) error

BatchCreateInstances creates multiple instances efficiently for federation discovery

func (*FederationInstanceRepository) BatchGetInstances

func (r *FederationInstanceRepository) BatchGetInstances(ctx context.Context, instanceIDs []string) ([]*types.Instance, error)

BatchGetInstances retrieves multiple instances efficiently using BaseRepository batch operations

func (*FederationInstanceRepository) BatchUpdateInstancesHealth

func (r *FederationInstanceRepository) BatchUpdateInstancesHealth(ctx context.Context, healthUpdates map[string]*types.HealthStatus) error

BatchUpdateInstancesHealth updates health status for multiple instances efficiently

func (*FederationInstanceRepository) BatchUpdateInstancesUsage

func (r *FederationInstanceRepository) BatchUpdateInstancesUsage(ctx context.Context, usageUpdates map[string]int64) error

BatchUpdateInstancesUsage updates usage counters for multiple instances efficiently

func (*FederationInstanceRepository) CreateInstance

func (r *FederationInstanceRepository) CreateInstance(ctx context.Context, instance *types.Instance) error

CreateInstance registers a new federated instance

func (*FederationInstanceRepository) DeleteInstance

func (r *FederationInstanceRepository) DeleteInstance(ctx context.Context, instanceID string) error

DeleteInstance removes an instance

func (*FederationInstanceRepository) GetHealthHistory

func (r *FederationInstanceRepository) GetHealthHistory(ctx context.Context, instanceID string, duration time.Duration) ([]*types.HealthStatus, error)

GetHealthHistory retrieves health history for an instance

func (*FederationInstanceRepository) GetInstance

func (r *FederationInstanceRepository) GetInstance(ctx context.Context, instanceID string) (*types.Instance, error)

GetInstance retrieves an instance by ID

func (*FederationInstanceRepository) GetInstanceByDomain

func (r *FederationInstanceRepository) GetInstanceByDomain(ctx context.Context, domain string) (*types.Instance, error)

GetInstanceByDomain retrieves an instance by domain name

func (*FederationInstanceRepository) GetInstancesByTier

func (r *FederationInstanceRepository) GetInstancesByTier(ctx context.Context, tier types.TierLevel, limit int) ([]*types.Instance, error)

GetInstancesByTier retrieves instances by tier level using GSI2 (backward compatible)

func (*FederationInstanceRepository) GetInstancesByTierWithCursor

func (r *FederationInstanceRepository) GetInstancesByTierWithCursor(ctx context.Context, tier types.TierLevel, limit int, cursor string) ([]*types.Instance, string, error)

GetInstancesByTierWithCursor retrieves instances by tier level using GSI2 with cursor pagination

func (*FederationInstanceRepository) ListAllInstances

func (r *FederationInstanceRepository) ListAllInstances(ctx context.Context, limit int, startKey map[string]interface{}) ([]*types.Instance, map[string]interface{}, error)

ListAllInstances returns instances while honoring legacy startKey-based pagination

func (*FederationInstanceRepository) ListAllInstancesWithCursor

func (r *FederationInstanceRepository) ListAllInstancesWithCursor(ctx context.Context, limit int, cursor string) ([]*types.Instance, string, error)

ListAllInstancesWithCursor returns instances using internal cursor pagination

func (*FederationInstanceRepository) ListHealthyInstances

func (r *FederationInstanceRepository) ListHealthyInstances(ctx context.Context) ([]*types.Instance, error)

ListHealthyInstances returns all healthy instances

func (*FederationInstanceRepository) ListInstancesByStatus

func (r *FederationInstanceRepository) ListInstancesByStatus(ctx context.Context, status types.InstanceStatus, limit int) ([]*types.Instance, error)

ListInstancesByStatus retrieves instances by status using GSI1 (backward compatible)

func (*FederationInstanceRepository) ListInstancesByStatusWithCursor

func (r *FederationInstanceRepository) ListInstancesByStatusWithCursor(ctx context.Context, status types.InstanceStatus, limit int, cursor string) ([]*types.Instance, string, error)

ListInstancesByStatusWithCursor retrieves instances by status using GSI1 with cursor pagination

func (*FederationInstanceRepository) SearchInstances

func (r *FederationInstanceRepository) SearchInstances(ctx context.Context, domainPattern string, limit int) ([]*types.Instance, error)

SearchInstances searches for instances by domain pattern (backward compatible)

func (*FederationInstanceRepository) SearchInstancesWithCursor

func (r *FederationInstanceRepository) SearchInstancesWithCursor(ctx context.Context, domainPattern string, limit int, cursor string) ([]*types.Instance, string, error)

SearchInstancesWithCursor searches for instances by domain pattern with cursor pagination

func (*FederationInstanceRepository) UpdateInstance

func (r *FederationInstanceRepository) UpdateInstance(ctx context.Context, instance *types.Instance) error

UpdateInstance updates an existing instance

func (*FederationInstanceRepository) UpdateInstanceHealth

func (r *FederationInstanceRepository) UpdateInstanceHealth(ctx context.Context, instanceID string, health *types.HealthStatus) error

UpdateInstanceHealth updates instance health metrics

func (*FederationInstanceRepository) UpdateInstanceUsage

func (r *FederationInstanceRepository) UpdateInstanceUsage(ctx context.Context, instanceID string, bytesUsed int64) error

UpdateInstanceUsage updates usage counters efficiently

type FederationRepository

type FederationRepository struct {
	*EnhancedBaseRepository[*models.FederationCostActivity]
	// contains filtered or unexported fields
}

FederationRepository implements federation tracking operations using enhanced DynamORM patterns

func NewFederationRepository

func NewFederationRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService, cfg *appConfig.Config) *FederationRepository

NewFederationRepository creates a new federation repository with enhanced functionality

func (*FederationRepository) AcknowledgeSeverance

func (r *FederationRepository) AcknowledgeSeverance(ctx context.Context, userID, domain string) error

AcknowledgeSeverance marks a severance as acknowledged by the user

func (*FederationRepository) AddToInbox

func (r *FederationRepository) AddToInbox(ctx context.Context, actorID string, activity *activitypub.Activity) error

AddToInbox adds an activity to an actor's inbox

func (*FederationRepository) AddToOutbox

func (r *FederationRepository) AddToOutbox(ctx context.Context, actorID string, activity *activitypub.Activity, public bool) error

AddToOutbox adds an activity to an actor's outbox

func (*FederationRepository) AggregateFederationMetrics

func (r *FederationRepository) AggregateFederationMetrics(ctx context.Context, domain, fromPeriod, toPeriod string, timestamp time.Time) error

AggregateFederationMetrics aggregates raw metrics into higher-level time buckets

func (*FederationRepository) AttemptReconnection

func (r *FederationRepository) AttemptReconnection(ctx context.Context, userID, domain string) error

AttemptReconnection records an attempt to reconnect to a severed domain

func (*FederationRepository) CalculateFederationClusters

func (r *FederationRepository) CalculateFederationClusters(ctx context.Context) ([]*storage.InstanceCluster, error)

CalculateFederationClusters calculates instance clusters based on connections

func (*FederationRepository) CleanupOldDeliveries

func (r *FederationRepository) CleanupOldDeliveries(_ context.Context, olderThan time.Duration) (int, error)

CleanupOldDeliveries removes old delivery records (called by scheduled job)

func (*FederationRepository) CreateSeveredRelationship

func (r *FederationRepository) CreateSeveredRelationship(ctx context.Context, rel *models.SeveredRelationship) error

CreateSeveredRelationship records a new severed federation relationship

func (*FederationRepository) GetAffectedFollowersCount

func (r *FederationRepository) GetAffectedFollowersCount(ctx context.Context, userID, domain string) (int, error)

GetAffectedFollowersCount returns the count of followers affected by a domain severance This counts how many followers from the specified remote domain were lost when severance occurred

func (*FederationRepository) GetAffectedFollowingCount

func (r *FederationRepository) GetAffectedFollowingCount(ctx context.Context, userID, domain string) (int, error)

GetAffectedFollowingCount returns the count of following relationships affected by a domain severance This counts how many accounts this user was following on the severed domain

func (*FederationRepository) GetAffectedRelationships

func (r *FederationRepository) GetAffectedRelationships(ctx context.Context, userID, domain string) ([]*storage.RelationshipRecord, error)

GetAffectedRelationships returns relationships affected by domain severance

func (*FederationRepository) GetAllFederationEdges

func (r *FederationRepository) GetAllFederationEdges(ctx context.Context, limit int) ([]*storage.FederationEdge, error)

GetAllFederationEdges retrieves all federation edges across all domains with pagination

func (*FederationRepository) GetCostProjections

func (r *FederationRepository) GetCostProjections(ctx context.Context, period string) (*storage.CostProjection, error)

GetCostProjections generates cost projections based on historical data

func (*FederationRepository) GetDeliveryStatus

func (r *FederationRepository) GetDeliveryStatus(ctx context.Context, activityID, targetDomain string) (*storage.DeliveryStatus, error)

GetDeliveryStatus retrieves the delivery status for an activity to a domain

func (*FederationRepository) GetDetailedFederationMetrics

func (r *FederationRepository) GetDetailedFederationMetrics(ctx context.Context, domain, period string, startTime, endTime time.Time) ([]*models.FederationAnalyticsTimeSeries, error)

GetDetailedFederationMetrics retrieves detailed time series data for federation metrics

func (*FederationRepository) GetDetailedMetricsByPeriod

func (r *FederationRepository) GetDetailedMetricsByPeriod(ctx context.Context, period string, startTime, endTime time.Time, limit int) ([]*models.FederationAnalyticsTimeSeries, error)

GetDetailedMetricsByPeriod retrieves detailed time series data across all domains for a specific period

func (*FederationRepository) GetDomainHealthScore

func (r *FederationRepository) GetDomainHealthScore(ctx context.Context, domain string) (float64, error)

GetDomainHealthScore calculates the current health score for a domain

func (*FederationRepository) GetFederationActivitiesByTimeRange

func (r *FederationRepository) GetFederationActivitiesByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.FederationCostActivity, error)

GetFederationActivitiesByTimeRange retrieves federation activities within a time range Queries day-by-day to ensure complete coverage across the time range

func (*FederationRepository) GetFederationAlertsData

func (r *FederationRepository) GetFederationAlertsData(ctx context.Context) ([]models.FederationAlert, error)

GetFederationAlertsData returns domains that should trigger alerts

func (*FederationRepository) GetFederationClusters

func (r *FederationRepository) GetFederationClusters(ctx context.Context, limit int) ([]*storage.InstanceCluster, error)

GetFederationClusters retrieves instance clusters for graph visualization

func (*FederationRepository) GetFederationCosts

func (r *FederationRepository) GetFederationCosts(ctx context.Context, startTime, endTime time.Time, limit int, _ string) ([]*storage.FederationCost, string, error)

GetFederationCosts retrieves aggregated federation costs

func (*FederationRepository) GetFederationCostsByUser

func (r *FederationRepository) GetFederationCostsByUser(ctx context.Context, userID string, startTime, endTime time.Time, limit, offset int) ([]*models.FederationCost, error)

GetFederationCostsByUser returns federation costs for a specific user within a date range

func (*FederationRepository) GetFederationEdges

func (r *FederationRepository) GetFederationEdges(ctx context.Context, domains []string) ([]*storage.FederationEdge, error)

GetFederationEdges retrieves edges between specified domains

func (*FederationRepository) GetFederationNodes

func (r *FederationRepository) GetFederationNodes(ctx context.Context, depth int) ([]*storage.FederationNode, error)

GetFederationNodes retrieves federation nodes up to a certain depth

func (*FederationRepository) GetFederationNodesByHealth

func (r *FederationRepository) GetFederationNodesByHealth(ctx context.Context, healthStatus string, limit int) ([]*storage.FederationNode, error)

GetFederationNodesByHealth retrieves federation nodes filtered by health status

func (*FederationRepository) GetFederationStatistics

func (r *FederationRepository) GetFederationStatistics(ctx context.Context, startTime, endTime time.Time) (*storage.FederationStats, error)

GetFederationStatistics retrieves federation statistics for a time range

func (*FederationRepository) GetInboxItems

func (r *FederationRepository) GetInboxItems(ctx context.Context, actorID string, limit int, cursor string) ([]*activitypub.Activity, string, error)

GetInboxItems retrieves activities from an actor's inbox

func (*FederationRepository) GetInstanceConnections

func (r *FederationRepository) GetInstanceConnections(ctx context.Context, domain string, connectionType string) ([]*storage.InstanceConnection, error)

GetInstanceConnections retrieves connections for a specific instance

func (*FederationRepository) GetInstanceHealthReport

func (r *FederationRepository) GetInstanceHealthReport(ctx context.Context, domain string, period time.Duration) (*storage.InstanceHealthReport, error)

GetInstanceHealthReport generates a health report for a specific instance

func (*FederationRepository) GetInstanceInfo

func (r *FederationRepository) GetInstanceInfo(ctx context.Context, domain string) (*storage.InstanceInfo, error)

GetInstanceInfo retrieves information about a federated instance

func (*FederationRepository) GetInstanceMetadata

func (r *FederationRepository) GetInstanceMetadata(ctx context.Context, domain string) (*storage.InstanceMetadata, error)

GetInstanceMetadata retrieves metadata for a specific instance

func (*FederationRepository) GetInstanceStats

func (r *FederationRepository) GetInstanceStats(ctx context.Context, domain string) (*storage.InstanceStats, error)

GetInstanceStats retrieves comprehensive statistics for a specific instance

func (*FederationRepository) GetKnownInstances

func (r *FederationRepository) GetKnownInstances(ctx context.Context, limit int, _ string) ([]*storage.InstanceInfo, string, error)

GetKnownInstances retrieves a list of known federated instances

func (*FederationRepository) GetOutboxItems

func (r *FederationRepository) GetOutboxItems(ctx context.Context, actorID string, limit int, _ string) ([]*activitypub.Activity, string, error)

GetOutboxItems retrieves activities from an actor's outbox

func (*FederationRepository) GetPublicOutbox

func (r *FederationRepository) GetPublicOutbox(ctx context.Context, actorID string, limit int, cursor string) ([]*activitypub.Activity, string, error)

GetPublicOutbox retrieves only public activities from an actor's outbox

func (*FederationRepository) GetRecentInstanceConnections

func (r *FederationRepository) GetRecentInstanceConnections(ctx context.Context, domain string, since time.Duration) ([]*storage.InstanceConnection, error)

GetRecentInstanceConnections retrieves connections for an instance within a time window

func (*FederationRepository) GetSeveranceHistory

func (r *FederationRepository) GetSeveranceHistory(ctx context.Context, localInstance, remoteInstance string, limit int) ([]*models.SeveredRelationship, error)

GetSeveranceHistory retrieves the history of severances between two instances

func (*FederationRepository) GetSeveredRelationship

func (r *FederationRepository) GetSeveredRelationship(ctx context.Context, localInstance, remoteInstance string) (*models.SeveredRelationship, error)

GetSeveredRelationship retrieves a specific severed relationship

func (*FederationRepository) GetSeveredRelationships

func (r *FederationRepository) GetSeveredRelationships(ctx context.Context, localInstance string, limit int, cursor string) ([]*models.SeveredRelationship, string, error)

GetSeveredRelationships retrieves severed relationships for a local instance

func (*FederationRepository) GetStrongestConnectionsByType

func (r *FederationRepository) GetStrongestConnectionsByType(ctx context.Context, connectionType string, limit int) ([]*storage.FederationEdge, error)

GetStrongestConnectionsByType retrieves the strongest federation connections by type

func (*FederationRepository) GetUnhealthyDomains

func (r *FederationRepository) GetUnhealthyDomains(ctx context.Context, healthThreshold float64) ([]*models.FederationAnalyticsTimeSeries, error)

GetUnhealthyDomains returns domains that are currently unhealthy or critical

func (*FederationRepository) GetUserSeveredRelationships

func (r *FederationRepository) GetUserSeveredRelationships(ctx context.Context, userID string) ([]*storage.SeveredRelationship, error)

GetUserSeveredRelationships returns all severed relationships for a user

func (*FederationRepository) ListFailedDeliveries

func (r *FederationRepository) ListFailedDeliveries(ctx context.Context, limit int) ([]*storage.DeliveryStatus, error)

ListFailedDeliveries retrieves deliveries that need retry

func (*FederationRepository) RecordDeliveryAttempt

func (r *FederationRepository) RecordDeliveryAttempt(ctx context.Context, activityID, targetDomain string, success bool, errorMsg string) error

RecordDeliveryAttempt records a delivery attempt for an activity

func (*FederationRepository) RecordFederationActivity

func (r *FederationRepository) RecordFederationActivity(ctx context.Context, activity *storage.FederationActivity) error

RecordFederationActivity records a single federation activity for cost tracking

func (*FederationRepository) RetryDelivery

func (r *FederationRepository) RetryDelivery(ctx context.Context, activityID, targetDomain string) error

RetryDelivery marks a delivery for immediate retry

func (*FederationRepository) ReverseSeverance

func (r *FederationRepository) ReverseSeverance(ctx context.Context, localInstance, remoteInstance string) error

ReverseSeverance marks a severed relationship as restored

func (*FederationRepository) StoreDetailedFederationMetrics

func (r *FederationRepository) StoreDetailedFederationMetrics(ctx context.Context, metrics *models.FederationAnalyticsTimeSeries) error

StoreDetailedFederationMetrics stores detailed federation time series record with 5-minute aggregation

func (*FederationRepository) StoreFederationTimeSeries

func (r *FederationRepository) StoreFederationTimeSeries(ctx context.Context, data *storage.FederationTimeSeries) error

StoreFederationTimeSeries stores time-series federation metrics

func (*FederationRepository) StoreInstanceCluster

func (r *FederationRepository) StoreInstanceCluster(ctx context.Context, cluster *storage.InstanceCluster) error

StoreInstanceCluster stores a calculated federation cluster

func (*FederationRepository) TrackFederationIssue

func (r *FederationRepository) TrackFederationIssue(ctx context.Context, domain, issueType string) error

TrackFederationIssue records a federation issue for monitoring

func (*FederationRepository) UpdateFederationEdge

func (r *FederationRepository) UpdateFederationEdge(ctx context.Context, edge *storage.FederationEdge) error

UpdateFederationEdge updates or creates a federation edge

func (*FederationRepository) UpdateFederationNode

func (r *FederationRepository) UpdateFederationNode(ctx context.Context, node *storage.FederationNode) error

UpdateFederationNode updates or creates a federation node

func (*FederationRepository) UpdateInstanceMetadata

func (r *FederationRepository) UpdateInstanceMetadata(ctx context.Context, metadata *storage.InstanceMetadata) error

UpdateInstanceMetadata updates instance metadata

func (*FederationRepository) UpdateSeveredRelationship

func (r *FederationRepository) UpdateSeveredRelationship(ctx context.Context, rel *models.SeveredRelationship) error

UpdateSeveredRelationship updates an existing severed relationship

func (*FederationRepository) UpsertInstanceInfo

func (r *FederationRepository) UpsertInstanceInfo(ctx context.Context, info *storage.InstanceInfo) error

UpsertInstanceInfo creates or updates instance information

type FilterItem

type FilterItem interface {
	*models.FilterKeyword | *models.FilterStatus
}

FilterItem defines the interface for filter-related items that can be created

type FilterItemCreatable

type FilterItemCreatable interface {
	GetID() string
	SetID(string)
	SetCreatedAt(time.Time)
	UpdateKeys() error
}

FilterItemCreatable defines the common interface for creatable filter items

type FilterItemDeletable

type FilterItemDeletable interface {
	GetPK() string
	GetSK() string
	GetFilterID() string
	GetItemID() string
}

FilterItemDeletable defines the common interface for deletable filter items

type FilterRepository

type FilterRepository struct {
	*EnhancedBaseRepository[*models.Filter]
	// contains filtered or unexported fields
}

FilterRepository handles user content filtering operations using enhanced DynamORM patterns

func NewFilterRepository

func NewFilterRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *FilterRepository

NewFilterRepository creates a new FilterRepository with enhanced functionality and cost tracking

func (*FilterRepository) AddFilterKeyword

func (r *FilterRepository) AddFilterKeyword(ctx context.Context, keyword *models.FilterKeyword) error

AddFilterKeyword adds a new keyword to a filter

func (*FilterRepository) AddFilterStatus

func (r *FilterRepository) AddFilterStatus(ctx context.Context, filterStatus *models.FilterStatus) error

AddFilterStatus adds a new status to a filter

func (*FilterRepository) CheckContentFiltered

func (r *FilterRepository) CheckContentFiltered(ctx context.Context, username, statusID string, context []string) (bool, []*models.Filter, error)

CheckContentFiltered checks if a specific status is filtered for a user

func (*FilterRepository) CreateFilter

func (r *FilterRepository) CreateFilter(ctx context.Context, filter *models.Filter) error

CreateFilter creates a new filter

func (*FilterRepository) DeleteFilter

func (r *FilterRepository) DeleteFilter(ctx context.Context, filterID string) error

DeleteFilter deletes a filter and all its associated keywords and statuses

func (*FilterRepository) EvaluateFilters

func (r *FilterRepository) EvaluateFilters(ctx context.Context, username string, content string, context []string) ([]*models.Filter, error)

EvaluateFilters evaluates content against user filters

func (*FilterRepository) GetActiveFilters

func (r *FilterRepository) GetActiveFilters(ctx context.Context, username string, context []string) ([]*models.Filter, error)

GetActiveFilters retrieves active filters for a user in specific contexts

func (*FilterRepository) GetFilter

func (r *FilterRepository) GetFilter(ctx context.Context, filterID string) (*models.Filter, error)

GetFilter retrieves a filter by ID

func (*FilterRepository) GetFilterKeywords

func (r *FilterRepository) GetFilterKeywords(ctx context.Context, filterID string) ([]*models.FilterKeyword, error)

GetFilterKeywords retrieves all keywords for a filter

func (*FilterRepository) GetFilterStatuses

func (r *FilterRepository) GetFilterStatuses(ctx context.Context, filterID string) ([]*models.FilterStatus, error)

GetFilterStatuses retrieves all statuses for a filter

func (*FilterRepository) GetUserFilters

func (r *FilterRepository) GetUserFilters(ctx context.Context, username string) ([]*models.Filter, error)

GetUserFilters retrieves all filters for a user

func (*FilterRepository) RemoveFilterKeyword

func (r *FilterRepository) RemoveFilterKeyword(ctx context.Context, keywordID string) error

RemoveFilterKeyword removes a filter keyword

func (*FilterRepository) RemoveFilterStatus

func (r *FilterRepository) RemoveFilterStatus(ctx context.Context, filterStatusID string) error

RemoveFilterStatus removes a filter status by its ID

func (*FilterRepository) UpdateFilter

func (r *FilterRepository) UpdateFilter(ctx context.Context, filter *models.Filter) error

UpdateFilter updates a filter

type GSIKeyUtils

type GSIKeyUtils struct{}

GSIKeyUtils provides utilities for generating GSI keys

func NewGSIKeyUtils

func NewGSIKeyUtils() *GSIKeyUtils

NewGSIKeyUtils creates a new GSIKeyUtils instance

func (*GSIKeyUtils) DomainIndexKey

func (g *GSIKeyUtils) DomainIndexKey(domain string) string

DomainIndexKey generates a domain index key: DOMAIN#{domain}

func (*GSIKeyUtils) EmailIndexKey

func (g *GSIKeyUtils) EmailIndexKey(email string) string

EmailIndexKey generates an email index key: EMAIL#{email}

func (*GSIKeyUtils) StatusIndexKey

func (g *GSIKeyUtils) StatusIndexKey(status string) string

StatusIndexKey generates a status index key: STATUS#{status}

func (*GSIKeyUtils) UserIndexKey

func (g *GSIKeyUtils) UserIndexKey(username string) string

UserIndexKey generates a user index key: USER#{username}

type GSIQueryConfig

type GSIQueryConfig struct {
	PKField   string // GSI PK field name (e.g., "gsi1PK", "gsi2PK")
	SKField   string // GSI SK field name (e.g., "gsi1SK", "gsi2SK")
	PKValue   string // PK value for the GSI
	SKPattern string // SK pattern (for BEGINS_WITH, range queries, etc.)
	UseCursor bool   // Enables cursor-based pagination on the configured sort key
	OrderBy   string // Sort order (SortOrderAsc or SortOrderDesc)
}

GSIQueryConfig configures GSI-specific query behavior

type HashtagFollowUpdateConfig

type HashtagFollowUpdateConfig struct {
	Operation   string // "notification", "mute", "unmute"
	BoolValue   *bool  // For notification setting or mute/unmute
	ErrorPrefix string // Error message prefix
}

HashtagFollowUpdateConfig holds configuration for hashtag follow updates

type HashtagRepository

type HashtagRepository struct {
	*EnhancedBaseRepository[*models.Hashtag]
	// contains filtered or unexported fields
}

HashtagRepository implements hashtag-related database operations using enhanced DynamORM patterns

func NewHashtagRepository

func NewHashtagRepository(db core.DB, tableName string, logger *zap.Logger, domain string) *HashtagRepository

NewHashtagRepository creates a new hashtag repository

func (*HashtagRepository) BatchCreateHashtagTrends

func (r *HashtagRepository) BatchCreateHashtagTrends(ctx context.Context, trends []*storage.TrendingHashtag) error

BatchCreateHashtagTrends creates multiple hashtag trend records efficiently

func (*HashtagRepository) DeleteOldHashtagTrends

func (r *HashtagRepository) DeleteOldHashtagTrends(ctx context.Context, before time.Time) error

DeleteOldHashtagTrends deletes hashtag trend records older than the specified time

func (*HashtagRepository) FollowHashtag

func (r *HashtagRepository) FollowHashtag(ctx context.Context, userID, hashtag string) error

FollowHashtag creates a hashtag follow relationship

func (*HashtagRepository) GetFollowedHashtags

func (r *HashtagRepository) GetFollowedHashtags(ctx context.Context, userID string, limit int, cursor string) ([]*storage.HashtagFollow, string, error)

GetFollowedHashtags retrieves hashtags followed by a user

func (*HashtagRepository) GetHashtagActivity

func (r *HashtagRepository) GetHashtagActivity(_ context.Context, hashtag string, since time.Time) ([]*storage.Activity, error)

GetHashtagActivity retrieves activities for a hashtag since a specific time

func (*HashtagRepository) GetHashtagFollow

func (r *HashtagRepository) GetHashtagFollow(ctx context.Context, userID string, hashtag string) (*models.HashtagFollow, error)

GetHashtagFollow retrieves the hashtag follow record for a user

func (*HashtagRepository) GetHashtagInfo

func (r *HashtagRepository) GetHashtagInfo(ctx context.Context, hashtag string) (*storage.Hashtag, error)

GetHashtagInfo retrieves information about a specific hashtag

func (*HashtagRepository) GetHashtagMute

func (r *HashtagRepository) GetHashtagMute(ctx context.Context, userID string, hashtag string) (*models.HashtagMute, error)

GetHashtagMute retrieves the hashtag mute record for a user

func (*HashtagRepository) GetHashtagNotificationSettings

func (r *HashtagRepository) GetHashtagNotificationSettings(ctx context.Context, userID, hashtag string) (*storage.HashtagNotificationSettings, error)

GetHashtagNotificationSettings retrieves notification preferences for a hashtag

func (*HashtagRepository) GetHashtagStats

func (r *HashtagRepository) GetHashtagStats(ctx context.Context, hashtag string) (any, error)

GetHashtagStats retrieves hashtag statistics

func (*HashtagRepository) GetHashtagTimelineAdvanced

func (r *HashtagRepository) GetHashtagTimelineAdvanced(ctx context.Context, hashtag string, maxID *string, limit int, visibility string) ([]*storage.StatusSearchResult, error)

GetHashtagTimelineAdvanced retrieves hashtag timeline with advanced filtering using efficient indexing

func (*HashtagRepository) GetHashtagTrendingHistory

func (r *HashtagRepository) GetHashtagTrendingHistory(_ context.Context, _ string, _ int) ([]*TrendingScore, error)

GetHashtagTrendingHistory returns historical trending data for a hashtag

func (*HashtagRepository) GetHashtagTrendsByScore

func (r *HashtagRepository) GetHashtagTrendsByScore(ctx context.Context, date time.Time, limit int, ascending bool) ([]*storage.TrendingHashtag, error)

GetHashtagTrendsByScore retrieves trending hashtags ordered by trend score

func (*HashtagRepository) GetHashtagUsageHistory

func (r *HashtagRepository) GetHashtagUsageHistory(ctx context.Context, hashtag string, days int) ([]int64, error)

GetHashtagUsageHistory retrieves recent usage history for a hashtag

func (*HashtagRepository) GetHashtagsByTimeRange

func (r *HashtagRepository) GetHashtagsByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*storage.TrendingHashtag, error)

GetHashtagsByTimeRange retrieves hashtags within a specific time range

func (*HashtagRepository) GetMultiHashtagTimeline

func (r *HashtagRepository) GetMultiHashtagTimeline(ctx context.Context, hashtags []string, maxID *string, limit int, userID string) ([]*storage.StatusSearchResult, error)

GetMultiHashtagTimeline retrieves timeline for multiple hashtags

func (*HashtagRepository) GetRecentHashtags

func (r *HashtagRepository) GetRecentHashtags(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

GetRecentHashtags returns hashtags that have been recently used

func (*HashtagRepository) GetSuggestedHashtags

func (r *HashtagRepository) GetSuggestedHashtags(ctx context.Context, userID string, limit int) ([]*storage.HashtagSearchResult, error)

GetSuggestedHashtags gets suggested hashtags for a user

func (*HashtagRepository) GetTrendingAnalytics

func (r *HashtagRepository) GetTrendingAnalytics(ctx context.Context, since time.Time) (*TrendingAnalytics, error)

GetTrendingAnalytics provides aggregated analytics for trending hashtags

func (*HashtagRepository) GetTrendingCalculatorConfig

func (r *HashtagRepository) GetTrendingCalculatorConfig() TrendingCalculatorConfig

GetTrendingCalculatorConfig returns the current trending calculator configuration

func (*HashtagRepository) GetTrendingHashtags

func (r *HashtagRepository) GetTrendingHashtags(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

GetTrendingHashtags returns trending hashtags using sophisticated scoring algorithms

func (*HashtagRepository) GetTrendingHashtagsAdvanced

func (r *HashtagRepository) GetTrendingHashtagsAdvanced(ctx context.Context, config TrendingCalculatorConfig, limit int) ([]*storage.TrendingHashtag, error)

GetTrendingHashtagsAdvanced allows custom configuration for trending calculation

func (*HashtagRepository) IndexHashtag

func (r *HashtagRepository) IndexHashtag(ctx context.Context, hashtag string, statusID string, authorID string, visibility string) error

IndexHashtag indexes a hashtag when used in a status

func (*HashtagRepository) IndexStatusHashtags

func (r *HashtagRepository) IndexStatusHashtags(ctx context.Context, statusID string, authorID string, authorHandle string, statusURL string, content string, hashtags []string, published time.Time, visibility string) error

IndexStatusHashtags indexes a status with its hashtags for efficient search

func (*HashtagRepository) IsFollowingHashtag

func (r *HashtagRepository) IsFollowingHashtag(ctx context.Context, userID, hashtag string) (bool, error)

IsFollowingHashtag checks if a user is following a hashtag

func (*HashtagRepository) IsHashtagMuted

func (r *HashtagRepository) IsHashtagMuted(ctx context.Context, userID, hashtag string) (bool, error)

IsHashtagMuted checks if a hashtag is muted for a user

func (*HashtagRepository) MuteHashtag

func (r *HashtagRepository) MuteHashtag(ctx context.Context, userID, hashtag string, until *time.Time) error

MuteHashtag mutes a hashtag for a user

func (*HashtagRepository) ReconfigureTrendingCalculator

func (r *HashtagRepository) ReconfigureTrendingCalculator(config TrendingCalculatorConfig)

ReconfigureTrendingCalculator updates the trending calculator configuration

func (*HashtagRepository) RemoveStatusFromHashtagIndex

func (r *HashtagRepository) RemoveStatusFromHashtagIndex(ctx context.Context, statusID string) error

RemoveStatusFromHashtagIndex removes a status from all hashtag indexes

func (*HashtagRepository) StoreHashtagTrend

func (r *HashtagRepository) StoreHashtagTrend(_ context.Context, trendData any) error

StoreHashtagTrend stores trending data for a hashtag

func (*HashtagRepository) UnfollowHashtag

func (r *HashtagRepository) UnfollowHashtag(ctx context.Context, userID, hashtag string) error

UnfollowHashtag removes a hashtag follow relationship and related artifacts

func (*HashtagRepository) UnmuteHashtag

func (r *HashtagRepository) UnmuteHashtag(ctx context.Context, userID, hashtag string) error

UnmuteHashtag unmutes a hashtag for a user

func (*HashtagRepository) UpdateHashtagNotificationSettings

func (r *HashtagRepository) UpdateHashtagNotificationSettings(ctx context.Context, userID, hashtag string, settings *storage.HashtagNotificationSettings) error

UpdateHashtagNotificationSettings updates notification settings for a hashtag

type HistoryQueryConfig

type HistoryQueryConfig struct {
	MetricType  string                                   // The metric type (e.g., "storage_bytes", "user_count")
	IndexName   string                                   // GSI index name
	PKField     string                                   // GSI PK field name
	SKField     string                                   // GSI SK field name
	LogName     string                                   // Name for logging
	ErrorPrefix string                                   // Error message prefix
	Converter   func(interface{}) map[string]interface{} // Custom field converter
}

HistoryQueryConfig configures behavior for history/metrics query operations

type ImportExportItem

type ImportExportItem interface {
	GetStatus() string
	GetCreatedAt() time.Time
}

ImportExportItem interface for models that support import/export operations

type ImportExportMetrics

type ImportExportMetrics struct {
	StartDate                 time.Time `json:"start_date"`
	EndDate                   time.Time `json:"end_date"`
	TotalOperations           int64     `json:"total_operations"`
	TotalImportOperations     int64     `json:"total_import_operations"`
	TotalExportOperations     int64     `json:"total_export_operations"`
	TotalCostMicroCents       int64     `json:"total_cost_micro_cents"`
	TotalImportCostMicroCents int64     `json:"total_import_cost_micro_cents"`
	TotalExportCostMicroCents int64     `json:"total_export_cost_micro_cents"`
	TotalCostDollars          float64   `json:"total_cost_dollars"`
	TotalImportCostDollars    float64   `json:"total_import_cost_dollars"`
	TotalExportCostDollars    float64   `json:"total_export_cost_dollars"`
	AverageCostPerOperation   float64   `json:"average_cost_per_operation"`
	AverageImportCost         float64   `json:"average_import_cost"`
	AverageExportCost         float64   `json:"average_export_cost"`
	OperationsPerDollar       float64   `json:"operations_per_dollar"`
	ImportCostPercentage      float64   `json:"import_cost_percentage"`
	ExportCostPercentage      float64   `json:"export_cost_percentage"`
}

ImportExportMetrics represents key metrics for import/export operations

type ImportExportTrends

type ImportExportTrends struct {
	StartTime     time.Time  `json:"start_time"`
	EndTime       time.Time  `json:"end_time"`
	ImportTrend   *CostTrend `json:"import_trend"`
	ExportTrend   *CostTrend `json:"export_trend"`
	CombinedTrend *CostTrend `json:"combined_trend"`
}

ImportExportTrends represents cost trends for import/export operations

type ImportExportUserCostSummary

type ImportExportUserCostSummary struct {
	Username      string            `json:"username"`
	StartDate     time.Time         `json:"start_date"`
	EndDate       time.Time         `json:"end_date"`
	ImportCosts   *UserServiceCosts `json:"import_costs"`
	ExportCosts   *UserServiceCosts `json:"export_costs"`
	CombinedCosts *UserServiceCosts `json:"combined_costs"`
}

ImportExportUserCostSummary represents cost summary for a user's import/export operations

type ImportRepository

type ImportRepository struct {
	// contains filtered or unexported fields
}

ImportRepository handles import-related database operations using DynamORM

func NewImportRepository

func NewImportRepository(db core.DB, tableName string, logger *zap.Logger) *ImportRepository

NewImportRepository creates a new import repository

func (*ImportRepository) CheckBudgetLimits

func (r *ImportRepository) CheckBudgetLimits(ctx context.Context, username string, importCostMicroCents, exportCostMicroCents int64) (*models.ImportBudget, bool, error)

CheckBudgetLimits checks if a user is within their budget limits

func (*ImportRepository) CreateImport

func (r *ImportRepository) CreateImport(_ context.Context, importRecord *models.Import) error

CreateImport creates a new import record

func (*ImportRepository) CreateImportBudget

func (r *ImportRepository) CreateImportBudget(_ context.Context, budget *models.ImportBudget) error

CreateImportBudget creates a new import budget configuration

func (*ImportRepository) CreateImportCostTracking

func (r *ImportRepository) CreateImportCostTracking(_ context.Context, costTracking *models.ImportCostTracking) error

CreateImportCostTracking creates a new import cost tracking record

func (*ImportRepository) GetHighCostImports

func (r *ImportRepository) GetHighCostImports(ctx context.Context, thresholdMicroCents int64, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

GetHighCostImports returns import operations that exceed a cost threshold

func (*ImportRepository) GetImport

func (r *ImportRepository) GetImport(_ context.Context, importID string) (*models.Import, error)

GetImport retrieves an import by ID

func (*ImportRepository) GetImportBudget

func (r *ImportRepository) GetImportBudget(_ context.Context, username, period string) (*models.ImportBudget, error)

GetImportBudget retrieves import budget configuration for a user

func (*ImportRepository) GetImportCostSummary

func (r *ImportRepository) GetImportCostSummary(ctx context.Context, username string, startDate, endDate time.Time) (*models.ImportCostSummary, error)

GetImportCostSummary calculates cost summary for a user's imports

func (*ImportRepository) GetImportCostTracking

func (r *ImportRepository) GetImportCostTracking(_ context.Context, importID string) ([]*models.ImportCostTracking, error)

GetImportCostTracking retrieves import cost tracking records for an import

func (*ImportRepository) GetImportCostsByDateRange

func (r *ImportRepository) GetImportCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

GetImportCostsByDateRange retrieves import costs for all users within a date range

func (*ImportRepository) GetImportsForUser

func (r *ImportRepository) GetImportsForUser(ctx context.Context, username string, limit int, cursor string) ([]*models.Import, string, error)

GetImportsForUser retrieves all imports for a user

func (*ImportRepository) GetUserImportCosts

func (r *ImportRepository) GetUserImportCosts(ctx context.Context, username string, startDate, endDate time.Time, limit int) ([]*models.ImportCostTracking, error)

GetUserImportCosts retrieves import costs for a user within a date range

func (*ImportRepository) GetUserImportsByStatus

func (r *ImportRepository) GetUserImportsByStatus(ctx context.Context, username string, statuses []string) ([]*models.Import, error)

GetUserImportsByStatus retrieves imports for a user filtered by status

func (*ImportRepository) UpdateBudgetUsage

func (r *ImportRepository) UpdateBudgetUsage(ctx context.Context, username, period string, importCostMicroCents, exportCostMicroCents int64) error

UpdateBudgetUsage updates the current usage for a user's budget

func (*ImportRepository) UpdateImportBudget

func (r *ImportRepository) UpdateImportBudget(_ context.Context, budget *models.ImportBudget) error

UpdateImportBudget updates an existing import budget

func (*ImportRepository) UpdateImportProgress

func (r *ImportRepository) UpdateImportProgress(ctx context.Context, importID string, progress int) error

UpdateImportProgress updates the progress of an import

func (*ImportRepository) UpdateImportStatus

func (r *ImportRepository) UpdateImportStatus(ctx context.Context, importID, status string, completionData map[string]any, errorMsg string) error

UpdateImportStatus updates the status and metadata of an import

type InMemoryCachingService

type InMemoryCachingService struct {
	// contains filtered or unexported fields
}

InMemoryCachingService provides a simple in-memory cache implementation

func NewInMemoryCachingService

func NewInMemoryCachingService() *InMemoryCachingService

NewInMemoryCachingService creates a new in-memory caching service

func (*InMemoryCachingService) Delete

Delete removes a value from the cache

func (*InMemoryCachingService) Get

func (c *InMemoryCachingService) Get(_ context.Context, key string, dest interface{}) error

Get retrieves a value from the cache

func (*InMemoryCachingService) InvalidatePattern

func (c *InMemoryCachingService) InvalidatePattern(_ context.Context, pattern string) error

InvalidatePattern removes all cache entries matching a pattern

func (*InMemoryCachingService) Set

func (c *InMemoryCachingService) Set(_ context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value in the cache with TTL

type InstanceHealthRepository

type InstanceHealthRepository struct {
	*EnhancedBaseRepository[*models.InstanceHealth]
	// contains filtered or unexported fields
}

InstanceHealthRepository handles health check data using BaseRepository with DynamORM

func NewInstanceHealthRepository

func NewInstanceHealthRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *InstanceHealthRepository

NewInstanceHealthRepository creates a new instance health repository with enhanced functionality

func (*InstanceHealthRepository) CalculateHealthSummary

func (r *InstanceHealthRepository) CalculateHealthSummary(ctx context.Context, domain string, window time.Duration) (*models.InstanceHealthSummary, error)

CalculateHealthSummary aggregates health data and creates a summary

func (*InstanceHealthRepository) CleanupOldHealthData

func (r *InstanceHealthRepository) CleanupOldHealthData(_ context.Context, olderThan time.Duration) (int, error)

CleanupOldHealthData removes health data older than the specified duration

func (*InstanceHealthRepository) GetDomainsForHealthCheck

func (r *InstanceHealthRepository) GetDomainsForHealthCheck(ctx context.Context, limit int) ([]string, error)

GetDomainsForHealthCheck retrieves a list of domains that need health checking with monitoring prioritization

func (*InstanceHealthRepository) GetHealthHistory

func (r *InstanceHealthRepository) GetHealthHistory(ctx context.Context, domain string, since time.Time, limit int) ([]*models.InstanceHealth, error)

GetHealthHistory retrieves health history for a domain within a time range with trend analysis

func (*InstanceHealthRepository) GetHealthSummary

func (r *InstanceHealthRepository) GetHealthSummary(ctx context.Context, domain string, window time.Duration) (*models.InstanceHealthSummary, error)

GetHealthSummary retrieves an aggregated health summary with uptime status reporting

func (*InstanceHealthRepository) GetLatestHealthCheck

func (r *InstanceHealthRepository) GetLatestHealthCheck(ctx context.Context, domain string) (*models.InstanceHealth, error)

GetLatestHealthCheck retrieves the most recent health check for a domain with health status logging

func (*InstanceHealthRepository) GetUnhealthyInstances

func (r *InstanceHealthRepository) GetUnhealthyInstances(ctx context.Context, threshold float64) ([]string, error)

GetUnhealthyInstances returns instances that are currently unhealthy with detailed health status analysis

func (*InstanceHealthRepository) SaveHealthCheck

func (r *InstanceHealthRepository) SaveHealthCheck(ctx context.Context, health *models.InstanceHealth) error

SaveHealthCheck stores a health check result with health validation and alerting logic

func (*InstanceHealthRepository) SaveHealthChecks

func (r *InstanceHealthRepository) SaveHealthChecks(ctx context.Context, healthChecks []*models.InstanceHealth) error

SaveHealthChecks saves multiple health checks in batch with health monitoring validation

func (*InstanceHealthRepository) SaveHealthSummary

func (r *InstanceHealthRepository) SaveHealthSummary(ctx context.Context, summary *models.InstanceHealthSummary) error

SaveHealthSummary saves an aggregated health summary with uptime monitoring alerts

type InstanceInfoItem

type InstanceInfoItem struct {
	PK string `theorydb:"pk"`
	SK string `theorydb:"sk"`

	Domain      string    `json:"domain"`
	Software    string    `json:"software,omitempty"`
	Version     string    `json:"version,omitempty"`
	PublicKey   string    `json:"public_key,omitempty"`
	SharedInbox string    `json:"shared_inbox,omitempty"`
	LastSeen    time.Time `json:"last_seen"`
	FirstSeen   time.Time `json:"first_seen"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

InstanceInfoItem represents instance information in DynamoDB

func (*InstanceInfoItem) BeforeCreate

func (i *InstanceInfoItem) BeforeCreate() error

BeforeCreate for InstanceInfoItem

func (*InstanceInfoItem) BeforeUpdate

func (i *InstanceInfoItem) BeforeUpdate() error

BeforeUpdate for InstanceInfoItem

func (InstanceInfoItem) TableName

func (InstanceInfoItem) TableName() string

TableName returns the DynamoDB table name

type InstanceRepository

type InstanceRepository struct {
	*EnhancedBaseRepository[*models.InstanceConfig]
	// contains filtered or unexported fields
}

InstanceRepository implements instance operations using enhanced DynamORM patterns

func NewInstanceRepository

func NewInstanceRepository(db core.DB, tableName string, logger *zap.Logger) *InstanceRepository

NewInstanceRepository creates a new instance repository with enhanced functionality

func NewInstanceRepositoryWithCostTracking

func NewInstanceRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *InstanceRepository

NewInstanceRepositoryWithCostTracking creates a new instance repository with cost tracking

func (*InstanceRepository) EnsureAgentInstanceConfig

func (r *InstanceRepository) EnsureAgentInstanceConfig(ctx context.Context) (*models.AgentInstanceConfig, error)

EnsureAgentInstanceConfig ensures the instance agent policy record exists and returns it.

func (*InstanceRepository) EnsureInstanceState

func (r *InstanceRepository) EnsureInstanceState(ctx context.Context) (*models.InstanceState, error)

EnsureInstanceState ensures the instance state record exists and returns it.

func (*InstanceRepository) GetActiveUserCount

func (r *InstanceRepository) GetActiveUserCount(ctx context.Context, days int) (int64, error)

GetActiveUserCount returns the number of active users in the last N days

func (*InstanceRepository) GetAgentInstanceConfig

func (r *InstanceRepository) GetAgentInstanceConfig(ctx context.Context) (*models.AgentInstanceConfig, error)

GetAgentInstanceConfig returns the current instance agent policy. If no record exists yet, it returns conservative defaults without persisting.

func (*InstanceRepository) GetContactAccount

func (r *InstanceRepository) GetContactAccount(ctx context.Context) (*storage.ActorRecord, error)

GetContactAccount returns the contact account for the instance This returns the first admin user as the contact account

func (*InstanceRepository) GetDailyActiveUserCount

func (r *InstanceRepository) GetDailyActiveUserCount(ctx context.Context) (int64, error)

GetDailyActiveUserCount returns the number of daily active users

func (*InstanceRepository) GetDomainStats

func (r *InstanceRepository) GetDomainStats(ctx context.Context, domain string) (any, error)

GetDomainStats returns statistics for a specific domain

func (*InstanceRepository) GetExtendedDescription

func (r *InstanceRepository) GetExtendedDescription(ctx context.Context) (string, time.Time, error)

GetExtendedDescription retrieves the instance extended description Matches legacy: PK="INSTANCE#CONFIG", SK="EXTENDED_DESC", returns default if not set

func (*InstanceRepository) GetInstanceRules

func (r *InstanceRepository) GetInstanceRules(ctx context.Context) ([]storage.InstanceRule, error)

GetInstanceRules retrieves the instance rules Matches legacy: PK="INSTANCE#CONFIG", SK="RULES"

func (*InstanceRepository) GetInstanceState

func (r *InstanceRepository) GetInstanceState(ctx context.Context) (*models.InstanceState, error)

GetInstanceState returns the current instance activation state. If no state exists yet, it defaults to a locked state without persisting.

func (*InstanceRepository) GetLocalCommentCount

func (r *InstanceRepository) GetLocalCommentCount(ctx context.Context) (int64, error)

GetLocalCommentCount returns the number of local comments (posts with InReplyToID)

func (*InstanceRepository) GetLocalPostCount

func (r *InstanceRepository) GetLocalPostCount(ctx context.Context) (int64, error)

GetLocalPostCount returns the number of local posts

func (*InstanceRepository) GetMetricsSummary

func (r *InstanceRepository) GetMetricsSummary(ctx context.Context, timeRange string) (map[string]interface{}, error)

GetMetricsSummary returns aggregated metrics for a given time range

func (*InstanceRepository) GetRulesByCategory

func (r *InstanceRepository) GetRulesByCategory(ctx context.Context, category string) ([]storage.InstanceRule, error)

GetRulesByCategory retrieves rules filtered by category Since legacy doesn't implement this, we'll use the instance rules model with category filtering

func (*InstanceRepository) GetStorageHistory

func (r *InstanceRepository) GetStorageHistory(ctx context.Context, days int) ([]any, error)

GetStorageHistory returns storage usage history for the last N days

func (*InstanceRepository) GetStorageUsage

func (r *InstanceRepository) GetStorageUsage(ctx context.Context) (any, error)

GetStorageUsage returns current storage usage statistics

func (*InstanceRepository) GetTotalDomainCount

func (r *InstanceRepository) GetTotalDomainCount(ctx context.Context) (int64, error)

GetTotalDomainCount returns the total number of known domains

func (*InstanceRepository) GetTotalStatusCount

func (r *InstanceRepository) GetTotalStatusCount(ctx context.Context) (int64, error)

GetTotalStatusCount returns the total number of statuses

func (*InstanceRepository) GetTotalUserCount

func (r *InstanceRepository) GetTotalUserCount(ctx context.Context) (int64, error)

GetTotalUserCount returns the total number of users Since legacy doesn't implement this, use instance metrics pattern

func (*InstanceRepository) GetUserGrowthHistory

func (r *InstanceRepository) GetUserGrowthHistory(ctx context.Context, days int) ([]any, error)

GetUserGrowthHistory returns user growth data for the last N days

func (*InstanceRepository) GetWeeklyActivity

func (r *InstanceRepository) GetWeeklyActivity(ctx context.Context, weekTimestamp int64) (*storage.WeeklyActivity, error)

GetWeeklyActivity retrieves weekly activity data for a specific week

func (*InstanceRepository) RecordActivity

func (r *InstanceRepository) RecordActivity(ctx context.Context, activityType string, _ string, timestamp time.Time) error

RecordActivity records activity data for analytics

func (*InstanceRepository) RecordDailyMetrics

func (r *InstanceRepository) RecordDailyMetrics(ctx context.Context, date string, metrics map[string]interface{}) error

RecordDailyMetrics records daily historical metrics for the instance

func (*InstanceRepository) SetAgentInstanceConfig

func (r *InstanceRepository) SetAgentInstanceConfig(ctx context.Context, cfg *models.AgentInstanceConfig) error

SetAgentInstanceConfig updates the instance agent policy.

func (*InstanceRepository) SetBootstrapWalletAddress

func (r *InstanceRepository) SetBootstrapWalletAddress(ctx context.Context, address string) error

SetBootstrapWalletAddress sets the bootstrap wallet address used for setup authentication.

func (*InstanceRepository) SetExtendedDescription

func (r *InstanceRepository) SetExtendedDescription(ctx context.Context, description string) error

SetExtendedDescription updates the instance extended description Matches legacy: PK="INSTANCE#CONFIG", SK="EXTENDED_DESC"

func (*InstanceRepository) SetInstanceLocked

func (r *InstanceRepository) SetInstanceLocked(ctx context.Context, locked bool) error

SetInstanceLocked updates the instance lock state.

func (*InstanceRepository) SetInstanceRules

func (r *InstanceRepository) SetInstanceRules(ctx context.Context, rules []storage.InstanceRule) error

SetInstanceRules updates the instance rules Matches legacy: assigns IDs if not present, PK="INSTANCE#CONFIG", SK="RULES"

func (*InstanceRepository) SetPrimaryAdminUsername

func (r *InstanceRepository) SetPrimaryAdminUsername(ctx context.Context, username string) error

SetPrimaryAdminUsername records the primary admin username created during setup.

type JobCategoryStats

type JobCategoryStats struct {
	Category                string
	ExecutionCount          int64
	SuccessfulExecutions    int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	TotalDurationMs         int64
	AverageCostPerExecution float64
	AverageDurationMs       float64
	SuccessRate             float64
}

JobCategoryStats represents statistics for a job category

type JobExecutionStats

type JobExecutionStats struct {
	JobName        string
	Schedule       string
	StartTime      time.Time
	EndTime        time.Time
	TotalRuns      int
	SuccessfulRuns int64
	FailedRuns     int64
	SuccessRate    float64

	AverageDurationMs   float64
	AverageCostDollars  float64
	TotalCostDollars    float64
	TotalCostMicroCents int64

	TotalItemsProcessed        int64
	TotalItemsErrored          int64
	TotalLambdaInvocations     int64
	TotalLambdaDurationMs      int64
	CostPerItemProcessed       float64
	CostPerSuccessfulExecution float64

	StatusBreakdown     map[string]int64
	CategoryBreakdown   map[string]*JobCategoryStats
	DurationPercentiles map[string]float64
	CostPercentiles     map[string]float64
}

JobExecutionStats represents execution statistics for a job

type JobPerformanceDataPoint

type JobPerformanceDataPoint struct {
	Date                    time.Time
	TotalExecutions         int64
	SuccessfulExecutions    int64
	FailedExecutions        int64
	TotalCostDollars        float64
	TotalDurationMs         int64
	TotalItemsProcessed     int64
	AverageCostPerExecution float64
	AverageDurationMs       float64
	CostPerItemProcessed    float64
	SuccessRate             float64
}

JobPerformanceDataPoint represents a single data point in the performance trend

type JobPerformanceTrend

type JobPerformanceTrend struct {
	JobName                    string
	Schedule                   string
	StartTime                  time.Time
	EndTime                    time.Time
	DataPoints                 []JobPerformanceDataPoint
	CostTrendPercentage        float64
	DurationTrendPercentage    float64
	SuccessRateTrendPercentage float64
}

JobPerformanceTrend represents performance trends for a job over time

type JobSummaryStats

type JobSummaryStats struct {
	JobName                 string
	ExecutionCount          int64
	SuccessfulExecutions    int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	TotalDurationMs         int64
	AverageCostPerExecution float64
	AverageDurationMs       float64
	SuccessRate             float64
}

JobSummaryStats represents summary statistics for a job

type KeyUtils

type KeyUtils struct{}

KeyUtils provides utilities for generating consistent DynamoDB keys

func NewKeyUtils

func NewKeyUtils() *KeyUtils

NewKeyUtils creates a new KeyUtils instance

func (*KeyUtils) ActorKey

func (k *KeyUtils) ActorKey(username string) string

ActorKey generates an actor primary key: ACTOR#{username}

func (*KeyUtils) AuthCodeKey

func (k *KeyUtils) AuthCodeKey(code string) string

AuthCodeKey generates an authorization code primary key: AUTH_CODE#{code}

func (*KeyUtils) BlockKey

func (k *KeyUtils) BlockKey(username string) string

BlockKey generates a block primary key: ACTOR#{username}#BLOCKS

func (*KeyUtils) BlockedSK

func (k *KeyUtils) BlockedSK(blockedUsername string) string

BlockedSK generates a blocked sort key: BLOCKED#{username}

func (*KeyUtils) FollowKey

func (k *KeyUtils) FollowKey(followerUsername string) string

FollowKey generates a follow primary key: follow#{follower}

func (*KeyUtils) FollowingSK

func (k *KeyUtils) FollowingSK(followedUsername string) string

FollowingSK generates a following sort key: following#{followed}

func (*KeyUtils) HashtagKey

func (k *KeyUtils) HashtagKey(tag string) string

HashtagKey generates a hashtag primary key: HASHTAG#{tag}

func (*KeyUtils) ListKey

func (k *KeyUtils) ListKey(listID string) string

ListKey generates a list primary key: LIST#{listID}

func (*KeyUtils) MuteKey

func (k *KeyUtils) MuteKey(username string) string

MuteKey generates a mute primary key: MUTE#{username}

func (*KeyUtils) MutedSK

func (k *KeyUtils) MutedSK(mutedUsername string) string

MutedSK generates a muted sort key: MUTED#{username}

func (*KeyUtils) OAuthStateKey

func (k *KeyUtils) OAuthStateKey(state string) string

OAuthStateKey generates an OAuth state primary key: OAUTH_STATE#{state}

func (*KeyUtils) ObjectKey

func (k *KeyUtils) ObjectKey(objectID string) string

ObjectKey generates an object primary key: object#{id}

func (*KeyUtils) RefreshTokenKey

func (k *KeyUtils) RefreshTokenKey(token string) string

RefreshTokenKey generates a refresh token primary key: REFRESH_TOKEN#{token}

func (*KeyUtils) UserKey

func (k *KeyUtils) UserKey(username string) string

UserKey generates a user primary key: USER#{username}

func (*KeyUtils) WalletKey

func (k *KeyUtils) WalletKey(address string) string

WalletKey generates a wallet primary key: WALLET#{address}

func (*KeyUtils) WebAuthnCredentialKey

func (k *KeyUtils) WebAuthnCredentialKey(credentialID string) string

WebAuthnCredentialKey generates a WebAuthn credential primary key: WEBAUTHN_CREDENTIAL#{id}

type LikeRepository

type LikeRepository struct {
	*EnhancedBaseRepository[*models.Like]
}

LikeRepository implements like operations using enhanced DynamORM patterns

func NewLikeRepository

func NewLikeRepository(db core.DB, tableName string, logger *zap.Logger) *LikeRepository

NewLikeRepository creates a new like repository with enhanced functionality

func NewLikeRepositoryWithCostTracking

func NewLikeRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *LikeRepository

NewLikeRepositoryWithCostTracking creates a new like repository with cost tracking

func (*LikeRepository) CascadeDeleteLikes

func (r *LikeRepository) CascadeDeleteLikes(ctx context.Context, objectID string) error

CascadeDeleteLikes deletes all likes for an object

func (*LikeRepository) CheckLikesForStatuses added in v1.1.1

func (r *LikeRepository) CheckLikesForStatuses(ctx context.Context, actorID string, statusIDs []string) (map[string]bool, error)

CheckLikesForStatuses returns a map of statusID -> liked for the provided IDs.

func (*LikeRepository) CountActorLikes

func (r *LikeRepository) CountActorLikes(ctx context.Context, actorID string) (int64, error)

CountActorLikes returns the total number of likes by an actor

func (*LikeRepository) CountForObject

func (r *LikeRepository) CountForObject(ctx context.Context, objectID string) (int64, error)

CountForObject provides Storage interface compatibility for CountObjectLikes

func (*LikeRepository) CreateLike

func (r *LikeRepository) CreateLike(ctx context.Context, actor, object, statusAuthorID string) (*models.Like, error)

CreateLike creates a new like with enhanced validation and event emission

func (*LikeRepository) DeleteLike

func (r *LikeRepository) DeleteLike(ctx context.Context, actor, object string) error

DeleteLike removes a like

func (*LikeRepository) GetActorLikes

func (r *LikeRepository) GetActorLikes(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Like, string, error)

GetActorLikes retrieves all likes by an actor

func (*LikeRepository) GetBoostCount

func (r *LikeRepository) GetBoostCount(ctx context.Context, statusID string) (int64, error)

GetBoostCount counts boosts/announces for a status

func (*LikeRepository) GetForObject

func (r *LikeRepository) GetForObject(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Like, string, error)

GetForObject provides Storage interface compatibility for GetObjectLikes

func (*LikeRepository) GetLike

func (r *LikeRepository) GetLike(ctx context.Context, actor, object string) (*models.Like, error)

GetLike retrieves a specific like

func (*LikeRepository) GetLikeCount

func (r *LikeRepository) GetLikeCount(ctx context.Context, statusID string) (int64, error)

GetLikeCount counts likes for a status

func (*LikeRepository) GetLikedObjects

func (r *LikeRepository) GetLikedObjects(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Like, string, error)

GetLikedObjects provides Storage interface compatibility (already exists as GetActorLikes with different name)

func (*LikeRepository) GetObjectLikes

func (r *LikeRepository) GetObjectLikes(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Like, string, error)

GetObjectLikes retrieves all likes for an object

func (*LikeRepository) GetTombstone

func (r *LikeRepository) GetTombstone(ctx context.Context, objectID string) (*storage.Tombstone, error)

GetTombstone retrieves a tombstone by object ID

func (*LikeRepository) HasLiked

func (r *LikeRepository) HasLiked(ctx context.Context, actor, object string) (bool, error)

HasLiked checks if an actor has liked an object

func (*LikeRepository) HasReblogged

func (r *LikeRepository) HasReblogged(ctx context.Context, actorID, statusID string) (bool, error)

HasReblogged checks if a user has reblogged/boosted a specific status

func (*LikeRepository) IncrementReblogCount

func (r *LikeRepository) IncrementReblogCount(ctx context.Context, objectID string) error

IncrementReblogCount increments the reblog count on a status

func (*LikeRepository) TombstoneObject

func (r *LikeRepository) TombstoneObject(ctx context.Context, objectID string, deletedBy string) error

TombstoneObject creates a tombstone for a deleted object

type LinearRegressionStats

type LinearRegressionStats struct {
	Slope           float64 `json:"slope"`            // Rate of change per time unit
	Intercept       float64 `json:"intercept"`        // Y-intercept
	RSquared        float64 `json:"r_squared"`        // Coefficient of determination (0-1)
	Correlation     float64 `json:"correlation"`      // Correlation coefficient (-1 to 1)
	SlopeStdError   float64 `json:"slope_std_error"`  // Standard error of slope
	TStatistic      float64 `json:"t_statistic"`      // T-statistic for slope
	PValue          float64 `json:"p_value"`          // P-value for slope significance
	ConfidenceLevel float64 `json:"confidence_level"` // Confidence level (e.g., 0.95)
	TrendDirection  string  `json:"trend_direction"`  // "increasing", "decreasing", "stable"
	TrendStrength   string  `json:"trend_strength"`   // "weak", "moderate", "strong"
	IsSignificant   bool    `json:"is_significant"`   // Whether trend is statistically significant
}

LinearRegressionStats represents linear regression analysis results

type ListRepository

type ListRepository struct {
	*EnhancedBaseRepository[*models.List]
	// contains filtered or unexported fields
}

ListRepository handles list-related database operations using enhanced patterns

func NewListRepository

func NewListRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ListRepository

NewListRepository creates a new list repository with enhanced functionality

func (*ListRepository) AddAccountsToList

func (r *ListRepository) AddAccountsToList(ctx context.Context, listID string, accountIDs []string) error

AddAccountsToList adds multiple accounts to a list

func (*ListRepository) AddListMember

func (r *ListRepository) AddListMember(ctx context.Context, listID, memberUsername string) error

AddListMember adds a member to a list

func (*ListRepository) CountListMembers

func (r *ListRepository) CountListMembers(ctx context.Context, listID string) (int, error)

CountListMembers counts the number of members in a list

func (*ListRepository) CountUserLists

func (r *ListRepository) CountUserLists(ctx context.Context, username string) (int, error)

CountUserLists counts the number of lists owned by a user

func (*ListRepository) CreateList

func (r *ListRepository) CreateList(ctx context.Context, list *models.List) error

CreateList creates a new list

func (*ListRepository) DeleteList

func (r *ListRepository) DeleteList(ctx context.Context, listID string) error

DeleteList deletes a list and all its memberships

func (*ListRepository) GetAccountLists

func (r *ListRepository) GetAccountLists(ctx context.Context, accountID string) ([]*storage.List, error)

GetAccountLists retrieves all lists that contain an account (for backward compatibility)

func (*ListRepository) GetAccountListsForUser

func (r *ListRepository) GetAccountListsForUser(ctx context.Context, accountID, username string) ([]*storage.List, error)

GetAccountListsForUser retrieves all lists (for a specific user) that contain an account

func (*ListRepository) GetAccountListsPaginated

func (r *ListRepository) GetAccountListsPaginated(ctx context.Context, accountID string, limit int, cursor string) ([]*storage.List, string, error)

GetAccountListsPaginated retrieves lists that contain an account with pagination

func (*ListRepository) GetExclusiveLists

func (r *ListRepository) GetExclusiveLists(ctx context.Context, username string) ([]*storage.List, error)

GetExclusiveLists retrieves all exclusive lists for a user

func (*ListRepository) GetList

func (r *ListRepository) GetList(ctx context.Context, listID string) (*models.List, error)

GetList retrieves a list by ID

func (*ListRepository) GetListAccounts

func (r *ListRepository) GetListAccounts(ctx context.Context, listID string) ([]string, error)

GetListAccounts retrieves all account IDs in a list

func (*ListRepository) GetListMembers

GetListMembers retrieves paginated list members GetListMembers gets members of a list with pagination

func (*ListRepository) GetListStatuses

GetListStatuses is an alias for GetListTimeline (both return statuses from list members)

func (*ListRepository) GetListTimeline

GetListTimeline retrieves the timeline for a list

func (*ListRepository) GetListsByMember

func (r *ListRepository) GetListsByMember(ctx context.Context, memberUsername string, opts interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.List], error)

GetListsByMember gets all lists that contain a specific member

func (*ListRepository) GetListsContainingAccount

func (r *ListRepository) GetListsContainingAccount(ctx context.Context, accountID, username string) ([]*storage.List, error)

GetListsContainingAccount is an alias for GetAccountListsForUser

func (*ListRepository) GetListsForUser

func (r *ListRepository) GetListsForUser(ctx context.Context, username string) ([]*storage.List, error)

GetListsForUser retrieves all lists owned by a user (for backward compatibility)

func (*ListRepository) GetListsForUserPaginated

func (r *ListRepository) GetListsForUserPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.List, string, error)

GetListsForUserPaginated retrieves lists owned by a user with pagination

func (*ListRepository) GetUserLists

GetUserLists is an alias for GetListsForUser GetUserLists gets all lists owned by a user with pagination

func (*ListRepository) IsListMember

func (r *ListRepository) IsListMember(ctx context.Context, listID, memberUsername string) (bool, error)

IsListMember checks if a user is a member of a list

func (*ListRepository) RemoveAccountFromAllLists

func (r *ListRepository) RemoveAccountFromAllLists(ctx context.Context, accountID string) error

RemoveAccountFromAllLists removes an account from all lists

func (*ListRepository) RemoveAccountsFromList

func (r *ListRepository) RemoveAccountsFromList(ctx context.Context, listID string, accountIDs []string) error

RemoveAccountsFromList removes multiple accounts from a list

func (*ListRepository) RemoveListMember

func (r *ListRepository) RemoveListMember(ctx context.Context, listID, memberUsername string) error

RemoveListMember removes a member from a list

func (*ListRepository) UpdateList

func (r *ListRepository) UpdateList(ctx context.Context, list *models.List) error

UpdateList updates a list's properties

type LogEventHandler

type LogEventHandler struct {
	// contains filtered or unexported fields
}

LogEventHandler logs all events (useful for debugging)

func NewLogEventHandler

func NewLogEventHandler() *LogEventHandler

NewLogEventHandler creates a new log event handler

func (*LogEventHandler) Handle

func (h *LogEventHandler) Handle(_ context.Context, event Event) error

Handle logs the event

type MarkerRepository

type MarkerRepository struct {
	*EnhancedBaseRepository[*models.Marker]
}

MarkerRepository implements marker operations using enhanced DynamORM patterns

func NewMarkerRepository

func NewMarkerRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MarkerRepository

NewMarkerRepository creates a new marker repository with enhanced functionality and cost tracking

func (*MarkerRepository) GetMarkers

func (r *MarkerRepository) GetMarkers(ctx context.Context, username string, timelines []string) (map[string]*storage.Marker, error)

GetMarkers retrieves timeline position markers for specified timelines

func (*MarkerRepository) SaveMarker

func (r *MarkerRepository) SaveMarker(ctx context.Context, username, timeline string, lastReadID string, version int) error

SaveMarker saves or updates a timeline position marker

type MediaAnalyticsRepository

type MediaAnalyticsRepository struct {
	*EnhancedBaseRepository[*models.MediaAnalytics]
}

MediaAnalyticsRepository handles media analytics operations using DynamORM with BaseRepository

func NewMediaAnalyticsRepository

func NewMediaAnalyticsRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MediaAnalyticsRepository

NewMediaAnalyticsRepository creates a new media analytics repository with enhanced functionality

func (*MediaAnalyticsRepository) CalculatePopularityMetrics

func (r *MediaAnalyticsRepository) CalculatePopularityMetrics(ctx context.Context, mediaID string, days int) (map[string]interface{}, error)

CalculatePopularityMetrics calculates content popularity metrics with trending algorithms

func (*MediaAnalyticsRepository) CleanupOldAnalytics

func (r *MediaAnalyticsRepository) CleanupOldAnalytics(ctx context.Context, olderThan time.Duration) error

CleanupOldAnalytics removes analytics records older than the specified duration preserving business intelligence data

func (*MediaAnalyticsRepository) GenerateAnalyticsReport

func (r *MediaAnalyticsRepository) GenerateAnalyticsReport(ctx context.Context, startDate, endDate string) (map[string]interface{}, error)

GenerateAnalyticsReport generates comprehensive analytics report with business intelligence

func (*MediaAnalyticsRepository) GetAllMediaAnalyticsByTimeRange

func (r *MediaAnalyticsRepository) GetAllMediaAnalyticsByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)

GetAllMediaAnalyticsByTimeRange retrieves analytics for all media within time range

func (*MediaAnalyticsRepository) GetBandwidthByTimeRange

func (r *MediaAnalyticsRepository) GetBandwidthByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)

GetBandwidthByTimeRange retrieves bandwidth usage data within time range

func (*MediaAnalyticsRepository) GetContentRecommendations

func (r *MediaAnalyticsRepository) GetContentRecommendations(ctx context.Context, userID string, limit int) ([]map[string]interface{}, error)

GetContentRecommendations generates ML-based content recommendations

func (*MediaAnalyticsRepository) GetDailyCostSummary

func (r *MediaAnalyticsRepository) GetDailyCostSummary(ctx context.Context, date string) (map[string]interface{}, error)

GetDailyCostSummary retrieves cost summary for a specific date with business intelligence aggregation

func (*MediaAnalyticsRepository) GetMediaAnalyticsByDate

func (r *MediaAnalyticsRepository) GetMediaAnalyticsByDate(ctx context.Context, date string) ([]*models.MediaAnalytics, error)

GetMediaAnalyticsByDate retrieves media analytics for a specific date with engagement data

func (*MediaAnalyticsRepository) GetMediaAnalyticsByID

func (r *MediaAnalyticsRepository) GetMediaAnalyticsByID(ctx context.Context, format string, timestamp time.Time, mediaID string) (*models.MediaAnalytics, error)

GetMediaAnalyticsByID retrieves media analytics by media ID and timestamp

func (*MediaAnalyticsRepository) GetMediaAnalyticsByTimeRange

func (r *MediaAnalyticsRepository) GetMediaAnalyticsByTimeRange(ctx context.Context, mediaID string, startTime, endTime time.Time, limit int) ([]*models.MediaAnalytics, error)

GetMediaAnalyticsByTimeRange retrieves analytics for a specific media within time range

func (*MediaAnalyticsRepository) GetMediaAnalyticsByVariant

func (r *MediaAnalyticsRepository) GetMediaAnalyticsByVariant(ctx context.Context, variantKey string) ([]*models.MediaAnalytics, error)

GetMediaAnalyticsByVariant retrieves media analytics for a specific variant with performance metrics

func (*MediaAnalyticsRepository) GetMediaMetricsForDate

func (r *MediaAnalyticsRepository) GetMediaMetricsForDate(ctx context.Context, mediaID, date string) (map[string]interface{}, error)

GetMediaMetricsForDate gets metrics for a specific media item on a specific date

func (*MediaAnalyticsRepository) GetPopularMedia

func (r *MediaAnalyticsRepository) GetPopularMedia(_ context.Context, _, _ time.Time, _ int, _ *string) ([]*models.MediaAnalytics, error)

GetPopularMedia retrieves popular media sorted by view count with cursor pagination NOTE: Deprecated in favor of service layer using GetPopularMediaByPeriod from PopularityRepository This method is kept for backward compatibility but should not be used

func (*MediaAnalyticsRepository) GetTopVariantsByDemand

func (r *MediaAnalyticsRepository) GetTopVariantsByDemand(ctx context.Context, date string, limit int) ([]map[string]interface{}, error)

GetTopVariantsByDemand retrieves the most popular variants by viewer count with recommendation algorithms

func (*MediaAnalyticsRepository) RecordMediaAnalytics

func (r *MediaAnalyticsRepository) RecordMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error

RecordMediaAnalytics records a media analytics entry with comprehensive engagement tracking

func (*MediaAnalyticsRepository) RecordMediaView

func (r *MediaAnalyticsRepository) RecordMediaView(ctx context.Context, mediaID, userID string, duration time.Duration, quality string) error

RecordMediaView tracks media view events with user engagement analytics

func (*MediaAnalyticsRepository) StoreMediaAnalytics

func (r *MediaAnalyticsRepository) StoreMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error

StoreMediaAnalytics stores a media analytics event NOTE: Popularity updates are now handled by the service layer (RecordStreamingEvent) which calls MediaPopularityRepository.IncrementViewCount directly

func (*MediaAnalyticsRepository) TrackUserBehavior

func (r *MediaAnalyticsRepository) TrackUserBehavior(ctx context.Context, userID string, behaviorData map[string]interface{}) error

TrackUserBehavior analyzes user behavior patterns for personalization

func (*MediaAnalyticsRepository) UpdateMediaAnalytics

func (r *MediaAnalyticsRepository) UpdateMediaAnalytics(ctx context.Context, analytics *models.MediaAnalytics) error

UpdateMediaAnalytics updates an existing media analytics record with engagement metrics

type MediaMetadataRepository

type MediaMetadataRepository struct {
	*EnhancedBaseRepository[*models.MediaMetadata]
}

MediaMetadataRepository handles media metadata operations using enhanced DynamORM patterns

func NewMediaMetadataRepository

func NewMediaMetadataRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MediaMetadataRepository

NewMediaMetadataRepository creates a new media metadata repository with enhanced functionality and cost tracking

func (*MediaMetadataRepository) CleanupExpiredMetadata

func (r *MediaMetadataRepository) CleanupExpiredMetadata(ctx context.Context) error

CleanupExpiredMetadata cleans up expired media metadata records This is media cleanup business logic - preserve ALL cleanup functionality for failed media

func (*MediaMetadataRepository) CreateMediaMetadata

func (r *MediaMetadataRepository) CreateMediaMetadata(ctx context.Context, metadata *models.MediaMetadata) error

CreateMediaMetadata creates a new media metadata record

func (*MediaMetadataRepository) DeleteMediaMetadata

func (r *MediaMetadataRepository) DeleteMediaMetadata(ctx context.Context, mediaID string) error

DeleteMediaMetadata deletes media metadata by media ID

func (*MediaMetadataRepository) GetMediaMetadata

func (r *MediaMetadataRepository) GetMediaMetadata(ctx context.Context, mediaID string) (*models.MediaMetadata, error)

GetMediaMetadata retrieves media metadata by media ID

func (*MediaMetadataRepository) GetMediaMetadataByStatus

func (r *MediaMetadataRepository) GetMediaMetadataByStatus(ctx context.Context, status string, limit int) ([]*models.MediaMetadata, error)

GetMediaMetadataByStatus retrieves media metadata records by processing status using GSI

func (*MediaMetadataRepository) GetPendingMediaMetadata

func (r *MediaMetadataRepository) GetPendingMediaMetadata(ctx context.Context, limit int) ([]*models.MediaMetadata, error)

GetPendingMediaMetadata retrieves media metadata records that need processing

func (*MediaMetadataRepository) GetProcessingMediaMetadata

func (r *MediaMetadataRepository) GetProcessingMediaMetadata(ctx context.Context, limit int) ([]*models.MediaMetadata, error)

GetProcessingMediaMetadata retrieves media metadata records currently being processed

func (*MediaMetadataRepository) MarkProcessingComplete

func (r *MediaMetadataRepository) MarkProcessingComplete(ctx context.Context, mediaID string, result ProcessingResult) error

MarkProcessingComplete marks media metadata as processing complete with results This is media processing business logic - preserve ALL functionality including thumbnail/EXIF data

func (*MediaMetadataRepository) MarkProcessingFailed

func (r *MediaMetadataRepository) MarkProcessingFailed(ctx context.Context, mediaID string, errorMsg string) error

MarkProcessingFailed marks media metadata as processing failed This is media processing business logic - preserve ALL error handling functionality

func (*MediaMetadataRepository) MarkProcessingStarted

func (r *MediaMetadataRepository) MarkProcessingStarted(ctx context.Context, mediaID string) error

MarkProcessingStarted marks media metadata as processing started This is media processing business logic - preserve complete functionality

func (*MediaMetadataRepository) UpdateMediaMetadata

func (r *MediaMetadataRepository) UpdateMediaMetadata(ctx context.Context, metadata *models.MediaMetadata) error

UpdateMediaMetadata updates an existing media metadata record

type MediaPopularityRepository

type MediaPopularityRepository struct {
	*EnhancedBaseRepository[*models.MediaPopularity]
}

MediaPopularityRepository handles media popularity aggregates using DynamORM

func NewMediaPopularityRepository

func NewMediaPopularityRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MediaPopularityRepository

NewMediaPopularityRepository creates a new media popularity repository

func (*MediaPopularityRepository) GetPopularMediaByPeriod

func (r *MediaPopularityRepository) GetPopularMediaByPeriod(ctx context.Context, period string, limit int, cursor *string) ([]*models.MediaPopularity, error)

GetPopularMediaByPeriod retrieves popular media for a given period with cursor pagination Queries GSI1 which is sorted by inverted view count for descending popularity order

func (*MediaPopularityRepository) GetPopularityForMedia

func (r *MediaPopularityRepository) GetPopularityForMedia(ctx context.Context, mediaID, period string) (*models.MediaPopularity, error)

GetPopularityForMedia retrieves popularity record for specific media

func (*MediaPopularityRepository) IncrementViewCount

func (r *MediaPopularityRepository) IncrementViewCount(ctx context.Context, mediaID, period string, incrementBy int64) error

IncrementViewCount atomically increments view count for media

func (*MediaPopularityRepository) UpsertPopularity

func (r *MediaPopularityRepository) UpsertPopularity(ctx context.Context, popularity *models.MediaPopularity) error

UpsertPopularity creates or updates media popularity record

type MediaRepository

type MediaRepository struct {
	*EnhancedBaseRepository[*models.Media]
	// contains filtered or unexported fields
}

MediaRepository handles media and media job operations using enhanced DynamORM patterns

func NewMediaRepository

func NewMediaRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MediaRepository

NewMediaRepository creates a new MediaRepository with enhanced functionality and cost tracking

func (*MediaRepository) AddMediaVariant

func (r *MediaRepository) AddMediaVariant(ctx context.Context, mediaID, variantName string, variant models.MediaVariant) error

AddMediaVariant adds a variant to a media item

func (*MediaRepository) AddSpendingTransaction

func (r *MediaRepository) AddSpendingTransaction(ctx context.Context, transaction *models.MediaSpendingTransaction) error

AddSpendingTransaction adds a transaction and updates the spending record

func (*MediaRepository) CreateMedia

func (r *MediaRepository) CreateMedia(ctx context.Context, media *models.Media) error

CreateMedia creates a new media record

func (*MediaRepository) CreateMediaJob

func (r *MediaRepository) CreateMediaJob(ctx context.Context, job *models.MediaJob) error

CreateMediaJob creates a new media processing job

func (*MediaRepository) CreateMediaSpending

func (r *MediaRepository) CreateMediaSpending(ctx context.Context, spending *models.MediaSpending) error

CreateMediaSpending creates a new media spending record

func (*MediaRepository) CreateMediaSpendingTransaction

func (r *MediaRepository) CreateMediaSpendingTransaction(ctx context.Context, transaction *models.MediaSpendingTransaction) error

CreateMediaSpendingTransaction creates a new spending transaction

func (*MediaRepository) CreateTranscodingJob

func (r *MediaRepository) CreateTranscodingJob(ctx context.Context, job *models.TranscodingJob) error

CreateTranscodingJob creates a new transcoding job record

func (*MediaRepository) CreateUserMediaConfig

func (r *MediaRepository) CreateUserMediaConfig(ctx context.Context, config *models.UserMediaConfig) error

CreateUserMediaConfig creates a new user media configuration

func (*MediaRepository) DeleteExpiredMedia

func (r *MediaRepository) DeleteExpiredMedia(ctx context.Context, expiredBefore time.Time) (int64, error)

DeleteExpiredMedia deletes media items that have expired

func (*MediaRepository) DeleteMedia

func (r *MediaRepository) DeleteMedia(ctx context.Context, mediaID string) error

DeleteMedia deletes a media record

func (*MediaRepository) DeleteMediaJob

func (r *MediaRepository) DeleteMediaJob(ctx context.Context, jobID string) error

DeleteMediaJob deletes a media job

func (*MediaRepository) DeleteMediaVariant

func (r *MediaRepository) DeleteMediaVariant(ctx context.Context, mediaID, variantName string) error

DeleteMediaVariant removes a variant from a media item

func (*MediaRepository) DeleteTranscodingJob

func (r *MediaRepository) DeleteTranscodingJob(ctx context.Context, jobID string) error

DeleteTranscodingJob deletes a transcoding job

func (*MediaRepository) DeleteUserMediaConfig

func (r *MediaRepository) DeleteUserMediaConfig(ctx context.Context, userID string) error

DeleteUserMediaConfig deletes a user's media configuration

func (*MediaRepository) GetJobsByStatus

func (r *MediaRepository) GetJobsByStatus(ctx context.Context, status string, limit int) ([]*models.MediaJob, error)

GetJobsByStatus retrieves jobs by status

func (*MediaRepository) GetJobsByUser

func (r *MediaRepository) GetJobsByUser(ctx context.Context, username string, limit int) ([]*models.MediaJob, error)

GetJobsByUser retrieves jobs for a specific user

func (*MediaRepository) GetMedia

func (r *MediaRepository) GetMedia(ctx context.Context, mediaID string) (*models.Media, error)

GetMedia retrieves a media record by ID

func (*MediaRepository) GetMediaByContentType

func (r *MediaRepository) GetMediaByContentType(ctx context.Context, contentType string, limit int) ([]*models.Media, error)

GetMediaByContentType retrieves media records by content type

func (*MediaRepository) GetMediaByIDs

func (r *MediaRepository) GetMediaByIDs(ctx context.Context, mediaIDs []string) ([]*models.Media, error)

GetMediaByIDs retrieves multiple media items by their IDs

func (*MediaRepository) GetMediaByStatus

func (r *MediaRepository) GetMediaByStatus(ctx context.Context, status string, limit int) ([]*models.Media, error)

GetMediaByStatus retrieves media records by processing status

func (*MediaRepository) GetMediaByUser

func (r *MediaRepository) GetMediaByUser(ctx context.Context, userID string, limit int) ([]*models.Media, error)

GetMediaByUser retrieves media records for a specific user

func (*MediaRepository) GetMediaJob

func (r *MediaRepository) GetMediaJob(ctx context.Context, jobID string) (*models.MediaJob, error)

GetMediaJob retrieves a media job by ID

func (*MediaRepository) GetMediaSpending

func (r *MediaRepository) GetMediaSpending(ctx context.Context, userID, period string) (*models.MediaSpending, error)

GetMediaSpending retrieves a media spending record for a user and period

func (*MediaRepository) GetMediaSpendingByTimeRange

func (r *MediaRepository) GetMediaSpendingByTimeRange(ctx context.Context, userID string, periodType string, limit int) ([]*models.MediaSpending, error)

GetMediaSpendingByTimeRange retrieves spending records for a user within a time range

func (*MediaRepository) GetMediaSpendingTransactions

func (r *MediaRepository) GetMediaSpendingTransactions(ctx context.Context, userID string, limit int) ([]*models.MediaSpendingTransaction, error)

GetMediaSpendingTransactions retrieves spending transactions for a user

func (*MediaRepository) GetMediaStorageUsage

func (r *MediaRepository) GetMediaStorageUsage(ctx context.Context, userID string) (int64, error)

GetMediaStorageUsage returns the total storage used by a user's media

func (*MediaRepository) GetMediaUsageStats

func (r *MediaRepository) GetMediaUsageStats(ctx context.Context, mediaID string) (usageCount int, lastUsed *time.Time, err error)

GetMediaUsageStats returns usage statistics for a media item

func (*MediaRepository) GetMediaVariant

func (r *MediaRepository) GetMediaVariant(ctx context.Context, mediaID, variantName string) (*models.MediaVariant, error)

GetMediaVariant retrieves a specific variant of a media item

func (*MediaRepository) GetModerationPendingMedia

GetModerationPendingMedia retrieves media items that need moderation review

func (*MediaRepository) GetOrCreateMediaSpending

func (r *MediaRepository) GetOrCreateMediaSpending(ctx context.Context, userID, period, periodType string) (*models.MediaSpending, error)

GetOrCreateMediaSpending gets an existing spending record or creates a new one

func (*MediaRepository) GetPendingMedia

GetPendingMedia retrieves media items with pending status

func (*MediaRepository) GetProcessingMedia

GetProcessingMedia retrieves media items with processing status

func (*MediaRepository) GetTotalStorageUsage

func (r *MediaRepository) GetTotalStorageUsage(ctx context.Context) (int64, error)

GetTotalStorageUsage returns the total storage used by all media in the system

func (*MediaRepository) GetTranscodingCostsByUser

func (r *MediaRepository) GetTranscodingCostsByUser(ctx context.Context, userID string, timeRange string) (map[string]int64, error)

GetTranscodingCostsByUser retrieves aggregated transcoding costs for a user

func (*MediaRepository) GetTranscodingJob

func (r *MediaRepository) GetTranscodingJob(ctx context.Context, jobID string) (*models.TranscodingJob, error)

GetTranscodingJob retrieves a transcoding job by ID

func (*MediaRepository) GetTranscodingJobsByMedia

func (r *MediaRepository) GetTranscodingJobsByMedia(ctx context.Context, mediaID string, limit int) ([]*models.TranscodingJob, error)

GetTranscodingJobsByMedia retrieves transcoding jobs for a specific media item

func (*MediaRepository) GetTranscodingJobsByStatus

func (r *MediaRepository) GetTranscodingJobsByStatus(ctx context.Context, status string, limit int) ([]*models.TranscodingJob, error)

GetTranscodingJobsByStatus retrieves transcoding jobs by status

func (*MediaRepository) GetTranscodingJobsByUser

func (r *MediaRepository) GetTranscodingJobsByUser(ctx context.Context, userID string, limit int) ([]*models.TranscodingJob, error)

GetTranscodingJobsByUser retrieves transcoding jobs for a specific user

func (*MediaRepository) GetUnusedMedia

GetUnusedMedia retrieves media that hasn't been used since a specific time

func (*MediaRepository) GetUserMedia

GetUserMedia retrieves media for a user with pagination (interface compatible)

func (*MediaRepository) GetUserMediaByType

func (r *MediaRepository) GetUserMediaByType(ctx context.Context, userID, contentType string, opts interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.Media], error)

GetUserMediaByType retrieves media for a user filtered by content type

func (*MediaRepository) GetUserMediaConfig

func (r *MediaRepository) GetUserMediaConfig(ctx context.Context, userID string) (*models.UserMediaConfig, error)

GetUserMediaConfig retrieves a user's media configuration

func (*MediaRepository) GetUserMediaConfigByUsername

func (r *MediaRepository) GetUserMediaConfigByUsername(ctx context.Context, username string) (*models.UserMediaConfig, error)

GetUserMediaConfigByUsername retrieves a user's media configuration by username

func (*MediaRepository) GetUserMediaLegacy

func (r *MediaRepository) GetUserMediaLegacy(ctx context.Context, username string) ([]any, error)

GetUserMediaLegacy retrieves media records for a user (for legacy interface compatibility)

func (*MediaRepository) MarkMediaFailed

func (r *MediaRepository) MarkMediaFailed(ctx context.Context, mediaID, errorMsg string) error

MarkMediaFailed marks a media item as failed with an error message

func (*MediaRepository) MarkMediaProcessing

func (r *MediaRepository) MarkMediaProcessing(ctx context.Context, mediaID string) error

MarkMediaProcessing marks a media item as currently being processed

func (*MediaRepository) MarkMediaReady

func (r *MediaRepository) MarkMediaReady(ctx context.Context, mediaID string) error

MarkMediaReady marks a media item as successfully processed and ready

func (*MediaRepository) MarkMediaUsed

func (r *MediaRepository) MarkMediaUsed(ctx context.Context, mediaID string) error

MarkMediaUsed marks a media item as used (increments usage count)

func (*MediaRepository) SetCostService

func (r *MediaRepository) SetCostService(costService *cost.TrackingService)

SetCostService allows setting or updating the cost service

func (*MediaRepository) SetDependencies

func (r *MediaRepository) SetDependencies(deps map[string]interface{})

SetDependencies sets repository dependencies for cross-repo operations

func (*MediaRepository) SetMediaModeration

func (r *MediaRepository) SetMediaModeration(ctx context.Context, mediaID string, isNSFW bool, score float64, labels []string) error

SetMediaModeration sets moderation results for a media item

func (*MediaRepository) TrackQuery

func (r *MediaRepository) TrackQuery(ctx context.Context, indexName string, readUnits int64, itemCount int64) error

TrackQuery tracks query operations with item count and potential GSI usage

func (*MediaRepository) TrackRead

func (r *MediaRepository) TrackRead(ctx context.Context, operationType string, readUnits int64) error

TrackRead provides a simple way to track read operations

func (*MediaRepository) TrackWrite

func (r *MediaRepository) TrackWrite(ctx context.Context, operationType string, writeUnits int64) error

TrackWrite provides a simple way to track write operations

func (*MediaRepository) UnmarkAllMediaAsSensitive

func (r *MediaRepository) UnmarkAllMediaAsSensitive(ctx context.Context, username string) error

UnmarkAllMediaAsSensitive unmarks all media for a user as non-sensitive

func (*MediaRepository) UpdateMedia

func (r *MediaRepository) UpdateMedia(ctx context.Context, media *models.Media) error

UpdateMedia updates an existing media record

func (*MediaRepository) UpdateMediaAttachment

func (r *MediaRepository) UpdateMediaAttachment(ctx context.Context, mediaID string, updates map[string]any) error

UpdateMediaAttachment updates a media attachment (for interface compatibility)

func (*MediaRepository) UpdateMediaJob

func (r *MediaRepository) UpdateMediaJob(ctx context.Context, job *models.MediaJob) error

UpdateMediaJob updates an existing media job

func (*MediaRepository) UpdateMediaSpending

func (r *MediaRepository) UpdateMediaSpending(ctx context.Context, spending *models.MediaSpending) error

UpdateMediaSpending updates an existing media spending record

func (*MediaRepository) UpdateTranscodingJob

func (r *MediaRepository) UpdateTranscodingJob(ctx context.Context, job *models.TranscodingJob) error

UpdateTranscodingJob updates an existing transcoding job

func (*MediaRepository) UpdateUserMediaConfig

func (r *MediaRepository) UpdateUserMediaConfig(ctx context.Context, config *models.UserMediaConfig) error

UpdateUserMediaConfig updates an existing user media configuration

type MediaRepositoryInterface

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

MediaRepositoryInterface defines the interface for media operations

type MediaSessionRepository

type MediaSessionRepository struct {
	*EnhancedBaseRepository[*models.MediaSession]
	// contains filtered or unexported fields
}

MediaSessionRepository implements session management using DynamORM with BaseRepository

func NewMediaSessionRepository

func NewMediaSessionRepository(db core.DB, logger *zap.Logger, _ interface{}) *MediaSessionRepository

NewMediaSessionRepository creates a new MediaSessionRepository

func NewMediaSessionRepositoryWithCostTracking

func NewMediaSessionRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MediaSessionRepository

NewMediaSessionRepositoryWithCostTracking creates a new MediaSessionRepository with cost tracking

func (*MediaSessionRepository) CleanupExpiredSessions

func (r *MediaSessionRepository) CleanupExpiredSessions(ctx context.Context, maxAge time.Duration) error

CleanupExpiredSessions removes sessions older than the specified duration

func (*MediaSessionRepository) CreateSession

func (r *MediaSessionRepository) CreateSession(ctx context.Context, session *types.StreamingSession) error

CreateSession creates a new streaming session (legacy compatibility)

func (*MediaSessionRepository) EndSession

func (r *MediaSessionRepository) EndSession(ctx context.Context, sessionID string) error

EndSession marks a session as ended (legacy compatibility)

func (*MediaSessionRepository) EndStreamingSession

func (r *MediaSessionRepository) EndStreamingSession(ctx context.Context, sessionID string) error

EndStreamingSession marks a session as ended and calculates final metrics

func (*MediaSessionRepository) GetActiveSessionsCount

func (r *MediaSessionRepository) GetActiveSessionsCount(ctx context.Context) (int, error)

GetActiveSessionsCount returns the count of active sessions for monitoring

func (*MediaSessionRepository) GetActiveStreams

func (r *MediaSessionRepository) GetActiveStreams(ctx context.Context, limit int) ([]*types.StreamingSession, error)

GetActiveStreams retrieves all active streaming sessions for monitoring

func (*MediaSessionRepository) GetMediaSessions

func (r *MediaSessionRepository) GetMediaSessions(ctx context.Context, mediaID string, limit int32) ([]*types.StreamingSession, error)

GetMediaSessions retrieves sessions for a specific media item

func (*MediaSessionRepository) GetSession

func (r *MediaSessionRepository) GetSession(ctx context.Context, sessionID string) (*types.StreamingSession, error)

GetSession retrieves a streaming session (legacy compatibility)

func (*MediaSessionRepository) GetSessionsByTimeRange

func (r *MediaSessionRepository) GetSessionsByTimeRange(ctx context.Context, startTime, endTime time.Time, limit int32) ([]*types.StreamingSession, error)

GetSessionsByTimeRange retrieves sessions within a specific time range for analytics

func (*MediaSessionRepository) GetUserSessions

func (r *MediaSessionRepository) GetUserSessions(ctx context.Context, userID string) ([]*types.StreamingSession, error)

GetUserSessions retrieves active sessions for a user using GSI

func (*MediaSessionRepository) SetSessionTTL

func (r *MediaSessionRepository) SetSessionTTL(ttl time.Duration)

SetSessionTTL configures the TTL for streaming sessions

func (*MediaSessionRepository) StartStreamingSession

func (r *MediaSessionRepository) StartStreamingSession(ctx context.Context, userID, mediaID string, format types.MediaFormat, quality types.Quality) (*types.StreamingSession, error)

StartStreamingSession creates and initializes a new streaming session with validation

func (*MediaSessionRepository) UpdateSession

func (r *MediaSessionRepository) UpdateSession(ctx context.Context, session *types.StreamingSession) error

UpdateSession updates a streaming session (legacy compatibility)

func (*MediaSessionRepository) UpdateStreamingMetrics

func (r *MediaSessionRepository) UpdateStreamingMetrics(ctx context.Context, sessionID string, segmentIndex int, bytesTransferred int64, bufferHealth float64, currentQuality types.Quality) error

UpdateStreamingMetrics updates session metrics with bandwidth optimization

func (*MediaSessionRepository) ValidateSessionAccess

func (r *MediaSessionRepository) ValidateSessionAccess(ctx context.Context, sessionID, userID string) (bool, error)

ValidateSessionAccess validates if user has access to the streaming session

type MetricRecordRepository

type MetricRecordRepository struct {
	*EnhancedBaseRepository[*models.MetricRecord]
	// contains filtered or unexported fields
}

MetricRecordRepository handles new reporting table schema with extensive indexing

func NewMetricRecordRepository

func NewMetricRecordRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MetricRecordRepository

NewMetricRecordRepository creates a new metric record repository with enhanced functionality

func (*MetricRecordRepository) BatchCreateMetricRecords

func (r *MetricRecordRepository) BatchCreateMetricRecords(ctx context.Context, records []*models.MetricRecord) error

BatchCreateMetricRecords creates multiple metric records efficiently

func (*MetricRecordRepository) CreateMetricRecord

func (r *MetricRecordRepository) CreateMetricRecord(ctx context.Context, record *models.MetricRecord) error

CreateMetricRecord creates a new metric record

func (*MetricRecordRepository) DeleteMetricRecord

func (r *MetricRecordRepository) DeleteMetricRecord(ctx context.Context, metricType, bucket, timestamp string) error

DeleteMetricRecord deletes a metric record by its keys

func (*MetricRecordRepository) GetMetricRecord

func (r *MetricRecordRepository) GetMetricRecord(ctx context.Context, metricType, bucket, timestamp string) (*models.MetricRecord, error)

GetMetricRecord retrieves a single metric record by its keys

func (*MetricRecordRepository) GetMetricsByAggregationLevel

func (r *MetricRecordRepository) GetMetricsByAggregationLevel(ctx context.Context, level string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

GetMetricsByAggregationLevel queries metrics by aggregation level within a time range using GSI4

func (*MetricRecordRepository) GetMetricsByDate

func (r *MetricRecordRepository) GetMetricsByDate(ctx context.Context, date time.Time, serviceName string) ([]*models.MetricRecord, error)

GetMetricsByDate queries metrics by date and service using GSI3

func (*MetricRecordRepository) GetMetricsByService

func (r *MetricRecordRepository) GetMetricsByService(ctx context.Context, serviceName string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

GetMetricsByService queries metrics by service within a time range using GSI1

func (*MetricRecordRepository) GetMetricsByType

func (r *MetricRecordRepository) GetMetricsByType(ctx context.Context, metricType string, startTime, endTime time.Time) ([]*models.MetricRecord, error)

GetMetricsByType queries metrics by type within a time range using GSI2

func (*MetricRecordRepository) GetServiceMetricsStats

func (r *MetricRecordRepository) GetServiceMetricsStats(ctx context.Context, serviceName string, metricType string, startTime, endTime time.Time) (*MetricRecordStats, error)

GetServiceMetricsStats calculates statistics for a service's metrics

func (*MetricRecordRepository) UpdateMetricRecord

func (r *MetricRecordRepository) UpdateMetricRecord(ctx context.Context, record *models.MetricRecord) error

UpdateMetricRecord updates an existing metric record

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 MetricsQueryConfig

type MetricsQueryConfig struct {
	IndexName   string // GSI index name
	PKField     string // GSI PK field name
	SKField     string // GSI SK field name
	PKPattern   string // PK value pattern (e.g., "SERVICE#%s", "METRIC_TYPE#%s")
	LogName     string // Name for logging
	ErrorPrefix string // Error message prefix
}

MetricsQueryConfig configures behavior for metrics query operations

type MetricsRepository

type MetricsRepository struct {
	*EnhancedBaseRepository[*models.Metrics]
	// contains filtered or unexported fields
}

MetricsRepository handles metrics persistence

func NewMetricsRepository

func NewMetricsRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MetricsRepository

NewMetricsRepository creates a new metrics repository with enhanced functionality

func (*MetricsRepository) Aggregate

func (r *MetricsRepository) Aggregate(ctx context.Context, metricType, period string, windowStart, windowEnd time.Time) error

Aggregate performs aggregation of raw metrics

func (*MetricsRepository) BatchCreate

func (r *MetricsRepository) BatchCreate(ctx context.Context, metricsList []*models.Metrics) error

BatchCreate creates multiple metrics records efficiently using DynamORM batch operations

func (*MetricsRepository) CleanupOldMetrics

func (r *MetricsRepository) CleanupOldMetrics(ctx context.Context, granularity string, cutoffTime time.Time) (int, error)

CleanupOldMetrics removes metrics older than the cutoff time for a specific granularity/period

func (*MetricsRepository) Create

func (r *MetricsRepository) Create(ctx context.Context, metrics *models.Metrics) error

Create creates a new metrics record

func (*MetricsRepository) CreateAggregated

func (r *MetricsRepository) CreateAggregated(ctx context.Context, aggregated *models.AggregatedMetrics) error

CreateAggregated creates an aggregated metrics record

func (*MetricsRepository) Get

func (r *MetricsRepository) Get(ctx context.Context, metricType, id string, timestamp time.Time) (*models.Metrics, error)

Get retrieves a metrics record by ID and type

func (*MetricsRepository) GetAggregated

func (r *MetricsRepository) GetAggregated(ctx context.Context, period, metricType string, windowStart time.Time) (*models.AggregatedMetrics, error)

GetAggregated retrieves aggregated metrics

func (*MetricsRepository) GetServiceStats

func (r *MetricsRepository) GetServiceStats(ctx context.Context, service string, metricType string, startTime, endTime time.Time) (*ServiceStats, error)

GetServiceStats calculates statistics for a service

func (*MetricsRepository) ListAggregatedByPeriod

func (r *MetricsRepository) ListAggregatedByPeriod(ctx context.Context, period, metricType string, startTime, endTime time.Time, limit int, cursor string) ([]*models.AggregatedMetrics, string, error)

ListAggregatedByPeriod lists aggregated metrics for a period

func (*MetricsRepository) ListByService

func (r *MetricsRepository) ListByService(ctx context.Context, service string, startTime, endTime time.Time, limit int) ([]*models.Metrics, error)

ListByService lists metrics by service within a time range

func (*MetricsRepository) ListByType

func (r *MetricsRepository) ListByType(ctx context.Context, metricType string, startTime, endTime time.Time, limit int) ([]*models.Metrics, error)

ListByType lists metrics by type within a time range

func (*MetricsRepository) UpdateAggregated

func (r *MetricsRepository) UpdateAggregated(ctx context.Context, aggregated *models.AggregatedMetrics) error

UpdateAggregated updates an existing aggregated metrics record

type ModerationMLRepository

type ModerationMLRepository struct {
	*EnhancedBaseRepository[*models.ModerationSample]
	// contains filtered or unexported fields
}

ModerationMLRepository handles ML moderation data storage operations

func NewModerationMLRepository

func NewModerationMLRepository(db core.DB, tableName string, logger *zap.Logger) *ModerationMLRepository

NewModerationMLRepository creates a new moderation ML repository

func (*ModerationMLRepository) CreateEffectivenessMetric

func (r *ModerationMLRepository) CreateEffectivenessMetric(ctx context.Context, metric *models.ModerationEffectivenessMetric) error

CreateEffectivenessMetric creates a new effectiveness metric record

func (*ModerationMLRepository) CreateModelVersion

func (r *ModerationMLRepository) CreateModelVersion(ctx context.Context, version *models.ModerationModelVersion) error

CreateModelVersion creates a new model version record

func (*ModerationMLRepository) CreatePollRequest

func (r *ModerationMLRepository) CreatePollRequest(ctx context.Context, pollRequest *models.MLPollRequest) error

CreatePollRequest creates a new poll request

func (*ModerationMLRepository) CreatePrediction

func (r *ModerationMLRepository) CreatePrediction(ctx context.Context, prediction *models.MLPrediction) error

CreatePrediction creates a new ML prediction record

func (*ModerationMLRepository) CreateSample

func (r *ModerationMLRepository) CreateSample(ctx context.Context, sample *models.ModerationSample) error

CreateSample creates a new moderation training sample

func (*ModerationMLRepository) CreateTrainingJob

func (r *ModerationMLRepository) CreateTrainingJob(ctx context.Context, job *models.ModelTrainingJob) error

CreateTrainingJob creates a new training job record

func (*ModerationMLRepository) GetActiveModelVersion

func (r *ModerationMLRepository) GetActiveModelVersion(ctx context.Context) (*models.ModerationModelVersion, error)

GetActiveModelVersion retrieves the currently active model version

func (*ModerationMLRepository) GetEffectivenessMetric

func (r *ModerationMLRepository) GetEffectivenessMetric(ctx context.Context, patternID, period string, startTime time.Time) (*models.ModerationEffectivenessMetric, error)

GetEffectivenessMetric retrieves effectiveness metrics for a pattern/period

func (*ModerationMLRepository) GetModelVersion

func (r *ModerationMLRepository) GetModelVersion(ctx context.Context, versionID string) (*models.ModerationModelVersion, error)

GetModelVersion retrieves a model version by ID

func (*ModerationMLRepository) GetPollRequest

func (r *ModerationMLRepository) GetPollRequest(ctx context.Context, jobID string, timestamp int64) (*models.MLPollRequest, error)

GetPollRequest retrieves a poll request by job ID

func (*ModerationMLRepository) GetPredictionsByModelVersion

func (r *ModerationMLRepository) GetPredictionsByModelVersion(ctx context.Context, modelVersion string, startTime, endTime time.Time, limit int) ([]*models.MLPrediction, error)

GetPredictionsByModelVersion retrieves predictions for a specific model version within a time range

func (*ModerationMLRepository) GetPredictionsByReviewStatus

func (r *ModerationMLRepository) GetPredictionsByReviewStatus(ctx context.Context, reviewed bool, startTime, endTime time.Time, limit int) ([]*models.MLPrediction, error)

GetPredictionsByReviewStatus retrieves predictions by review status within a time range

func (*ModerationMLRepository) GetSample

func (r *ModerationMLRepository) GetSample(ctx context.Context, sampleID string) (*models.ModerationSample, error)

GetSample retrieves a sample by ID

func (*ModerationMLRepository) GetTrainingJob

func (r *ModerationMLRepository) GetTrainingJob(ctx context.Context, jobID string) (*models.ModelTrainingJob, error)

GetTrainingJob retrieves a training job by ID

func (*ModerationMLRepository) ListEffectivenessMetricsByPattern

func (r *ModerationMLRepository) ListEffectivenessMetricsByPattern(ctx context.Context, patternID string, limit int) ([]*models.ModerationEffectivenessMetric, error)

ListEffectivenessMetricsByPattern retrieves all metrics for a pattern

func (*ModerationMLRepository) ListEffectivenessMetricsByPeriod

func (r *ModerationMLRepository) ListEffectivenessMetricsByPeriod(ctx context.Context, period string, limit int) ([]*models.ModerationEffectivenessMetric, error)

ListEffectivenessMetricsByPeriod retrieves top-performing patterns for a period

func (*ModerationMLRepository) ListSamplesByLabel

func (r *ModerationMLRepository) ListSamplesByLabel(ctx context.Context, label string, limit int) ([]*models.ModerationSample, error)

ListSamplesByLabel retrieves samples with a specific label

func (*ModerationMLRepository) ListSamplesByReviewer

func (r *ModerationMLRepository) ListSamplesByReviewer(ctx context.Context, reviewerID string, limit int) ([]*models.ModerationSample, error)

ListSamplesByReviewer retrieves samples submitted by a specific reviewer

func (*ModerationMLRepository) UpdateModelVersion

func (r *ModerationMLRepository) UpdateModelVersion(ctx context.Context, version *models.ModerationModelVersion) error

UpdateModelVersion updates an existing model version

func (*ModerationMLRepository) UpdatePollRequest

func (r *ModerationMLRepository) UpdatePollRequest(ctx context.Context, pollRequest *models.MLPollRequest) error

UpdatePollRequest updates an existing poll request

func (*ModerationMLRepository) UpdateTrainingJob

func (r *ModerationMLRepository) UpdateTrainingJob(ctx context.Context, job *models.ModelTrainingJob) error

UpdateTrainingJob updates an existing training job

type ModerationMetricsRepository

type ModerationMetricsRepository interface {
	// Metrics recording
	RecordMetricsEntry(ctx context.Context, entry *models.ModerationMetricsEntry) error
	RecordMetricsEntries(ctx context.Context, entries []*models.ModerationMetricsEntry) error

	// False positive tracking
	RecordFalsePositive(ctx context.Context, fp *models.ModerationFalsePositive) error
	GetFalsePositives(ctx context.Context, timeRange models.ModerationMetricsTimeRange) ([]*models.ModerationFalsePositive, error)

	// Decision sampling
	RecordDecisionSample(ctx context.Context, sample *models.ModerationDecisionSample) error
	GetDecisionSamples(ctx context.Context, timeRange models.ModerationMetricsTimeRange, decision string) ([]*models.ModerationDecisionSample, error)

	// Pattern statistics
	UpdatePatternStats(ctx context.Context, stats *models.ModerationPatternStats) error
	GetTopPatterns(ctx context.Context, limit int) ([]*models.ModerationPatternStats, error)
	IncrementPatternHit(ctx context.Context, patternID, patternName string) error

	// Statistics retrieval
	GetMetricsEntries(ctx context.Context, timeRange models.ModerationMetricsTimeRange, metricTypes []string) ([]*models.ModerationMetricsEntry, error)
	GetAggregatedStats(ctx context.Context, timeRange models.ModerationMetricsTimeRange) (*models.ModerationMetricsStats, error)
}

ModerationMetricsRepository interface defines methods for moderation metrics operations

func NewModerationMetricsRepository

func NewModerationMetricsRepository(args ...interface{}) ModerationMetricsRepository

NewModerationMetricsRepository creates a new moderation metrics repository with optional cost tracking For backward compatibility, supports both old signature (db, logger) and new signature (db, tableName, logger, costService)

type ModerationRepository

type ModerationRepository struct {
	*EnhancedBaseRepository[*models.ModerationEvent]
}

ModerationRepository implements moderation operations using enhanced DynamORM patterns

func NewModerationRepository

func NewModerationRepository(db core.DB, tableName string, logger *zap.Logger) *ModerationRepository

NewModerationRepository creates a new moderation repository with enhanced functionality

func (*ModerationRepository) AddFilterKeyword

func (r *ModerationRepository) AddFilterKeyword(ctx context.Context, filterID string, keyword *storage.FilterKeyword) error

AddFilterKeyword adds a new keyword to a filter

func (*ModerationRepository) AddFilterStatus

func (r *ModerationRepository) AddFilterStatus(ctx context.Context, filterID string, status *storage.FilterStatus) error

AddFilterStatus adds a new status to a filter

func (*ModerationRepository) AddModerationReview

func (r *ModerationRepository) AddModerationReview(ctx context.Context, review *storage.ModerationReview) error

AddModerationReview adds a review to a moderation event

func (*ModerationRepository) AssignReport

func (r *ModerationRepository) AssignReport(ctx context.Context, reportID string, assignedTo string) error

AssignReport assigns a report to a moderator

func (*ModerationRepository) CountPendingFlags

func (r *ModerationRepository) CountPendingFlags(ctx context.Context) (int, error)

CountPendingFlags returns the count of pending flags

func (*ModerationRepository) CreateAdminReview

func (r *ModerationRepository) CreateAdminReview(ctx context.Context, eventID string, adminID string, action storage.ActionType, reason string) error

CreateAdminReview creates an admin review that overrides consensus

func (*ModerationRepository) CreateAuditLog

func (r *ModerationRepository) CreateAuditLog(ctx context.Context, auditLog *storage.AuditLog) error

CreateAuditLog creates a new audit log entry

func (*ModerationRepository) CreateFilter

func (r *ModerationRepository) CreateFilter(ctx context.Context, filter *storage.Filter) error

CreateFilter creates a new filter

func (*ModerationRepository) CreateFlag

func (r *ModerationRepository) CreateFlag(ctx context.Context, flag *storage.Flag) error

CreateFlag creates a new flag

func (*ModerationRepository) CreateModerationDecision

func (r *ModerationRepository) CreateModerationDecision(ctx context.Context, decision *storage.ModerationDecision) error

CreateModerationDecision creates a consensus decision

func (*ModerationRepository) CreateModerationEvent

func (r *ModerationRepository) CreateModerationEvent(ctx context.Context, event *storage.ModerationEvent) error

CreateModerationEvent creates a new moderation event using BaseRepository

func (*ModerationRepository) CreateModerationPattern

func (r *ModerationRepository) CreateModerationPattern(ctx context.Context, pattern *storage.ModerationPattern) error

CreateModerationPattern creates a new moderation pattern

func (*ModerationRepository) CreateReport

func (r *ModerationRepository) CreateReport(ctx context.Context, report *storage.Report) error

CreateReport creates a new report

func (*ModerationRepository) DeleteFilter

func (r *ModerationRepository) DeleteFilter(ctx context.Context, filterID string) error

DeleteFilter deletes a filter and all its associated keywords and statuses

func (*ModerationRepository) DeleteFilterKeyword

func (r *ModerationRepository) DeleteFilterKeyword(ctx context.Context, keywordID string) error

DeleteFilterKeyword deletes a filter keyword

func (*ModerationRepository) DeleteFilterStatus

func (r *ModerationRepository) DeleteFilterStatus(ctx context.Context, statusID string) error

DeleteFilterStatus deletes a filter status by statusID (the ID being filtered, not the filter entry ID)

func (*ModerationRepository) DeleteFlag

func (r *ModerationRepository) DeleteFlag(ctx context.Context, id string) error

DeleteFlag removes a flag

func (*ModerationRepository) DeleteModerationPattern

func (r *ModerationRepository) DeleteModerationPattern(ctx context.Context, patternID string) error

DeleteModerationPattern deletes a moderation pattern

func (*ModerationRepository) GetAuditLogs

func (r *ModerationRepository) GetAuditLogs(ctx context.Context, limit int, cursor string) ([]*storage.AuditLog, string, error)

GetAuditLogs retrieves audit log entries with pagination

func (*ModerationRepository) GetAuditLogsByAdmin

func (r *ModerationRepository) GetAuditLogsByAdmin(ctx context.Context, adminID string, limit int, cursor string) ([]*storage.AuditLog, string, error)

GetAuditLogsByAdmin retrieves audit log entries for a specific admin

func (*ModerationRepository) GetAuditLogsByTarget

func (r *ModerationRepository) GetAuditLogsByTarget(ctx context.Context, targetID string, limit int, cursor string) ([]*storage.AuditLog, string, error)

GetAuditLogsByTarget retrieves audit log entries for a specific target

func (*ModerationRepository) GetDecisionHistory

func (r *ModerationRepository) GetDecisionHistory(ctx context.Context, contentID string) ([]*models.ModerationDecisionResult, error)

GetDecisionHistory retrieves decision history for a specific content ID

func (*ModerationRepository) GetFilter

func (r *ModerationRepository) GetFilter(ctx context.Context, filterID string) (*storage.Filter, error)

GetFilter retrieves a filter by ID

func (*ModerationRepository) GetFilterKeywords

func (r *ModerationRepository) GetFilterKeywords(ctx context.Context, filterID string) ([]*storage.FilterKeyword, error)

GetFilterKeywords retrieves all keywords for a filter

func (*ModerationRepository) GetFilterStatuses

func (r *ModerationRepository) GetFilterStatuses(ctx context.Context, filterID string) ([]*storage.FilterStatus, error)

GetFilterStatuses retrieves all statuses for a filter

func (*ModerationRepository) GetFiltersForUser

func (r *ModerationRepository) GetFiltersForUser(ctx context.Context, username string) ([]*storage.Filter, error)

GetFiltersForUser retrieves all filters for a user

func (*ModerationRepository) GetFlag

func (r *ModerationRepository) GetFlag(ctx context.Context, id string) (*storage.Flag, error)

GetFlag retrieves a flag by ID

func (*ModerationRepository) GetFlagsByActor

func (r *ModerationRepository) GetFlagsByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.Flag, string, error)

GetFlagsByActor retrieves all flags created by a specific actor

func (*ModerationRepository) GetFlagsByObject

func (r *ModerationRepository) GetFlagsByObject(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.Flag, string, error)

GetFlagsByObject retrieves all flags for a specific object

func (*ModerationRepository) GetModerationDecision

func (r *ModerationRepository) GetModerationDecision(ctx context.Context, objectID string) (*storage.ModerationDecision, error)

GetModerationDecision retrieves the current decision for an object

func (*ModerationRepository) GetModerationDecisionsByModerator

func (r *ModerationRepository) GetModerationDecisionsByModerator(ctx context.Context, moderatorUsername string, limit int) ([]*models.ModerationReview, error)

GetModerationDecisionsByModerator retrieves moderation decisions made by a specific moderator

func (*ModerationRepository) GetModerationEvent

func (r *ModerationRepository) GetModerationEvent(ctx context.Context, eventID string) (*storage.ModerationEvent, error)

GetModerationEvent retrieves a moderation event by ID

func (*ModerationRepository) GetModerationEvents

func (r *ModerationRepository) GetModerationEvents(ctx context.Context, filter *storage.ModerationEventFilter, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

GetModerationEvents retrieves all moderation events with optional filters

func (*ModerationRepository) GetModerationEventsByActor

func (r *ModerationRepository) GetModerationEventsByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

GetModerationEventsByActor retrieves all moderation events created by an actor

func (*ModerationRepository) GetModerationEventsByObject

func (r *ModerationRepository) GetModerationEventsByObject(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.ModerationEvent, string, error)

GetModerationEventsByObject retrieves all moderation events for an object

func (*ModerationRepository) GetModerationHistory

func (r *ModerationRepository) GetModerationHistory(ctx context.Context, objectID string) (*storage.ModerationHistory, error)

GetModerationHistory retrieves the complete moderation history for an object

func (*ModerationRepository) GetModerationPattern

func (r *ModerationRepository) GetModerationPattern(ctx context.Context, patternID string) (*storage.ModerationPattern, error)

GetModerationPattern retrieves a specific moderation pattern

func (*ModerationRepository) GetModerationPatterns

func (r *ModerationRepository) GetModerationPatterns(ctx context.Context, active bool, severity string, limit int) ([]*storage.ModerationPattern, error)

GetModerationPatterns retrieves moderation patterns based on criteria

func (*ModerationRepository) GetModerationQueue

GetModerationQueue retrieves pending moderation events

func (*ModerationRepository) GetModerationQueueCount

func (r *ModerationRepository) GetModerationQueueCount(ctx context.Context) (int, error)

GetModerationQueueCount returns the count of items in the moderation queue

func (*ModerationRepository) GetModerationQueuePaginated

func (r *ModerationRepository) GetModerationQueuePaginated(ctx context.Context, limit int, cursor string) ([]*storage.ModerationQueueItem, string, error)

GetModerationQueuePaginated retrieves pending moderation events with pagination

func (*ModerationRepository) GetModerationReviews

func (r *ModerationRepository) GetModerationReviews(ctx context.Context, eventID string) ([]*storage.ModerationReview, error)

GetModerationReviews retrieves all reviews for a moderation event

func (*ModerationRepository) GetOpenReportsCount

func (r *ModerationRepository) GetOpenReportsCount(ctx context.Context) (int, error)

GetOpenReportsCount returns the count of open reports

func (*ModerationRepository) GetPendingFlags

func (r *ModerationRepository) GetPendingFlags(ctx context.Context, limit int, cursor string) ([]*storage.Flag, string, error)

GetPendingFlags retrieves all pending flags

func (*ModerationRepository) GetPendingModerationCount

func (r *ModerationRepository) GetPendingModerationCount(ctx context.Context, moderatorID string) (int, error)

GetPendingModerationCount returns the count of pending moderation tasks for a specific moderator

func (*ModerationRepository) GetReport

func (r *ModerationRepository) GetReport(ctx context.Context, id string) (*storage.Report, error)

GetReport retrieves a report by ID

func (*ModerationRepository) GetReportStats

func (r *ModerationRepository) GetReportStats(ctx context.Context, username string) (*storage.ReportStats, error)

GetReportStats retrieves reporting statistics for a user

func (*ModerationRepository) GetReportedStatuses

func (r *ModerationRepository) GetReportedStatuses(ctx context.Context, reportID string) ([]any, error)

GetReportedStatuses retrieves statuses associated with a report

func (*ModerationRepository) GetReportsByStatus

func (r *ModerationRepository) GetReportsByStatus(ctx context.Context, status storage.ReportStatus, limit int, cursor string) ([]*storage.Report, string, error)

GetReportsByStatus retrieves reports with a specific status

func (*ModerationRepository) GetReportsByTarget

func (r *ModerationRepository) GetReportsByTarget(ctx context.Context, targetAccountID string, limit int, cursor string) ([]*storage.Report, string, error)

GetReportsByTarget retrieves reports targeting a specific account

func (*ModerationRepository) GetReviewQueue

func (r *ModerationRepository) GetReviewQueue(ctx context.Context, filters map[string]interface{}) ([]*models.ModerationReviewQueue, error)

GetReviewQueue retrieves review queue items with filtering

func (*ModerationRepository) GetReviewerStats

func (r *ModerationRepository) GetReviewerStats(ctx context.Context, reviewerID string) (*storage.ReviewerStats, error)

GetReviewerStats retrieves statistics for a reviewer

func (*ModerationRepository) GetUserReports

func (r *ModerationRepository) GetUserReports(ctx context.Context, username string, limit int, cursor string) ([]*storage.Report, string, error)

GetUserReports retrieves all reports created by a user

func (*ModerationRepository) IncrementFalseReports

func (r *ModerationRepository) IncrementFalseReports(ctx context.Context, username string) error

IncrementFalseReports increments the false report count for a user

func (*ModerationRepository) RecordPatternMatch

func (r *ModerationRepository) RecordPatternMatch(_ context.Context, patternID string, matched bool, timestamp time.Time) error

RecordPatternMatch records a moderation pattern match for analytics

func (*ModerationRepository) StoreAnalysisResult

func (r *ModerationRepository) StoreAnalysisResult(ctx context.Context, analysisData map[string]interface{}) error

StoreAnalysisResult stores detailed analysis results for audit/appeals

func (*ModerationRepository) StoreDecision

func (r *ModerationRepository) StoreDecision(ctx context.Context, decisionData map[string]interface{}) error

StoreDecision stores a moderation decision with enforcement tracking

func (*ModerationRepository) StoreModerationDecision

func (r *ModerationRepository) StoreModerationDecision(ctx context.Context, decision *storage.ModerationDecision) error

StoreModerationDecision stores a moderation decision (alias for CreateModerationDecision)

func (*ModerationRepository) UnassignReport

func (r *ModerationRepository) UnassignReport(ctx context.Context, reportID string) error

UnassignReport removes assignment from a report

func (*ModerationRepository) UpdateEnforcementStatus

func (r *ModerationRepository) UpdateEnforcementStatus(ctx context.Context, contentID, status string) error

UpdateEnforcementStatus updates the enforcement status of a decision

func (*ModerationRepository) UpdateFilter

func (r *ModerationRepository) UpdateFilter(ctx context.Context, filterID string, updates map[string]any) error

UpdateFilter updates a filter

func (*ModerationRepository) UpdateFilterKeyword

func (r *ModerationRepository) UpdateFilterKeyword(ctx context.Context, keywordID string, updates map[string]any) error

UpdateFilterKeyword updates a filter keyword

func (*ModerationRepository) UpdateFlagStatus

func (r *ModerationRepository) UpdateFlagStatus(ctx context.Context, id string, status storage.FlagStatus, reviewedBy string, reviewNote string) error

UpdateFlagStatus updates the status of a flag

func (*ModerationRepository) UpdateModerationDecision

func (r *ModerationRepository) UpdateModerationDecision(ctx context.Context, contentID string, review *storage.ModerationReview) error

UpdateModerationDecision updates a moderation decision based on a review

func (*ModerationRepository) UpdateModerationPattern

func (r *ModerationRepository) UpdateModerationPattern(ctx context.Context, pattern *storage.ModerationPattern) error

UpdateModerationPattern updates an existing moderation pattern

func (*ModerationRepository) UpdateReportStatus

func (r *ModerationRepository) UpdateReportStatus(ctx context.Context, id string, status storage.ReportStatus, actionTaken string, moderatorID string) error

UpdateReportStatus updates the status of a report

type MonthlyAggregate

type MonthlyAggregate struct {
	Year             int
	Month            int
	TotalCostDollars float64
	TotalRequests    int64
	TotalReads       int64
	TotalWrites      int64
}

MonthlyAggregate represents aggregated costs for a single month

type MuteRepository

type MuteRepository struct {
	*EnhancedBaseRepository[*models.Mute]
	// contains filtered or unexported fields
}

MuteRepository implements mute operations using enhanced DynamORM patterns

func NewMuteRepository

func NewMuteRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *MuteRepository

NewMuteRepository creates a new mute repository with enhanced functionality

func (*MuteRepository) CountMutedUsers

func (r *MuteRepository) CountMutedUsers(ctx context.Context, muterActor string) (int, error)

CountMutedUsers returns the number of users muted by the given actor

func (*MuteRepository) CountUsersWhoMuted

func (r *MuteRepository) CountUsersWhoMuted(ctx context.Context, mutedActor string) (int, error)

CountUsersWhoMuted returns the number of users who have muted the given actor

func (*MuteRepository) CreateMute

func (r *MuteRepository) CreateMute(ctx context.Context, muterActor, mutedActor, activityID string, hideNotifications bool, _ *time.Duration) error

CreateMute creates a new mute relationship

func (*MuteRepository) DeleteMute

func (r *MuteRepository) DeleteMute(ctx context.Context, muterActor, mutedActor string) error

DeleteMute removes a mute relationship (for Undo Mute)

func (*MuteRepository) GetMute

func (r *MuteRepository) GetMute(ctx context.Context, muterActor, mutedActor string) (*storage.Mute, error)

GetMute retrieves a specific mute relationship

func (*MuteRepository) GetMutedUsers

func (r *MuteRepository) GetMutedUsers(ctx context.Context, muterActor string, limit int, cursor string) ([]string, string, error)

GetMutedUsers returns a list of users muted by the given actor

func (*MuteRepository) GetUsersWhoMuted

func (r *MuteRepository) GetUsersWhoMuted(ctx context.Context, mutedActor string, limit int, cursor string) ([]string, string, error)

GetUsersWhoMuted returns a list of users who have muted the given actor

func (*MuteRepository) IsMuted

func (r *MuteRepository) IsMuted(ctx context.Context, muterActor, mutedActor string) (bool, error)

IsMuted checks if one actor has muted another

type NotificationCostRepository

type NotificationCostRepository struct {
	*EnhancedBaseRepository[*models.NotificationCostTracking]
	// contains filtered or unexported fields
}

NotificationCostRepository handles notification cost tracking operations using enhanced patterns

func NewNotificationCostRepository

func NewNotificationCostRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *NotificationCostRepository

NewNotificationCostRepository creates a new notification cost repository with enhanced functionality

func (*NotificationCostRepository) AggregateNotificationCosts

func (r *NotificationCostRepository) AggregateNotificationCosts(ctx context.Context, period, deliveryMethod string, windowStart, windowEnd time.Time) error

AggregateNotificationCosts aggregates raw cost data into aggregation records

func (*NotificationCostRepository) CreateAggregation

func (r *NotificationCostRepository) CreateAggregation(ctx context.Context, aggregation *models.NotificationCostAggregation) error

CreateAggregation creates a notification cost aggregation record

func (*NotificationCostRepository) CreateBudget

CreateBudget creates a notification budget record

func (*NotificationCostRepository) CreateCostTracking

func (r *NotificationCostRepository) CreateCostTracking(ctx context.Context, tracking *models.NotificationCostTracking) error

CreateCostTracking creates a new notification cost tracking record

func (*NotificationCostRepository) GetAggregation

func (r *NotificationCostRepository) GetAggregation(ctx context.Context, period, deliveryMethod string, windowStart time.Time) (*models.NotificationCostAggregation, error)

GetAggregation retrieves a notification cost aggregation record

func (*NotificationCostRepository) GetBudget

func (r *NotificationCostRepository) GetBudget(ctx context.Context, username, period string) (*models.NotificationBudget, error)

GetBudget retrieves a notification budget record

func (*NotificationCostRepository) GetCostTrackingByMethod

func (r *NotificationCostRepository) GetCostTrackingByMethod(ctx context.Context, deliveryMethod string, startTime, endTime time.Time, limit int) ([]*models.NotificationCostTracking, error)

GetCostTrackingByMethod retrieves cost tracking records by delivery method within a time range

func (*NotificationCostRepository) GetCostTrackingByNotification

func (r *NotificationCostRepository) GetCostTrackingByNotification(ctx context.Context, notificationID string, limit int) ([]*models.NotificationCostTracking, error)

GetCostTrackingByNotification retrieves cost tracking records for a notification

func (*NotificationCostRepository) GetCostTrackingByUser

func (r *NotificationCostRepository) GetCostTrackingByUser(ctx context.Context, username string, startTime, endTime time.Time, limit int) ([]*models.NotificationCostTracking, error)

GetCostTrackingByUser retrieves cost tracking records for a user within a time range

func (*NotificationCostRepository) GetDailyCostTracking

func (r *NotificationCostRepository) GetDailyCostTracking(ctx context.Context, date time.Time, limit int) ([]*models.NotificationCostTracking, error)

GetDailyCostTracking retrieves cost tracking records for a specific date

func (*NotificationCostRepository) GetDailySpending

func (r *NotificationCostRepository) GetDailySpending(ctx context.Context, username string) (int64, error)

GetDailySpending retrieves the current daily spending for a user

func (*NotificationCostRepository) GetHighCostNotifications

func (r *NotificationCostRepository) GetHighCostNotifications(ctx context.Context, thresholdMicroCents int64, startTime, endTime time.Time, limit int) ([]*models.NotificationCostTracking, error)

GetHighCostNotifications returns notifications that exceed a cost threshold

func (*NotificationCostRepository) GetNotificationCostSummary

func (r *NotificationCostRepository) GetNotificationCostSummary(ctx context.Context, startTime, endTime time.Time) (*NotificationCostSummary, error)

GetNotificationCostSummary calculates cost summary for notifications within a time range

func (*NotificationCostRepository) GetUserBudgets

func (r *NotificationCostRepository) GetUserBudgets(ctx context.Context, username string) ([]*models.NotificationBudget, error)

GetUserBudgets retrieves all budget records for a user

func (*NotificationCostRepository) GetUserSpending

func (r *NotificationCostRepository) GetUserSpending(ctx context.Context, username string, startTime, endTime time.Time) (*UserSpendingSummary, error)

GetUserSpending calculates total spending for a user in a time period

func (*NotificationCostRepository) ListAggregationsByPeriod

func (r *NotificationCostRepository) ListAggregationsByPeriod(ctx context.Context, period, deliveryMethod string, startTime, endTime time.Time, limit int) ([]*models.NotificationCostAggregation, error)

ListAggregationsByPeriod lists notification cost aggregations for a period and method

func (*NotificationCostRepository) UpdateAggregation

func (r *NotificationCostRepository) UpdateAggregation(ctx context.Context, aggregation *models.NotificationCostAggregation) error

UpdateAggregation updates an existing notification cost aggregation record

func (*NotificationCostRepository) UpdateBudget

UpdateBudget updates an existing notification budget record

type NotificationCostSummary

type NotificationCostSummary struct {
	StartTime                  time.Time
	EndTime                    time.Time
	Count                      int
	TotalNotifications         int64
	SuccessfulDeliveries       int64
	FailedDeliveries           int64
	TotalRetries               int64
	TotalCostMicroCents        int64
	TotalCostDollars           float64
	AverageCostPerNotification float64
	SuccessRate                float64
	RetryRate                  float64
	DeliveryMethodBreakdown    map[string]*DeliveryMethodSummaryStats
	NotificationTypeBreakdown  map[string]*NotificationTypeSummaryStats
}

NotificationCostSummary represents a summary of notification costs

type NotificationQueryHelper

type NotificationQueryHelper struct {
	// contains filtered or unexported fields
}

NotificationQueryHelper provides common query patterns for notifications

func NewNotificationQueryHelper

func NewNotificationQueryHelper(db core.DB, tableName string, logger *zap.Logger) *NotificationQueryHelper

NewNotificationQueryHelper creates a new notification query helper

func (*NotificationQueryHelper) GetPaginatedNotifications

func (h *NotificationQueryHelper) GetPaginatedNotifications(ctx context.Context, userID string, opts interfaces.PaginationOptions, additionalFilters map[string]interface{}) (*interfaces.PaginatedResult[*models.Notification], error)

GetPaginatedNotifications retrieves notifications with pagination using common patterns

type NotificationRepository

type NotificationRepository struct {
	*EnhancedBaseRepository[*models.Notification]
	// contains filtered or unexported fields
}

NotificationRepository handles notification operations using enhanced DynamORM patterns

func NewNotificationRepository

func NewNotificationRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *NotificationRepository

NewNotificationRepository creates a new notification repository with enhanced functionality and cost tracking

func (*NotificationRepository) ClearOldNotifications

func (r *NotificationRepository) ClearOldNotifications(ctx context.Context, username string, olderThan time.Time) (int, error)

ClearOldNotifications clears old notifications for a user

func (*NotificationRepository) ConsolidateNotifications

func (r *NotificationRepository) ConsolidateNotifications(ctx context.Context, groupKey string) error

ConsolidateNotifications consolidates notifications by group key

func (*NotificationRepository) CreateNotification

func (r *NotificationRepository) CreateNotification(ctx context.Context, notification *models.Notification) error

CreateNotification creates a new notification using BaseRepository

func (*NotificationRepository) CreateNotifications

func (r *NotificationRepository) CreateNotifications(ctx context.Context, notifications []*models.Notification) error

CreateNotifications creates multiple notifications efficiently

func (*NotificationRepository) DeleteExpiredNotifications

func (r *NotificationRepository) DeleteExpiredNotifications(ctx context.Context, expiredBefore time.Time) (int64, error)

DeleteExpiredNotifications deletes notifications that have expired

func (*NotificationRepository) DeleteNotification

func (r *NotificationRepository) DeleteNotification(ctx context.Context, notificationID string) error

DeleteNotification deletes a notification

func (*NotificationRepository) DeleteNotificationsByObject

func (r *NotificationRepository) DeleteNotificationsByObject(ctx context.Context, objectID string) error

DeleteNotificationsByObject deletes all notifications related to a specific object

func (*NotificationRepository) DeleteNotificationsByType

func (r *NotificationRepository) DeleteNotificationsByType(ctx context.Context, userID, notificationType string) error

DeleteNotificationsByType deletes notifications by type for a user

func (*NotificationRepository) GetNotification

func (r *NotificationRepository) GetNotification(ctx context.Context, notificationID string) (*models.Notification, error)

GetNotification retrieves a notification by ID using BaseRepository

func (*NotificationRepository) GetNotificationCountsByType

func (r *NotificationRepository) GetNotificationCountsByType(ctx context.Context, userID string) (map[string]int64, error)

GetNotificationCountsByType returns notification counts by type

func (*NotificationRepository) GetNotificationGroups

GetNotificationGroups retrieves notification groups for a user with pagination

func (*NotificationRepository) GetNotificationPreferences

func (r *NotificationRepository) GetNotificationPreferences(ctx context.Context, userID string) (*models.NotificationPreferences, error)

GetNotificationPreferences gets notification preferences for a user

func (*NotificationRepository) GetNotificationsAdvanced

func (r *NotificationRepository) GetNotificationsAdvanced(ctx context.Context, userID string, filters map[string]interface{}, pagination interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.Notification], error)

GetNotificationsAdvanced retrieves notifications with advanced filtering options

func (*NotificationRepository) GetNotificationsByType

func (r *NotificationRepository) GetNotificationsByType(ctx context.Context, userID, notificationType string, opts interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.Notification], error)

GetNotificationsByType retrieves notifications by type with pagination

func (*NotificationRepository) GetNotificationsFiltered

func (r *NotificationRepository) GetNotificationsFiltered(ctx context.Context, username string, filter map[string]interface{}) ([]*models.Notification, string, error)

GetNotificationsFiltered gets notifications with a filter

func (*NotificationRepository) GetPendingPushNotifications

GetPendingPushNotifications retrieves notifications that need push delivery

func (*NotificationRepository) GetUnreadNotificationCount

func (r *NotificationRepository) GetUnreadNotificationCount(ctx context.Context, userID string) (int64, error)

GetUnreadNotificationCount returns the count of unread notifications

func (*NotificationRepository) GetUnreadNotifications

GetUnreadNotifications retrieves unread notifications for a user with pagination

func (*NotificationRepository) GetUserNotifications

GetUserNotifications retrieves notifications for a user with pagination

func (*NotificationRepository) MarkAllNotificationsRead

func (r *NotificationRepository) MarkAllNotificationsRead(ctx context.Context, userID string) error

MarkAllNotificationsRead marks all notifications as read for a user

func (*NotificationRepository) MarkNotificationPushFailed

func (r *NotificationRepository) MarkNotificationPushFailed(ctx context.Context, notificationID, errorMsg string) error

MarkNotificationPushFailed marks a notification's push as failed

func (*NotificationRepository) MarkNotificationPushSent

func (r *NotificationRepository) MarkNotificationPushSent(ctx context.Context, notificationID string) error

MarkNotificationPushSent marks a notification's push as sent

func (*NotificationRepository) MarkNotificationRead

func (r *NotificationRepository) MarkNotificationRead(ctx context.Context, notificationID string) error

MarkNotificationRead marks a notification as read

func (*NotificationRepository) MarkNotificationUnread

func (r *NotificationRepository) MarkNotificationUnread(ctx context.Context, notificationID string) error

MarkNotificationUnread marks a notification as unread

func (*NotificationRepository) MarkNotificationsReadByType

func (r *NotificationRepository) MarkNotificationsReadByType(ctx context.Context, userID, notificationType string) error

MarkNotificationsReadByType marks notifications as read by type for a user

func (*NotificationRepository) SetDispatcher

func (r *NotificationRepository) SetDispatcher(dispatcher interfaces.NotificationDispatcher)

SetDispatcher wires an optional dispatcher for post-create side effects.

func (*NotificationRepository) SetNotificationPreference

func (r *NotificationRepository) SetNotificationPreference(ctx context.Context, userID string, preferenceType string, enabled bool) error

SetNotificationPreference sets a specific notification preference

func (*NotificationRepository) UpdateNotification

func (r *NotificationRepository) UpdateNotification(ctx context.Context, notification *models.Notification) error

UpdateNotification updates an existing notification using BaseRepository

func (*NotificationRepository) UpdateNotificationPreferences

func (r *NotificationRepository) UpdateNotificationPreferences(ctx context.Context, prefs *models.NotificationPreferences) error

UpdateNotificationPreferences updates notification preferences for a user

type NotificationTypeSummaryStats

type NotificationTypeSummaryStats struct {
	Type                  string
	Count                 int64
	SuccessfulDeliveries  int64
	FailedDeliveries      int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
	AverageCostDollars    float64
	SuccessRate           float64
}

NotificationTypeSummaryStats represents cost statistics for a notification type

type OAuthHelper

type OAuthHelper struct {
	// contains filtered or unexported fields
}

OAuthHelper provides common OAuth storage operations

func NewOAuthHelper

func NewOAuthHelper(db core.DB, logger *zap.Logger) *OAuthHelper

NewOAuthHelper creates a new OAuth helper

func (*OAuthHelper) CreateAuthorizationCodeGeneric

func (h *OAuthHelper) CreateAuthorizationCodeGeneric(ctx context.Context, code *storage.AuthorizationCode) error

CreateAuthorizationCodeGeneric creates a new OAuth authorization code

func (*OAuthHelper) CreateOAuthClientGeneric

func (h *OAuthHelper) CreateOAuthClientGeneric(ctx context.Context, client *storage.OAuthClient) error

CreateOAuthClientGeneric creates an OAuth client

func (*OAuthHelper) CreateRefreshTokenGeneric

func (h *OAuthHelper) CreateRefreshTokenGeneric(ctx context.Context, token *storage.RefreshToken) error

CreateRefreshTokenGeneric creates a new OAuth refresh token

func (*OAuthHelper) DeleteAuthorizationCodeGeneric

func (h *OAuthHelper) DeleteAuthorizationCodeGeneric(ctx context.Context, code string) error

DeleteAuthorizationCodeGeneric deletes an OAuth authorization code

func (*OAuthHelper) DeleteOAuthClientGeneric

func (h *OAuthHelper) DeleteOAuthClientGeneric(ctx context.Context, clientID string) error

DeleteOAuthClientGeneric deletes an OAuth client

func (*OAuthHelper) DeleteOAuthStateGeneric

func (h *OAuthHelper) DeleteOAuthStateGeneric(ctx context.Context, state string) error

DeleteOAuthStateGeneric deletes OAuth state

func (*OAuthHelper) DeleteRefreshTokenGeneric

func (h *OAuthHelper) DeleteRefreshTokenGeneric(ctx context.Context, token string) error

DeleteRefreshTokenGeneric deletes an OAuth refresh token

func (*OAuthHelper) GetAuthorizationCodeGeneric

func (h *OAuthHelper) GetAuthorizationCodeGeneric(ctx context.Context, code string) (*storage.AuthorizationCode, error)

GetAuthorizationCodeGeneric retrieves an OAuth authorization code

func (*OAuthHelper) GetOAuthClientGeneric

func (h *OAuthHelper) GetOAuthClientGeneric(ctx context.Context, clientID string) (*storage.OAuthClient, error)

GetOAuthClientGeneric retrieves an OAuth client

func (*OAuthHelper) GetOAuthStateGeneric

func (h *OAuthHelper) GetOAuthStateGeneric(ctx context.Context, state string) (*storage.OAuthState, error)

GetOAuthStateGeneric retrieves OAuth state

func (*OAuthHelper) GetRefreshTokenGeneric

func (h *OAuthHelper) GetRefreshTokenGeneric(ctx context.Context, token string) (*storage.RefreshToken, error)

GetRefreshTokenGeneric retrieves an OAuth refresh token

func (*OAuthHelper) GetUserAppConsentGeneric

func (h *OAuthHelper) GetUserAppConsentGeneric(ctx context.Context, userID, appID string) (*storage.UserAppConsent, error)

GetUserAppConsentGeneric retrieves user consent for an OAuth app

func (*OAuthHelper) ListOAuthClientsGeneric

func (h *OAuthHelper) ListOAuthClientsGeneric(ctx context.Context, ownerID string, limit int) ([]*storage.OAuthClient, string, error)

ListOAuthClientsGeneric lists OAuth clients for an owner

func (*OAuthHelper) SaveUserAppConsentGeneric

func (h *OAuthHelper) SaveUserAppConsentGeneric(ctx context.Context, consent *storage.UserAppConsent) error

SaveUserAppConsentGeneric saves user consent for an OAuth app

func (*OAuthHelper) StoreOAuthStateGeneric

func (h *OAuthHelper) StoreOAuthStateGeneric(ctx context.Context, state string, data *storage.OAuthState) error

StoreOAuthStateGeneric stores OAuth state for CSRF protection

func (*OAuthHelper) UpdateOAuthClientGeneric

func (h *OAuthHelper) UpdateOAuthClientGeneric(ctx context.Context, clientID string, updates map[string]interface{}) error

UpdateOAuthClientGeneric updates an OAuth client

type OAuthRepository

type OAuthRepository struct {
	*EnhancedBaseRepository[*models.OAuthClient]
	// contains filtered or unexported fields
}

OAuthRepository handles OAuth-related storage operations using enhanced DynamORM patterns

func NewOAuthRepository

func NewOAuthRepository(db core.DB, logger *zap.Logger) *OAuthRepository

NewOAuthRepository creates a new OAuth repository with enhanced functionality

func (*OAuthRepository) CreateAuthorizationCode

func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, code *storage.AuthorizationCode) error

CreateAuthorizationCode creates a new OAuth authorization code

func (*OAuthRepository) CreateOAuthClient

func (r *OAuthRepository) CreateOAuthClient(ctx context.Context, client *storage.OAuthClient) error

CreateOAuthClient creates a new OAuth client using BaseRepository

func (*OAuthRepository) CreateRefreshToken

func (r *OAuthRepository) CreateRefreshToken(ctx context.Context, token *storage.RefreshToken) error

CreateRefreshToken creates a new OAuth refresh token

func (*OAuthRepository) DeleteAuthorizationCode

func (r *OAuthRepository) DeleteAuthorizationCode(ctx context.Context, code string) error

DeleteAuthorizationCode deletes an OAuth authorization code

func (*OAuthRepository) DeleteExpiredTokens

func (r *OAuthRepository) DeleteExpiredTokens(_ context.Context) error

DeleteExpiredTokens removes expired OAuth tokens

func (*OAuthRepository) DeleteOAuthClient

func (r *OAuthRepository) DeleteOAuthClient(ctx context.Context, clientID string) error

DeleteOAuthClient deletes an OAuth client using BaseRepository

func (*OAuthRepository) DeleteOAuthState

func (r *OAuthRepository) DeleteOAuthState(ctx context.Context, state string) error

DeleteOAuthState deletes OAuth state

func (*OAuthRepository) DeleteRefreshToken

func (r *OAuthRepository) DeleteRefreshToken(ctx context.Context, token string) error

DeleteRefreshToken deletes an OAuth refresh token

func (*OAuthRepository) GetAuthorizationCode

func (r *OAuthRepository) GetAuthorizationCode(ctx context.Context, code string) (*storage.AuthorizationCode, error)

GetAuthorizationCode retrieves an OAuth authorization code

func (*OAuthRepository) GetOAuthClient

func (r *OAuthRepository) GetOAuthClient(ctx context.Context, clientID string) (*storage.OAuthClient, error)

GetOAuthClient retrieves an OAuth client using BaseRepository

func (*OAuthRepository) GetOAuthState

func (r *OAuthRepository) GetOAuthState(ctx context.Context, state string) (*storage.OAuthState, error)

GetOAuthState retrieves OAuth state

func (*OAuthRepository) GetRefreshToken

func (r *OAuthRepository) GetRefreshToken(ctx context.Context, token string) (*storage.RefreshToken, error)

GetRefreshToken retrieves an OAuth refresh token

func (*OAuthRepository) GetUserAppConsent

func (r *OAuthRepository) GetUserAppConsent(ctx context.Context, userID, appID string) (*storage.UserAppConsent, error)

GetUserAppConsent retrieves user consent for an OAuth app

func (*OAuthRepository) ListOAuthClients

func (r *OAuthRepository) ListOAuthClients(ctx context.Context, limit int32, _ string) ([]*storage.OAuthClient, string, error)

ListOAuthClients lists OAuth clients with pagination

func (*OAuthRepository) SaveUserAppConsent

func (r *OAuthRepository) SaveUserAppConsent(ctx context.Context, consent *storage.UserAppConsent) error

SaveUserAppConsent saves user consent for an OAuth app

func (*OAuthRepository) StoreOAuthState

func (r *OAuthRepository) StoreOAuthState(ctx context.Context, state string, data *storage.OAuthState) error

StoreOAuthState stores OAuth state for CSRF protection

func (*OAuthRepository) UpdateOAuthClient

func (r *OAuthRepository) UpdateOAuthClient(ctx context.Context, clientID string, updates map[string]any) error

UpdateOAuthClient updates an existing OAuth client using BaseRepository

type OAuthSessionRepository

type OAuthSessionRepository struct {
	*EnhancedBaseRepository[*models.OAuthAuthSession]
}

OAuthSessionRepository handles OAuth authorization session operations using BaseRepository

func NewOAuthSessionRepository

func NewOAuthSessionRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *OAuthSessionRepository

NewOAuthSessionRepository creates a new OAuth session repository with enhanced functionality

func (*OAuthSessionRepository) AuthorizeOAuthSession

func (r *OAuthSessionRepository) AuthorizeOAuthSession(ctx context.Context, sessionID string) error

AuthorizeOAuthSession marks an OAuth session as authorized by the user

func (*OAuthSessionRepository) CleanupExpiredOAuthSessions

func (r *OAuthSessionRepository) CleanupExpiredOAuthSessions(_ context.Context, _ int) (int, error)

CleanupExpiredOAuthSessions removes expired OAuth sessions (to be called by cleanup job)

func (*OAuthSessionRepository) CountUserOAuthSessions

func (r *OAuthSessionRepository) CountUserOAuthSessions(ctx context.Context, username string) (int, error)

CountUserOAuthSessions counts active OAuth sessions for a user

func (*OAuthSessionRepository) CreateOAuthSession

func (r *OAuthSessionRepository) CreateOAuthSession(ctx context.Context, session *models.OAuthAuthSession) error

CreateOAuthSession creates a new OAuth authorization session

func (*OAuthSessionRepository) DeleteOAuthSession

func (r *OAuthSessionRepository) DeleteOAuthSession(ctx context.Context, sessionID string) error

DeleteOAuthSession deletes an OAuth session

func (*OAuthSessionRepository) GetOAuthSession

func (r *OAuthSessionRepository) GetOAuthSession(ctx context.Context, sessionID string) (*models.OAuthAuthSession, error)

GetOAuthSession retrieves an OAuth session by session ID

func (*OAuthSessionRepository) GetOAuthSessionByState

func (r *OAuthSessionRepository) GetOAuthSessionByState(ctx context.Context, state string) (*models.OAuthAuthSession, error)

GetOAuthSessionByState retrieves an OAuth session by OAuth state parameter

func (*OAuthSessionRepository) GetUserOAuthSessions

func (r *OAuthSessionRepository) GetUserOAuthSessions(ctx context.Context, username string, limit int) ([]*models.OAuthAuthSession, error)

GetUserOAuthSessions retrieves all OAuth sessions for a user

func (*OAuthSessionRepository) SetOAuthSessionFlowStep

func (r *OAuthSessionRepository) SetOAuthSessionFlowStep(ctx context.Context, sessionID, step string, data map[string]interface{}) error

SetOAuthSessionFlowStep updates the flow step of an OAuth session

func (*OAuthSessionRepository) SetOAuthSessionUser

func (r *OAuthSessionRepository) SetOAuthSessionUser(ctx context.Context, sessionID, username string) error

SetOAuthSessionUser associates a user with an OAuth session (after login)

func (*OAuthSessionRepository) TouchOAuthSession

func (r *OAuthSessionRepository) TouchOAuthSession(ctx context.Context, sessionID string) error

TouchOAuthSession updates the last activity timestamp for a session

func (*OAuthSessionRepository) UpdateOAuthSession

func (r *OAuthSessionRepository) UpdateOAuthSession(ctx context.Context, session *models.OAuthAuthSession) error

UpdateOAuthSession updates an existing OAuth session

type ObjectRepository

type ObjectRepository struct {
	*EnhancedBaseRepository[*models.Object]
	// contains filtered or unexported fields
}

ObjectRepository implements object operations using enhanced DynamORM patterns

func NewObjectRepository

func NewObjectRepository(db core.DB, tableName, domain string, logger *zap.Logger) *ObjectRepository

NewObjectRepository creates a new object repository with enhanced functionality

func (*ObjectRepository) AddToCollection

func (r *ObjectRepository) AddToCollection(ctx context.Context, collection string, item *storage.CollectionItem) error

AddToCollection adds an item to a collection

func (*ObjectRepository) CleanupExpiredTombstones

func (r *ObjectRepository) CleanupExpiredTombstones(ctx context.Context, batchSize int) (int, error)

CleanupExpiredTombstones removes tombstones that have exceeded their TTL

func (*ObjectRepository) CountCollectionItems

func (r *ObjectRepository) CountCollectionItems(ctx context.Context, collection string) (int, error)

CountCollectionItems returns the count of items in a collection

func (*ObjectRepository) CountObjectReplies

func (r *ObjectRepository) CountObjectReplies(ctx context.Context, objectID string) (int, error)

CountObjectReplies counts the number of replies to an object

func (*ObjectRepository) CountQuotes

func (r *ObjectRepository) CountQuotes(ctx context.Context, noteID string) (int, error)

CountQuotes counts the number of quotes for a specific note

func (*ObjectRepository) CountReplies

func (r *ObjectRepository) CountReplies(ctx context.Context, objectID string) (int, error)

CountReplies counts the number of replies to an object using GSI6

func (*ObjectRepository) CountWithdrawnQuotes

func (r *ObjectRepository) CountWithdrawnQuotes(ctx context.Context, noteID string) (int, error)

CountWithdrawnQuotes counts the number of withdrawn quotes for a specific note

func (*ObjectRepository) CreateObject

func (r *ObjectRepository) CreateObject(ctx context.Context, object any) error

CreateObject stores a generic ActivityPub object

func (*ObjectRepository) CreateQuoteRelationship

func (r *ObjectRepository) CreateQuoteRelationship(ctx context.Context, quote *storage.QuoteRelationship) error

CreateQuoteRelationship creates a new quote relationship between notes

func (*ObjectRepository) CreateTombstone

func (r *ObjectRepository) CreateTombstone(ctx context.Context, tombstone *models.Tombstone) error

CreateTombstone creates a tombstone for a deleted object

func (*ObjectRepository) CreateUpdateHistory

func (r *ObjectRepository) CreateUpdateHistory(ctx context.Context, history *storage.UpdateHistory) error

CreateUpdateHistory creates a new update history entry for an object

func (*ObjectRepository) DeleteObject

func (r *ObjectRepository) DeleteObject(ctx context.Context, objectID string) error

DeleteObject deletes an object by ID

func (*ObjectRepository) GetCollectionItems

func (r *ObjectRepository) GetCollectionItems(ctx context.Context, collection string, limit int, cursor string) ([]*storage.CollectionItem, string, error)

GetCollectionItems retrieves items from a collection with pagination

func (*ObjectRepository) GetMissingReplies

func (r *ObjectRepository) GetMissingReplies(ctx context.Context, statusID string) ([]*storage.StatusSearchResult, error)

GetMissingReplies returns a list of known missing replies in a thread

func (*ObjectRepository) GetObject

func (r *ObjectRepository) GetObject(ctx context.Context, id string) (any, error)

GetObject retrieves an object by ID

func (*ObjectRepository) GetObjectHistory

func (r *ObjectRepository) GetObjectHistory(ctx context.Context, objectID string) ([]*storage.UpdateHistory, error)

GetObjectHistory retrieves the version history of an object

func (*ObjectRepository) GetObjectsByActor

func (r *ObjectRepository) GetObjectsByActor(ctx context.Context, actorID string, cursor string, limit int) ([]any, string, error)

GetObjectsByActor retrieves objects created by a specific actor

func (*ObjectRepository) GetQuoteType

func (r *ObjectRepository) GetQuoteType(ctx context.Context, statusID string) (string, error)

GetQuoteType returns the quote type for a status

func (*ObjectRepository) GetQuotesForNote

func (r *ObjectRepository) GetQuotesForNote(ctx context.Context, noteID string, limit int, cursor string) ([]*storage.QuoteRelationship, string, error)

GetQuotesForNote retrieves quotes for a specific note with pagination

func (*ObjectRepository) GetQuotesOfStatus

func (r *ObjectRepository) GetQuotesOfStatus(ctx context.Context, statusID string, limit int) ([]*storage.StatusSearchResult, error)

GetQuotesOfStatus retrieves quotes of a specific status

func (*ObjectRepository) GetReplies

func (r *ObjectRepository) GetReplies(ctx context.Context, objectID string, limit int, cursor string) ([]any, string, error)

GetReplies retrieves replies to an object with pagination

func (*ObjectRepository) GetReplyCount

func (r *ObjectRepository) GetReplyCount(ctx context.Context, statusID string) (int64, error)

GetReplyCount gets the reply count for a status

func (*ObjectRepository) GetStatus

func (r *ObjectRepository) GetStatus(ctx context.Context, statusID string) (any, error)

GetStatus retrieves a status by ID (alias for GetObject)

func (*ObjectRepository) GetStatusReplyCount

func (r *ObjectRepository) GetStatusReplyCount(ctx context.Context, statusID string) (int, error)

GetStatusReplyCount counts replies to a specific status (alias for CountReplies)

func (*ObjectRepository) GetThreadContext

func (r *ObjectRepository) GetThreadContext(ctx context.Context, statusID string) (*storage.ThreadContext, error)

GetThreadContext retrieves the thread context for a status with full hierarchy

func (*ObjectRepository) GetTombstone

func (r *ObjectRepository) GetTombstone(ctx context.Context, objectID string) (*models.Tombstone, error)

GetTombstone retrieves a tombstone by object ID

func (*ObjectRepository) GetTombstonesByActor

func (r *ObjectRepository) GetTombstonesByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Tombstone, string, error)

GetTombstonesByActor retrieves all tombstones created by a specific actor

func (*ObjectRepository) GetTombstonesByType

func (r *ObjectRepository) GetTombstonesByType(ctx context.Context, formerType string, limit int, cursor string) ([]*models.Tombstone, string, error)

GetTombstonesByType retrieves tombstones by their former type

func (*ObjectRepository) GetUpdateHistory

func (r *ObjectRepository) GetUpdateHistory(ctx context.Context, objectID string, limit int) ([]*storage.UpdateHistory, error)

GetUpdateHistory retrieves update history for an object

func (*ObjectRepository) GetUserStatusCount

func (r *ObjectRepository) GetUserStatusCount(ctx context.Context, userID string) (int, error)

GetUserStatusCount counts the number of statuses by a user

func (*ObjectRepository) IncrementReplyCount

func (r *ObjectRepository) IncrementReplyCount(ctx context.Context, objectID string) error

IncrementReplyCount increments the reply count for an object with proper atomic operations

func (*ObjectRepository) IsInCollection

func (r *ObjectRepository) IsInCollection(ctx context.Context, collection, itemID string) (bool, error)

IsInCollection checks if an item is in a collection

func (*ObjectRepository) IsQuoteAllowed

func (r *ObjectRepository) IsQuoteAllowed(ctx context.Context, statusID, quoterID string) (bool, error)

IsQuoteAllowed checks if a quote is allowed for a status by a quoter

func (*ObjectRepository) IsQuoted

func (r *ObjectRepository) IsQuoted(ctx context.Context, actorID, noteID string) (bool, error)

IsQuoted checks if a note is quoted by a specific actor

func (*ObjectRepository) IsTombstoned

func (r *ObjectRepository) IsTombstoned(ctx context.Context, objectID string) (bool, error)

IsTombstoned checks if an object has been tombstoned (deleted)

func (*ObjectRepository) IsWithdrawnFromQuotes

func (r *ObjectRepository) IsWithdrawnFromQuotes(ctx context.Context, statusID string) (bool, error)

IsWithdrawnFromQuotes checks if a status is withdrawn from quotes

func (*ObjectRepository) MarkThreadAsSynced

func (r *ObjectRepository) MarkThreadAsSynced(ctx context.Context, statusID string) error

MarkThreadAsSynced marks a thread as successfully synced

func (*ObjectRepository) RemoveFromCollection

func (r *ObjectRepository) RemoveFromCollection(ctx context.Context, collection, itemID string) error

RemoveFromCollection removes an item from a collection

func (*ObjectRepository) ReplaceObjectWithTombstone

func (r *ObjectRepository) ReplaceObjectWithTombstone(ctx context.Context, objectID, formerType, deletedBy string) error

ReplaceObjectWithTombstone atomically replaces an object with a tombstone

func (*ObjectRepository) SyncMissingRepliesFromRemote

func (r *ObjectRepository) SyncMissingRepliesFromRemote(ctx context.Context, statusID string) ([]*storage.StatusSearchResult, error)

SyncMissingRepliesFromRemote syncs missing replies from remote servers

func (*ObjectRepository) SyncThreadFromRemote

func (r *ObjectRepository) SyncThreadFromRemote(ctx context.Context, statusID string) (*storage.StatusSearchResult, error)

SyncThreadFromRemote syncs a thread from a remote server with proper background processing

func (*ObjectRepository) TombstoneObject

func (r *ObjectRepository) TombstoneObject(ctx context.Context, objectID string, deletedBy string) error

TombstoneObject marks an object as deleted by creating a tombstone

func (*ObjectRepository) UpdateObject

func (r *ObjectRepository) UpdateObject(ctx context.Context, object any) error

UpdateObject updates an existing object

func (*ObjectRepository) UpdateObjectWithHistory

func (r *ObjectRepository) UpdateObjectWithHistory(ctx context.Context, object any, updatedBy string) error

UpdateObjectWithHistory updates an object and tracks the edit history

func (*ObjectRepository) UpdateQuotePermissions

func (r *ObjectRepository) UpdateQuotePermissions(ctx context.Context, statusID string, permissions *storage.QuotePermissions) error

UpdateQuotePermissions updates the quote permissions for a status

func (*ObjectRepository) WithdrawQuote

func (r *ObjectRepository) WithdrawQuote(ctx context.Context, quoteNoteID string) error

WithdrawQuote withdraws a quote by marking it as withdrawn

func (*ObjectRepository) WithdrawStatusFromQuotes

func (r *ObjectRepository) WithdrawStatusFromQuotes(ctx context.Context, statusID string) error

WithdrawStatusFromQuotes withdraws a status from being quoted with proper cascade effects

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 PaginationConfig

type PaginationConfig struct {
	Limit  int
	Cursor string
}

PaginationConfig holds common pagination parameters

type PaginationOptions

type PaginationOptions struct {
	Cursor    string          `json:"cursor,omitempty"`     // Cursor for pagination
	Limit     int             `json:"limit"`                // Page size (default 20, max 50)
	SortOrder SearchSortOrder `json:"sort_order,omitempty"` // Sorting preference
}

PaginationOptions represents pagination parameters for search

func NewPaginationOptions

func NewPaginationOptions() *PaginationOptions

NewPaginationOptions creates pagination options with defaults

func (*PaginationOptions) Validate

func (p *PaginationOptions) Validate() error

Validate validates and normalizes pagination options

type PaginationResult

type PaginationResult struct {
	NextCursor   string `json:"next_cursor,omitempty"`   // Cursor for next page
	HasNextPage  bool   `json:"has_next_page"`           // Whether more results exist
	TotalScanned int    `json:"total_scanned,omitempty"` // Total items scanned (optional)
}

PaginationResult represents paginated search results

func CreatePaginationResult

func CreatePaginationResult(hasNextPage bool, nextCursor string, totalScanned int) *PaginationResult

CreatePaginationResult creates a pagination result with next cursor

type PaginationUtils

type PaginationUtils struct{}

PaginationUtils provides helpers for encoding, decoding, and validating cursors

func NewPaginationUtils

func NewPaginationUtils() *PaginationUtils

NewPaginationUtils creates a new PaginationUtils instance

func (*PaginationUtils) DecodeCursor

func (p *PaginationUtils) DecodeCursor(cursor string) (pk, sk string, err error)

DecodeCursor decodes pagination cursor from base64 format

func (*PaginationUtils) EncodeCursor

func (p *PaginationUtils) EncodeCursor(pk, sk string) string

EncodeCursor encodes pagination cursor using proper base64 encoding

type PatternAnalysis

type PatternAnalysis struct {
	Content     string          `json:"content"`
	Timestamp   time.Time       `json:"timestamp"`
	Matches     []*PatternMatch `json:"matches"`
	RiskScore   float64         `json:"risk_score"`
	Categories  []string        `json:"categories"`
	Confidence  float64         `json:"confidence"`
	ProcessTime int64           `json:"process_time_ms"`
}

PatternAnalysis represents the result of content analysis

type PatternFeedback

type PatternFeedback struct {
	PatternID    string    `json:"pattern_id"`
	FeedbackType string    `json:"feedback_type"` // "true_positive", "false_positive", "false_negative"
	ContentHash  string    `json:"content_hash"`
	UserID       string    `json:"user_id"`
	Timestamp    time.Time `json:"timestamp"`
	Notes        string    `json:"notes,omitempty"`
}

PatternFeedback represents user feedback about pattern accuracy

type PatternMatch

type PatternMatch struct {
	PatternID   string  `json:"pattern_id"`
	PatternType string  `json:"pattern_type"`
	Category    string  `json:"category"`
	Severity    string  `json:"severity"`
	IsMatch     bool    `json:"is_match"`
	Confidence  float64 `json:"confidence"`
	MatchTime   float64 `json:"match_time_ms"`
	Position    int     `json:"position"`
}

PatternMatch represents a single pattern match result

type PatternRepository

type PatternRepository struct {
	*EnhancedBaseRepository[*models.ModerationPattern]
}

PatternRepository handles moderation pattern storage operations using enhanced patterns

func NewPatternRepository

func NewPatternRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *PatternRepository

NewPatternRepository creates a new pattern repository with enhanced functionality

func (*PatternRepository) CreatePattern

func (r *PatternRepository) CreatePattern(ctx context.Context, pattern *models.ModerationPattern) error

CreatePattern creates a new moderation pattern

func (*PatternRepository) DeletePattern

func (r *PatternRepository) DeletePattern(ctx context.Context, patternID string) error

DeletePattern soft deletes a pattern by marking it inactive

func (*PatternRepository) GetPattern

func (r *PatternRepository) GetPattern(ctx context.Context, patternID string) (*models.ModerationPattern, error)

GetPattern retrieves a single pattern by ID

func (*PatternRepository) GetPatterns

func (r *PatternRepository) GetPatterns(ctx context.Context, category string, activeOnly bool) ([]*models.ModerationPattern, error)

GetPatterns retrieves patterns based on filter criteria

func (*PatternRepository) IncrementHitCount

func (r *PatternRepository) IncrementHitCount(ctx context.Context, patternID string) error

IncrementHitCount increments the hit count for a pattern

func (*PatternRepository) LoadActivePatterns

func (r *PatternRepository) LoadActivePatterns(ctx context.Context) ([]*models.ModerationPattern, error)

LoadActivePatterns loads all active patterns

func (*PatternRepository) UpdatePattern

func (r *PatternRepository) UpdatePattern(ctx context.Context, patternID string, updates *models.ModerationPattern) error

UpdatePattern updates an existing pattern

type PerformanceAnalytics

type PerformanceAnalytics struct {
	PopularQueries  []*models.SearchQueryStats `json:"popular_queries"`
	Metrics         map[string]interface{}     `json:"metrics"`
	Recommendations []string                   `json:"recommendations"`
}

PerformanceAnalytics contains performance metrics and recommendations

type PermissionService

type PermissionService interface {
	CheckPermissions(ctx context.Context, actor string, action string, resource BaseModel) error
	HasPermission(ctx context.Context, actor string, permission string) bool
}

PermissionService provides standardized permission checking

type PollRepository

type PollRepository struct {
	*EnhancedBaseRepository[*models.Poll]
	// contains filtered or unexported fields
}

PollRepository implements the PollRepository interface using enhanced DynamORM patterns

func NewPollRepository

func NewPollRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *PollRepository

NewPollRepository creates a new PollRepository with enhanced functionality and cost tracking

func (*PollRepository) CreatePoll

func (r *PollRepository) CreatePoll(ctx context.Context, poll *storage.Poll) error

CreatePoll creates a new poll in DynamoDB

func (*PollRepository) GetPoll

func (r *PollRepository) GetPoll(ctx context.Context, pollID string) (*storage.Poll, error)

GetPoll retrieves a poll by ID

func (*PollRepository) GetPollByStatusID

func (r *PollRepository) GetPollByStatusID(ctx context.Context, statusID string) (*storage.Poll, error)

GetPollByStatusID retrieves a poll by its associated status ID

func (*PollRepository) GetPollVotes

func (r *PollRepository) GetPollVotes(ctx context.Context, pollID string) (map[string][]int, error)

GetPollVotes retrieves all votes for a poll

func (*PollRepository) HasUserVoted

func (r *PollRepository) HasUserVoted(ctx context.Context, pollID string, userID string) (bool, []int, error)

HasUserVoted checks if a user has voted on a poll

func (*PollRepository) VoteOnPoll

func (r *PollRepository) VoteOnPoll(ctx context.Context, pollID string, voterID string, choices []int) error

VoteOnPoll records a vote on a poll

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 This structure is critical for media processing pipeline - preserves ALL functionality

type PublicKeyCacheRepository

type PublicKeyCacheRepository struct {
	*EnhancedBaseRepository[*models.PublicKeyCache]
}

PublicKeyCacheRepository handles caching of public keys for HTTP signature verification

func NewPublicKeyCacheRepository

func NewPublicKeyCacheRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *PublicKeyCacheRepository

NewPublicKeyCacheRepository creates a new public key cache repository with enhanced functionality

func (*PublicKeyCacheRepository) GetByActorURL

func (r *PublicKeyCacheRepository) GetByActorURL(ctx context.Context, actorURL string) (*models.PublicKeyCache, error)

GetByActorURL retrieves a cached public key by actor URL

func (*PublicKeyCacheRepository) InvalidateCache

func (r *PublicKeyCacheRepository) InvalidateCache(ctx context.Context, actorURL string) error

InvalidateCache removes a cached key (useful when verification fails consistently)

func (*PublicKeyCacheRepository) RefreshKey

func (r *PublicKeyCacheRepository) RefreshKey(ctx context.Context, actorURL, keyID, publicKeyPEM, algorithm string) error

RefreshKey updates an existing cache entry with a new public key

func (*PublicKeyCacheRepository) Store

func (r *PublicKeyCacheRepository) Store(ctx context.Context, actorURL, keyID, publicKeyPEM, algorithm string) (*models.PublicKeyCache, error)

Store caches a public key with automatic TTL

func (*PublicKeyCacheRepository) UpdateStats

func (r *PublicKeyCacheRepository) UpdateStats(ctx context.Context, actorURL string, success bool) error

UpdateStats updates the success/failure statistics for a cached key

type PublicationMemberRepository

type PublicationMemberRepository struct {
	*EnhancedBaseRepository[*models.PublicationMember]
}

PublicationMemberRepository implements publication member operations

func NewPublicationMemberRepository

func NewPublicationMemberRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *PublicationMemberRepository

NewPublicationMemberRepository creates a new publication member repository

func (*PublicationMemberRepository) CreateMember

CreateMember adds a new member

func (*PublicationMemberRepository) DeleteMember

func (r *PublicationMemberRepository) DeleteMember(ctx context.Context, publicationID, userID string) error

DeleteMember removes a member

func (*PublicationMemberRepository) GetMember

func (r *PublicationMemberRepository) GetMember(ctx context.Context, publicationID, userID string) (*models.PublicationMember, error)

GetMember retrieves a member by publication ID and user ID

func (*PublicationMemberRepository) ListMembers

func (r *PublicationMemberRepository) ListMembers(ctx context.Context, publicationID string) ([]*models.PublicationMember, error)

ListMembers lists all members of a publication

func (*PublicationMemberRepository) ListMembershipsForUserPaginated

func (r *PublicationMemberRepository) ListMembershipsForUserPaginated(ctx context.Context, userID string, limit int, cursor string) ([]*models.PublicationMember, string, error)

ListMembershipsForUserPaginated lists publications a user is a member of. Cursor values are gsi1SK values (PUBLICATION#...).

type PublicationRepository

type PublicationRepository struct {
	*EnhancedBaseRepository[*models.Publication]
}

PublicationRepository implements publication operations

func NewPublicationRepository

func NewPublicationRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *PublicationRepository

NewPublicationRepository creates a new publication repository

func (*PublicationRepository) CreatePublication

func (r *PublicationRepository) CreatePublication(ctx context.Context, publication *models.Publication) error

CreatePublication creates a new publication

func (*PublicationRepository) GetPublication

func (r *PublicationRepository) GetPublication(ctx context.Context, id string) (*models.Publication, error)

GetPublication retrieves a publication by ID

type PushSubscriptionRepository

type PushSubscriptionRepository struct {
	*EnhancedBaseRepository[*models.PushSubscription]
	// contains filtered or unexported fields
}

PushSubscriptionRepository handles push subscription operations using enhanced DynamORM patterns

func NewPushSubscriptionRepository

func NewPushSubscriptionRepository(
	db core.DB,
	tableName string,
	logger *zap.Logger,
	costService *cost.TrackingService,
	secretsClient SecretsManagerClient,
	vapidSecretARN string,
	defaultSubject string,
) *PushSubscriptionRepository

NewPushSubscriptionRepository creates a new push subscription repository with enhanced functionality and cost tracking

func (*PushSubscriptionRepository) CreatePushSubscription

func (r *PushSubscriptionRepository) CreatePushSubscription(ctx context.Context, username string, subscription *storage.PushSubscription) error

CreatePushSubscription creates a new push subscription

func (*PushSubscriptionRepository) DeleteAllPushSubscriptions

func (r *PushSubscriptionRepository) DeleteAllPushSubscriptions(ctx context.Context, username string) error

DeleteAllPushSubscriptions deletes all push subscriptions for a user

func (*PushSubscriptionRepository) DeletePushSubscription

func (r *PushSubscriptionRepository) DeletePushSubscription(ctx context.Context, username, subscriptionID string) error

DeletePushSubscription deletes a push subscription

func (*PushSubscriptionRepository) GetPushSubscription

func (r *PushSubscriptionRepository) GetPushSubscription(ctx context.Context, username, subscriptionID string) (*storage.PushSubscription, error)

GetPushSubscription retrieves a push subscription by ID

func (*PushSubscriptionRepository) GetUserPushSubscriptions

func (r *PushSubscriptionRepository) GetUserPushSubscriptions(ctx context.Context, username string) ([]*storage.PushSubscription, error)

GetUserPushSubscriptions retrieves all push subscriptions for a user

func (*PushSubscriptionRepository) GetVAPIDKeys

GetVAPIDKeys retrieves the VAPID keys for the instance

func (*PushSubscriptionRepository) SetVAPIDKeys

func (r *PushSubscriptionRepository) SetVAPIDKeys(ctx context.Context, keys *storage.VAPIDKeys) error

SetVAPIDKeys stores the VAPID keys for the instance

func (*PushSubscriptionRepository) UpdatePushSubscription

func (r *PushSubscriptionRepository) UpdatePushSubscription(ctx context.Context, username, subscriptionID string, alerts storage.PushSubscriptionAlerts) error

UpdatePushSubscription updates the alerts for a push subscription

type QualityMetrics

type QualityMetrics struct {
	AverageLength     float64 `json:"average_length"`     // Average content length
	MediaRatio        float64 `json:"media_ratio"`        // Posts with media
	LinkRatio         float64 `json:"link_ratio"`         // Posts with links
	ReplyRatio        float64 `json:"reply_ratio"`        // Reply posts ratio
	CrossPostRatio    float64 `json:"cross_post_ratio"`   // Cross-platform posts
	LanguageDiversity int     `json:"language_diversity"` // Number of languages
}

QualityMetrics represents content quality indicators

type QueryBuilder

type QueryBuilder[T any] struct {
	// contains filtered or unexported fields
}

QueryBuilder provides a fluent interface for building queries with less duplication

func NewQueryBuilder

func NewQueryBuilder[T any](ctx context.Context, q *QueryUtils) *QueryBuilder[T]

NewQueryBuilder creates a new query builder

func (*QueryBuilder[T]) Execute

func (qb *QueryBuilder[T]) Execute() (*QueryResult[T], error)

Execute runs the query and returns paginated results

func (*QueryBuilder[T]) WithIndex

func (qb *QueryBuilder[T]) WithIndex(indexName string) *QueryBuilder[T]

WithIndex sets the GSI index name

func (*QueryBuilder[T]) WithLimit

func (qb *QueryBuilder[T]) WithLimit(limit int) *QueryBuilder[T]

WithLimit sets the query limit

func (*QueryBuilder[T]) WithPK

func (qb *QueryBuilder[T]) WithPK(pk string) *QueryBuilder[T]

WithPK sets the partition key

func (*QueryBuilder[T]) WithSK

func (qb *QueryBuilder[T]) WithSK(sk string) *QueryBuilder[T]

WithSK sets the sort key

func (*QueryBuilder[T]) WithSKPrefix

func (qb *QueryBuilder[T]) WithSKPrefix(prefix string) *QueryBuilder[T]

WithSKPrefix sets the sort key prefix for BEGINS_WITH queries

type QueryCacheRepository

type QueryCacheRepository struct {
	*EnhancedBaseRepository[*models.QueryCacheEntry]
	// contains filtered or unexported fields
}

QueryCacheRepository handles query cache operations using enhanced patterns

func NewQueryCacheRepository

func NewQueryCacheRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService, instanceRepo *FederationInstanceRepository, routeRepo *RouteOptimizerRepository) *QueryCacheRepository

NewQueryCacheRepository creates a new query cache repository with enhanced functionality

func (*QueryCacheRepository) BatchGetInstances

func (r *QueryCacheRepository) BatchGetInstances(ctx context.Context, instanceIDs []string) ([]*types.Instance, error)

BatchGetInstances performs batch get for multiple instances with cache and database fallback

func (*QueryCacheRepository) CleanupExpiredEntries

func (r *QueryCacheRepository) CleanupExpiredEntries(_ context.Context) error

CleanupExpiredEntries removes expired cache entries (handled by TTL, but can be called manually)

func (*QueryCacheRepository) GetCachedValue

func (r *QueryCacheRepository) GetCachedValue(ctx context.Context, cacheKey string) (interface{}, error)

GetCachedValue retrieves a cached value by key

func (*QueryCacheRepository) GetInstance

func (r *QueryCacheRepository) GetInstance(ctx context.Context, instanceID string) (*types.Instance, error)

GetInstance retrieves a cached instance or nil if not found

func (*QueryCacheRepository) GetInstancesByStatus

func (r *QueryCacheRepository) GetInstancesByStatus(ctx context.Context, status types.InstanceStatus) ([]*types.Instance, error)

GetInstancesByStatus retrieves cached instances by status with database fallback

func (*QueryCacheRepository) GetMetricsInRange

func (r *QueryCacheRepository) GetMetricsInRange(ctx context.Context, routeID string, start, end time.Time, limit int) ([]*types.DeliveryResult, error)

GetMetricsInRange retrieves delivery results for metrics queries

func (*QueryCacheRepository) InvalidateCachePattern

func (r *QueryCacheRepository) InvalidateCachePattern(ctx context.Context, pattern string) error

InvalidateCachePattern removes cache entries matching a pattern

func (*QueryCacheRepository) PrewarmActiveInstances

func (r *QueryCacheRepository) PrewarmActiveInstances(ctx context.Context) error

PrewarmActiveInstances preloads active instances into cache

func (*QueryCacheRepository) SetCachedValue

func (r *QueryCacheRepository) SetCachedValue(ctx context.Context, cacheKey string, value interface{}, size int, ttl time.Duration) error

SetCachedValue stores a value in the cache

func (*QueryCacheRepository) SetInstance

func (r *QueryCacheRepository) SetInstance(ctx context.Context, instance *types.Instance, ttl time.Duration) error

SetInstance caches an instance

func (*QueryCacheRepository) SetInstancesByStatus

func (r *QueryCacheRepository) SetInstancesByStatus(ctx context.Context, status types.InstanceStatus, instances []*types.Instance, ttl time.Duration) error

SetInstancesByStatus caches instances by status

type QueryOptions

type QueryOptions struct {
	Limit      int
	Cursor     string
	SortOrder  string // "ASC" or "DESC"
	IndexName  string
	FilterExpr string
}

QueryOptions represents common query options

type QueryResult

type QueryResult[T any] struct {
	Items      []T
	NextCursor string
	HasMore    bool
}

QueryResult represents a generic query result with pagination

func GenericList

func GenericList[T any](ctx context.Context, q *QueryUtils, pk, skPrefix string, opts *QueryOptions) (*QueryResult[T], error)

GenericList performs a type-safe list query with pagination

type QueryUtils

type QueryUtils struct {
	// contains filtered or unexported fields
}

QueryUtils provides common query patterns used across repositories

func NewQueryUtils

func NewQueryUtils(db core.DB, logger *zap.Logger) *QueryUtils

NewQueryUtils creates a new QueryUtils instance

func (*QueryUtils) AddToCollectionHelper

func (q *QueryUtils) AddToCollectionHelper(ctx context.Context, collection string, item *storage.CollectionItem, db core.DB) error

AddToCollectionHelper provides a shared implementation for adding items to collections This eliminates duplication between ObjectRepository and RelationshipRepository AddToCollection methods

func (*QueryUtils) BatchDeleteQuery

func (q *QueryUtils) BatchDeleteQuery(ctx context.Context, keys []struct{ PK, SK string }) error

BatchDeleteQuery performs batch delete operations

func (*QueryUtils) CountQuery

func (q *QueryUtils) CountQuery(ctx context.Context, pk string, indexName string) (int, error)

CountQuery performs count operations with consistent error handling

func (*QueryUtils) CreateWithCondition

func (q *QueryUtils) CreateWithCondition(ctx context.Context, model interface{}) error

CreateWithCondition creates an item with condition checking (for idempotency)

func (*QueryUtils) DeleteItem

func (q *QueryUtils) DeleteItem(ctx context.Context, pk, sk string, model interface{}) error

DeleteItem performs a generic delete operation with error handling

func (*QueryUtils) DeleteWithNotFoundHandling

func (q *QueryUtils) DeleteWithNotFoundHandling(ctx context.Context, pk, sk string, model interface{}, operationType, param1, param2 string) error

DeleteWithNotFoundHandling performs a delete operation that treats NotFound as success This is a common pattern where deletion is idempotent (deleting non-existing items succeeds)

func (*QueryUtils) ExistsQuery

func (q *QueryUtils) ExistsQuery(ctx context.Context, pk, sk string) (bool, error)

ExistsQuery checks if an item exists with consistent error handling

func (*QueryUtils) FilterActiveItems

func (q *QueryUtils) FilterActiveItems(items []map[string]interface{}, currentTimestamp int64) []map[string]interface{}

FilterActiveItems filters out expired/inactive items based on common patterns

func (*QueryUtils) GSIStatusQuery

func (q *QueryUtils) GSIStatusQuery(ctx context.Context, indexName, status string, opts *QueryOptions) (*QueryResult[map[string]interface{}], error)

GSIStatusQuery performs common status-based GSI queries

func (*QueryUtils) GetItemByPK

func (q *QueryUtils) GetItemByPK(ctx context.Context, pk, sk string, result interface{}) error

GetItemByPK retrieves a single item by its primary key and sort key

func (*QueryUtils) QueryByGSI

func (q *QueryUtils) QueryByGSI(ctx context.Context, indexName, gsiPK, gsiSK string, opts *QueryOptions) (*QueryResult[map[string]interface{}], error)

QueryByGSI performs a generic GSI query with pagination

func (*QueryUtils) QueryWithPrefix

func (q *QueryUtils) QueryWithPrefix(ctx context.Context, pk, skPrefix string, opts *QueryOptions) (*QueryResult[map[string]interface{}], error)

QueryWithPrefix performs a query with SK prefix matching

func (*QueryUtils) TimeRangeQuery

func (q *QueryUtils) TimeRangeQuery(ctx context.Context, pk string, startTime, endTime int64, opts *QueryOptions) (*QueryResult[map[string]interface{}], error)

TimeRangeQuery performs queries with time range filtering

func (*QueryUtils) UpdateItem

func (q *QueryUtils) UpdateItem(ctx context.Context, model interface{}) error

UpdateItem performs a generic update operation with error handling

func (*QueryUtils) UserRelationshipQuery

func (q *QueryUtils) UserRelationshipQuery(ctx context.Context, username, relationshipType string, opts *QueryOptions) (*QueryResult[map[string]interface{}], error)

UserRelationshipQuery performs a common pattern for querying user relationships

type QuoteRepository

type QuoteRepository struct {
	// contains filtered or unexported fields
}

QuoteRepository implements quote operations using enhanced DynamORM patterns

func NewQuoteRepository

func NewQuoteRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *QuoteRepository

NewQuoteRepository creates a new quote repository with enhanced functionality

func (*QuoteRepository) CreateQuotePermissions

func (r *QuoteRepository) CreateQuotePermissions(ctx context.Context, permissions *models.QuotePermissions) error

CreateQuotePermissions creates new quote permissions for a user

func (*QuoteRepository) CreateQuoteRelationship

func (r *QuoteRepository) CreateQuoteRelationship(ctx context.Context, relationship *models.QuoteRelationship) error

CreateQuoteRelationship creates a new quote relationship

func (*QuoteRepository) DecrementQuoteCount

func (r *QuoteRepository) DecrementQuoteCount(_ context.Context, statusID string) error

DecrementQuoteCount decrements the quote count for a status

func (*QuoteRepository) DeleteQuotePermissions

func (r *QuoteRepository) DeleteQuotePermissions(ctx context.Context, username string) error

DeleteQuotePermissions deletes quote permissions for a user

func (*QuoteRepository) DeleteQuoteRelationship

func (r *QuoteRepository) DeleteQuoteRelationship(ctx context.Context, quoteStatusID, targetStatusID string) error

DeleteQuoteRelationship deletes a quote relationship

func (*QuoteRepository) GetQuoteCount

func (r *QuoteRepository) GetQuoteCount(ctx context.Context, statusID string) (int64, error)

GetQuoteCount gets the total number of quotes for a status

func (*QuoteRepository) GetQuotePermissions

func (r *QuoteRepository) GetQuotePermissions(ctx context.Context, username string) (*models.QuotePermissions, error)

GetQuotePermissions retrieves quote permissions for a user

func (*QuoteRepository) GetQuoteRelationship

func (r *QuoteRepository) GetQuoteRelationship(ctx context.Context, quoteStatusID, targetStatusID string) (*models.QuoteRelationship, error)

GetQuoteRelationship retrieves a quote relationship by quoter and target note IDs

func (*QuoteRepository) GetQuotesByUser

GetQuotesByUser retrieves quotes created by a specific user

func (*QuoteRepository) GetQuotesForStatus

GetQuotesForStatus retrieves quotes for a given status using GSI1

func (*QuoteRepository) IncrementQuoteCount

func (r *QuoteRepository) IncrementQuoteCount(_ context.Context, statusID string) error

IncrementQuoteCount increments the quote count for a status Note: This is typically handled by updating the Status model directly

func (*QuoteRepository) UpdateQuotePermissions

func (r *QuoteRepository) UpdateQuotePermissions(ctx context.Context, permissions *models.QuotePermissions) error

UpdateQuotePermissions updates existing quote permissions

func (*QuoteRepository) UpdateQuoteRelationship

func (r *QuoteRepository) UpdateQuoteRelationship(ctx context.Context, relationship *models.QuoteRelationship) error

UpdateQuoteRelationship updates an existing quote relationship

func (*QuoteRepository) WithdrawQuotes

func (r *QuoteRepository) WithdrawQuotes(ctx context.Context, noteID, userID string) (int, error)

WithdrawQuotes withdraws all quotes of a note created by a specific user

type RateLimitRepository

type RateLimitRepository struct {
	// contains filtered or unexported fields
}

RateLimitRepository handles rate limiting operations using enhanced repository patterns

func NewRateLimitRepository

func NewRateLimitRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RateLimitRepository

NewRateLimitRepository creates a new RateLimitRepository with enhanced functionality

func (*RateLimitRepository) CheckAPIRateLimit

func (r *RateLimitRepository) CheckAPIRateLimit(ctx context.Context, userID, endpoint string, limit int, window time.Duration) error

CheckAPIRateLimit checks and updates API rate limiting for a user/endpoint combination using BaseRepository

func (*RateLimitRepository) CheckCommunityNoteRateLimit

func (r *RateLimitRepository) CheckCommunityNoteRateLimit(ctx context.Context, userID string, limit int) (bool, int, error)

CheckCommunityNoteRateLimit checks if a user can create more community notes today using BaseRepository

func (*RateLimitRepository) CheckFederationRateLimit

func (r *RateLimitRepository) CheckFederationRateLimit(ctx context.Context, domain, endpoint string, limit int, window time.Duration) error

CheckFederationRateLimit checks and updates federation rate limiting for a domain/endpoint combination

func (*RateLimitRepository) CheckFixedWindowRateLimit added in v1.1.2

func (r *RateLimitRepository) CheckFixedWindowRateLimit(ctx context.Context, identifier, bucket string, limit int, window time.Duration) (allowed bool, remaining int, resetTime time.Time, err error)

CheckFixedWindowRateLimit atomically increments a counter for a fixed time window and returns the rate limit state.

Unlike CheckAPIRateLimit, this helper does not apply escalating penalties or record violations. It is intended for strict, predictable throttles (e.g., automation safety rails).

Fail-open: storage errors are returned to the caller to decide policy; callers should generally allow the request rather than failing user traffic due to rate limit storage outages.

func (*RateLimitRepository) ClearLoginAttempts

func (r *RateLimitRepository) ClearLoginAttempts(ctx context.Context, identifier string) error

ClearLoginAttempts clears all login attempts for an identifier using BaseRepository

func (*RateLimitRepository) GetAPIRateLimitInfo

func (r *RateLimitRepository) GetAPIRateLimitInfo(ctx context.Context, userID, endpoint string, limit int, window time.Duration) (remaining int, resetTime time.Time, err error)

GetAPIRateLimitInfo returns current rate limit info for response headers

func (*RateLimitRepository) GetFederationRateLimitInfo

func (r *RateLimitRepository) GetFederationRateLimitInfo(ctx context.Context, domain, endpoint string, limit int, window time.Duration) (remaining int, resetTime time.Time, err error)

GetFederationRateLimitInfo returns current federation rate limit info

func (*RateLimitRepository) GetLoginAttemptCount

func (r *RateLimitRepository) GetLoginAttemptCount(ctx context.Context, identifier string, since time.Time) (int, error)

GetLoginAttemptCount returns the number of login attempts since the given time

func (*RateLimitRepository) GetViolationCount

func (r *RateLimitRepository) GetViolationCount(ctx context.Context, userID, domain string, since time.Duration) (int, error)

GetViolationCount returns the number of violations in a time period for escalating penalties

func (*RateLimitRepository) ImposeLockout

func (r *RateLimitRepository) ImposeLockout(ctx context.Context, identifier string, duration time.Duration) error

ImposeLockout creates or updates a lockout record for the given identifier.

This is used by security and governance rails (including LLM agent circuit breakers).

func (*RateLimitRepository) IsDomainBlocked

func (r *RateLimitRepository) IsDomainBlocked(ctx context.Context, domain string) (bool, time.Time, error)

IsDomainBlocked checks if a federation domain is currently blocked

func (*RateLimitRepository) IsRateLimited

func (r *RateLimitRepository) IsRateLimited(ctx context.Context, identifier string) (bool, time.Time, error)

IsRateLimited checks if an identifier is currently rate limited using BaseRepository

func (*RateLimitRepository) IsUserBlocked

func (r *RateLimitRepository) IsUserBlocked(ctx context.Context, userID string) (bool, time.Time, error)

IsUserBlocked checks if a user is currently blocked due to rate limiting

func (*RateLimitRepository) RecordLoginAttempt

func (r *RateLimitRepository) RecordLoginAttempt(ctx context.Context, identifier string, success bool) error

RecordLoginAttempt records a login attempt for rate limiting using BaseRepository

type RecoveryRepository

type RecoveryRepository struct {
	*EnhancedBaseRepository[*models.RecoveryRequest]
}

RecoveryRepository implements recovery operations using enhanced repository patterns

func NewRecoveryRepository

func NewRecoveryRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RecoveryRepository

NewRecoveryRepository creates a new recovery repository with enhanced functionality

func (*RecoveryRepository) CountUnusedRecoveryCodes

func (r *RecoveryRepository) CountUnusedRecoveryCodes(ctx context.Context, username string) (int, error)

CountUnusedRecoveryCodes counts how many unused recovery codes the user has

func (*RecoveryRepository) DeleteAllRecoveryCodes

func (r *RecoveryRepository) DeleteAllRecoveryCodes(ctx context.Context, username string) error

DeleteAllRecoveryCodes deletes all recovery codes for a user

func (*RecoveryRepository) DeleteRecoveryRequest

func (r *RecoveryRepository) DeleteRecoveryRequest(ctx context.Context, requestID string) error

DeleteRecoveryRequest deletes a recovery request

func (*RecoveryRepository) DeleteRecoveryToken

func (r *RecoveryRepository) DeleteRecoveryToken(ctx context.Context, key string) error

DeleteRecoveryToken deletes a recovery token

func (*RecoveryRepository) DeleteTrustee

func (r *RecoveryRepository) DeleteTrustee(ctx context.Context, username, trusteeActorID string) error

DeleteTrustee removes a trustee

func (*RecoveryRepository) GetActiveRecoveryRequests

func (r *RecoveryRepository) GetActiveRecoveryRequests(ctx context.Context, username string) ([]*storage.SocialRecoveryRequest, error)

GetActiveRecoveryRequests gets all active recovery requests for a user

func (*RecoveryRepository) GetRecoveryCodes

func (r *RecoveryRepository) GetRecoveryCodes(ctx context.Context, username string) ([]*storage.RecoveryCodeItem, error)

GetRecoveryCodes retrieves all recovery codes for a user

func (*RecoveryRepository) GetRecoveryRequest

func (r *RecoveryRepository) GetRecoveryRequest(ctx context.Context, requestID string) (*storage.SocialRecoveryRequest, error)

GetRecoveryRequest retrieves a recovery request by ID

func (*RecoveryRepository) GetRecoveryToken

func (r *RecoveryRepository) GetRecoveryToken(ctx context.Context, key string) (map[string]any, error)

GetRecoveryToken retrieves a recovery token by key

func (*RecoveryRepository) GetTrustees

func (r *RecoveryRepository) GetTrustees(ctx context.Context, username string) ([]*storage.TrusteeConfig, error)

GetTrustees retrieves all trustees for a user

func (*RecoveryRepository) MarkRecoveryCodeUsed

func (r *RecoveryRepository) MarkRecoveryCodeUsed(ctx context.Context, username, codeHash string) error

MarkRecoveryCodeUsed marks a recovery code as used

func (*RecoveryRepository) StoreRecoveryCode

func (r *RecoveryRepository) StoreRecoveryCode(ctx context.Context, username string, code *storage.RecoveryCodeItem) error

StoreRecoveryCode stores a recovery code

func (*RecoveryRepository) StoreRecoveryRequest

func (r *RecoveryRepository) StoreRecoveryRequest(ctx context.Context, request *storage.SocialRecoveryRequest) error

StoreRecoveryRequest stores a social recovery request

func (*RecoveryRepository) StoreRecoveryToken

func (r *RecoveryRepository) StoreRecoveryToken(ctx context.Context, key string, data map[string]any) error

StoreRecoveryToken stores a generic recovery token with data

func (*RecoveryRepository) StoreTrustee

func (r *RecoveryRepository) StoreTrustee(ctx context.Context, username string, trustee *storage.TrusteeConfig) error

StoreTrustee stores a trustee configuration for social recovery

func (*RecoveryRepository) UpdateRecoveryRequest

func (r *RecoveryRepository) UpdateRecoveryRequest(ctx context.Context, request *storage.SocialRecoveryRequest) error

UpdateRecoveryRequest updates a recovery request

func (*RecoveryRepository) UpdateTrusteeConfirmed

func (r *RecoveryRepository) UpdateTrusteeConfirmed(ctx context.Context, username, trusteeActorID string, confirmed bool) error

UpdateTrusteeConfirmed updates the confirmed status of a trustee

type RelationshipBase

type RelationshipBase struct {
	// contains filtered or unexported fields
}

RelationshipBase provides common functionality for relationship repositories

func NewRelationshipBase

func NewRelationshipBase(db core.DB, tableName string, logger *zap.Logger, relType RelationshipType) *RelationshipBase

NewRelationshipBase creates a new relationship base repository

func (*RelationshipBase) CountRelationshipsByActor

func (r *RelationshipBase) CountRelationshipsByActor(ctx context.Context, actor string) (int, error)

CountRelationshipsByActor returns the count of relationships for an actor

func (*RelationshipBase) CountRelationshipsByObject

func (r *RelationshipBase) CountRelationshipsByObject(ctx context.Context, object string) (int, error)

CountRelationshipsByObject returns the count of relationships for an object

func (*RelationshipBase) CreateRelationship

func (r *RelationshipBase) CreateRelationship(ctx context.Context, actor, object, id string) error

CreateRelationship creates a new relationship with idempotency

func (*RelationshipBase) DeleteRelationship

func (r *RelationshipBase) DeleteRelationship(ctx context.Context, actor, object string) error

DeleteRelationship removes a relationship with idempotency

func (*RelationshipBase) ExistsRelationship

func (r *RelationshipBase) ExistsRelationship(ctx context.Context, actor, object string) (bool, error)

ExistsRelationship checks if a relationship exists

func (*RelationshipBase) GetRelationship

func (r *RelationshipBase) GetRelationship(ctx context.Context, actor, object string) (*RelationshipModel, error)

GetRelationship retrieves a specific relationship

func (*RelationshipBase) GetRelationshipsByActor

func (r *RelationshipBase) GetRelationshipsByActor(ctx context.Context, actor string, limit int, cursor string) ([]*RelationshipModel, string, error)

GetRelationshipsByActor retrieves all relationships for an actor with pagination

func (*RelationshipBase) GetRelationshipsByObject

func (r *RelationshipBase) GetRelationshipsByObject(ctx context.Context, object string, limit int, cursor string) ([]*RelationshipModel, string, error)

GetRelationshipsByObject retrieves all relationships for an object with pagination

type RelationshipHelper

type RelationshipHelper struct {
	DB           core.DB
	Logger       *zap.Logger
	RelationType string // "block" or "mute"
}

RelationshipHelper handles common operations for block/mute relationships

func NewRelationshipHelper

func NewRelationshipHelper(db core.DB, logger *zap.Logger, relationType string) *RelationshipHelper

NewRelationshipHelper creates a new relationship helper

func (*RelationshipHelper) CheckRelationship

func (h *RelationshipHelper) CheckRelationship(
	ctx context.Context,
	actorActor, targetActor string,
	pkFormat, skFormat string,
	modelType interface{},
) (bool, error)

CheckRelationship checks if a relationship exists between two actors

func (*RelationshipHelper) DeleteRelationship

func (h *RelationshipHelper) DeleteRelationship(
	ctx context.Context,
	actorActor, targetActor string,
	pkFormat, skFormat string,
	modelType interface{},
) error

DeleteRelationship removes a relationship (for Undo operations)

func (*RelationshipHelper) GetRelatedUsers

func (h *RelationshipHelper) GetRelatedUsers(
	ctx context.Context,
	actorActor string,
	limit int,
	cursor string,
	pkFormat string,
	modelType interface{},
	_ string,
) ([]string, string, error)

GetRelatedUsers returns a list of users in a relationship with the given actor

func (*RelationshipHelper) GetUsersWhoRelated

func (h *RelationshipHelper) GetUsersWhoRelated(
	ctx context.Context,
	targetActor string,
	limit int,
	cursor string,
	gsiIndex string,
	gsiPKFormat string,
	modelType interface{},
	_ string,
) ([]string, string, error)

GetUsersWhoRelated returns a list of users who have a relationship with the given actor

type RelationshipModel

type RelationshipModel struct {
	PK        string    `theorydb:"PK,pk"`
	SK        string    `theorydb:"SK,sk"`
	GSI1PK    string    `theorydb:"GSI1PK,gsi1pk"`
	GSI1SK    string    `theorydb:"GSI1SK,gsi1sk"`
	Actor     string    `theorydb:"Actor"`
	Object    string    `theorydb:"Object"`
	Type      string    `theorydb:"Type"`
	CreatedAt time.Time `theorydb:"CreatedAt"`
	ID        string    `theorydb:"ID"`
}

RelationshipModel represents a generic relationship

type RelationshipPaginationConfig

type RelationshipPaginationConfig struct {
	IndexName   string // "" for main table, "gsi1", "gsi5", etc. for GSIs
	PKFormat    string // Format string for partition key, e.g. "ACTOR#%s#BLOCKS"
	SKField     string // Field name for sort key in cursor, e.g. "SK" or gsi1SKField
	ActorField  string // "Actor" or "Object" - which field to extract for result
	ErrorPrefix string // Prefix for error messages, e.g. "blocked users" or "muted users"
	ModelType   string // modelTypeBlock or "Mute" - which model to query
}

RelationshipPaginationConfig holds configuration for paginated relationship queries

type RelationshipRepository

type RelationshipRepository struct {
	*EnhancedBaseRepository[*models.RelationshipRecord]
	// contains filtered or unexported fields
}

RelationshipRepository implements relationship operations using enhanced DynamORM patterns

func NewRelationshipRepository

func NewRelationshipRepository(db core.DB, tableName string, logger *zap.Logger) *RelationshipRepository

NewRelationshipRepository creates a new relationship repository with enhanced functionality

func NewRelationshipRepositoryWithCostTracking

func NewRelationshipRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RelationshipRepository

NewRelationshipRepositoryWithCostTracking creates a new relationship repository with cost tracking

func (*RelationshipRepository) AcceptFollowRequest

func (r *RelationshipRepository) AcceptFollowRequest(ctx context.Context, followerUsername, followingUsername string) error

AcceptFollowRequest accepts a follow request

func (*RelationshipRepository) AddToCollection

func (r *RelationshipRepository) AddToCollection(ctx context.Context, collection string, item *storage.CollectionItem) error

AddToCollection adds an item to a collection

func (*RelationshipRepository) BlockUser

func (r *RelationshipRepository) BlockUser(ctx context.Context, blockerID, blockedID string) error

BlockUser blocks another user

func (*RelationshipRepository) ClearCollection

func (r *RelationshipRepository) ClearCollection(ctx context.Context, collection string) error

ClearCollection removes all items from a collection

func (*RelationshipRepository) CountBlockedUsers

func (r *RelationshipRepository) CountBlockedUsers(ctx context.Context, blockerActor string) (int, error)

CountBlockedUsers returns the number of users blocked by the given actor

func (*RelationshipRepository) CountCollectionItems

func (r *RelationshipRepository) CountCollectionItems(ctx context.Context, collection string) (int, error)

CountCollectionItems returns the count of items in a collection

func (*RelationshipRepository) CountFollowers

func (r *RelationshipRepository) CountFollowers(ctx context.Context, username string) (int, error)

CountFollowers returns the number of followers for a user

func (*RelationshipRepository) CountFollowing

func (r *RelationshipRepository) CountFollowing(ctx context.Context, username string) (int, error)

CountFollowing returns the number of users that a user is following

func (*RelationshipRepository) CountMutedUsers

func (r *RelationshipRepository) CountMutedUsers(ctx context.Context, muterActor string) (int, error)

CountMutedUsers returns the number of users muted by the given actor

func (*RelationshipRepository) CountRelationshipsByDomain

func (r *RelationshipRepository) CountRelationshipsByDomain(ctx context.Context, domain string) (followers, following int, err error)

CountRelationshipsByDomain counts follower/following relationships involving a remote domain Returns (followers from domain, following to domain, error) Uses domain-aware GSIs (GSI2, GSI3) for O(1) indexed queries instead of full table scan

func (*RelationshipRepository) CountUsersWhoBlocked

func (r *RelationshipRepository) CountUsersWhoBlocked(ctx context.Context, blockedActor string) (int, error)

CountUsersWhoBlocked returns the number of users who have blocked the given actor

func (*RelationshipRepository) CountUsersWhoMuted

func (r *RelationshipRepository) CountUsersWhoMuted(ctx context.Context, mutedActor string) (int, error)

CountUsersWhoMuted returns the number of users who have muted the given actor

func (*RelationshipRepository) CreateBlock

func (r *RelationshipRepository) CreateBlock(ctx context.Context, blockerActor, blockedActor, activityID string) error

CreateBlock creates a new block relationship

func (*RelationshipRepository) CreateEndorsement

func (r *RelationshipRepository) CreateEndorsement(ctx context.Context, endorsement *storage.AccountPin) error

CreateEndorsement creates a new endorsement (account pin) relationship

func (*RelationshipRepository) CreateMove

func (r *RelationshipRepository) CreateMove(ctx context.Context, move *storage.Move) error

CreateMove creates a new move record

func (*RelationshipRepository) CreateMute

func (r *RelationshipRepository) CreateMute(ctx context.Context, muterActor, mutedActor, activityID string, hideNotifications bool, duration *time.Duration) error

CreateMute creates a new mute relationship

func (*RelationshipRepository) CreateRelationship

func (r *RelationshipRepository) CreateRelationship(ctx context.Context, followerUsername, followingUsername, activityID string) error

CreateRelationship creates a new follow relationship with enhanced validation and events

func (*RelationshipRepository) DeleteBlock

func (r *RelationshipRepository) DeleteBlock(ctx context.Context, blockerActor, blockedActor string) error

DeleteBlock removes a block relationship (for Undo Block)

func (*RelationshipRepository) DeleteEndorsement

func (r *RelationshipRepository) DeleteEndorsement(ctx context.Context, endorserID, endorsedID string) error

DeleteEndorsement removes an endorsement (account pin) relationship

func (*RelationshipRepository) DeleteMute

func (r *RelationshipRepository) DeleteMute(ctx context.Context, muterActor, mutedActor string) error

DeleteMute removes a mute relationship (for Undo Mute)

func (*RelationshipRepository) DeleteRelationship

func (r *RelationshipRepository) DeleteRelationship(ctx context.Context, followerUsername, followingUsername string) error

DeleteRelationship removes a follow relationship

func (*RelationshipRepository) GetAccountMoves

func (r *RelationshipRepository) GetAccountMoves(ctx context.Context, actor string) ([]*storage.Move, error)

GetAccountMoves retrieves all moves for an account (as actor)

func (*RelationshipRepository) GetBlock

func (r *RelationshipRepository) GetBlock(ctx context.Context, blockerActor, blockedActor string) (*storage.Block, error)

GetBlock retrieves a specific block relationship

func (*RelationshipRepository) GetBlockedUsers

func (r *RelationshipRepository) GetBlockedUsers(ctx context.Context, blockerActor string, limit int, cursor string) ([]string, string, error)

GetBlockedUsers returns a list of users blocked by the given actor

func (*RelationshipRepository) GetCollectionItems

func (r *RelationshipRepository) GetCollectionItems(ctx context.Context, collection string, limit int, cursor string) ([]*storage.CollectionItem, string, error)

GetCollectionItems retrieves items from a collection with pagination

func (*RelationshipRepository) GetEndorsements

func (r *RelationshipRepository) GetEndorsements(ctx context.Context, userID string, limit int, cursor string) ([]*storage.AccountPin, string, error)

GetEndorsements retrieves all endorsements (account pins) for a user

func (*RelationshipRepository) GetFollowRequest

func (r *RelationshipRepository) GetFollowRequest(ctx context.Context, followerID, targetID string) (*storage.RelationshipRecord, error)

GetFollowRequest gets a follow request by follower and target IDs

func (*RelationshipRepository) GetFollowerCount

func (r *RelationshipRepository) GetFollowerCount(ctx context.Context, userID string) (int64, error)

GetFollowerCount returns the number of followers for a user (interface method)

func (*RelationshipRepository) GetFollowers

func (r *RelationshipRepository) GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetFollowers retrieves all followers for a user

func (*RelationshipRepository) GetFollowing

func (r *RelationshipRepository) GetFollowing(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetFollowing retrieves all users that a user is following

func (*RelationshipRepository) GetFollowingCount

func (r *RelationshipRepository) GetFollowingCount(ctx context.Context, userID string) (int64, error)

GetFollowingCount returns the number of users that a user is following (interface method)

func (*RelationshipRepository) GetMove

func (r *RelationshipRepository) GetMove(ctx context.Context, actor string) (*storage.Move, error)

GetMove retrieves the most recent move for an actor

func (*RelationshipRepository) GetMoveByTarget

func (r *RelationshipRepository) GetMoveByTarget(ctx context.Context, target string) ([]*storage.Move, error)

GetMoveByTarget retrieves all moves to a specific target account

func (*RelationshipRepository) GetMute

func (r *RelationshipRepository) GetMute(ctx context.Context, muterActor, mutedActor string) (*storage.Mute, error)

GetMute retrieves a specific mute relationship

func (*RelationshipRepository) GetMutedUsers

func (r *RelationshipRepository) GetMutedUsers(ctx context.Context, muterActor string, limit int, cursor string) ([]string, string, error)

GetMutedUsers returns a list of users muted by the given actor

func (*RelationshipRepository) GetPendingFollowRequests

func (r *RelationshipRepository) GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetPendingFollowRequests retrieves pending follow requests for a user

func (*RelationshipRepository) GetPendingMoves

func (r *RelationshipRepository) GetPendingMoves(ctx context.Context, limit int) ([]*storage.Move, error)

GetPendingMoves retrieves moves that haven't been fully processed

func (*RelationshipRepository) GetRelationship

func (r *RelationshipRepository) GetRelationship(ctx context.Context, followerUsername, followingUsername string) (*models.RelationshipRecord, error)

GetRelationship retrieves a specific follow relationship

func (*RelationshipRepository) GetRelationshipNote

func (r *RelationshipRepository) GetRelationshipNote(ctx context.Context, userID, targetID string) (*storage.AccountNote, error)

GetRelationshipNote retrieves a private note on an account

func (*RelationshipRepository) GetUsersWhoBlocked

func (r *RelationshipRepository) GetUsersWhoBlocked(ctx context.Context, blockedActor string, limit int, cursor string) ([]string, string, error)

GetUsersWhoBlocked returns a list of users who have blocked the given actor

func (*RelationshipRepository) GetUsersWhoMuted

func (r *RelationshipRepository) GetUsersWhoMuted(ctx context.Context, mutedActor string, limit int, cursor string) ([]string, string, error)

GetUsersWhoMuted returns a list of users who have muted the given actor

func (*RelationshipRepository) HasFollowRequest

func (r *RelationshipRepository) HasFollowRequest(ctx context.Context, requesterID, targetID string) (bool, error)

HasFollowRequest checks if there's a follow request between two users

func (*RelationshipRepository) HasMovedFrom

func (r *RelationshipRepository) HasMovedFrom(ctx context.Context, oldActor, newActor string) (bool, error)

HasMovedFrom checks if newActor has moved from oldActor

func (*RelationshipRepository) HasPendingFollowRequest

func (r *RelationshipRepository) HasPendingFollowRequest(ctx context.Context, requesterID, targetID string) (bool, error)

HasPendingFollowRequest checks if there's a pending follow request between two users

func (*RelationshipRepository) IsBlocked

func (r *RelationshipRepository) IsBlocked(ctx context.Context, blockerActor, blockedActor string) (bool, error)

IsBlocked checks if one actor has blocked another

func (*RelationshipRepository) IsBlockedBidirectional

func (r *RelationshipRepository) IsBlockedBidirectional(ctx context.Context, actor1, actor2 string) (bool, error)

IsBlockedBidirectional checks if either actor has blocked the other

func (*RelationshipRepository) IsEndorsed

func (r *RelationshipRepository) IsEndorsed(ctx context.Context, userID, targetID string) (bool, error)

IsEndorsed checks if a user has endorsed (pinned) a target account

func (*RelationshipRepository) IsFollowing

func (r *RelationshipRepository) IsFollowing(ctx context.Context, followerUsername, targetActorID string) (bool, error)

IsFollowing checks if followerUsername is following the targetActorID

func (*RelationshipRepository) IsInCollection

func (r *RelationshipRepository) IsInCollection(ctx context.Context, collection, itemID string) (bool, error)

IsInCollection checks if an item is in a collection

func (*RelationshipRepository) IsMuted

func (r *RelationshipRepository) IsMuted(ctx context.Context, muterActor, mutedActor string) (bool, error)

IsMuted checks if one actor has muted another

func (*RelationshipRepository) RejectFollowRequest

func (r *RelationshipRepository) RejectFollowRequest(ctx context.Context, followerUsername, followingUsername string) error

RejectFollowRequest rejects a follow request

func (*RelationshipRepository) RemoveFromCollection

func (r *RelationshipRepository) RemoveFromCollection(ctx context.Context, collection, itemID string) error

RemoveFromCollection removes an item from a collection

func (*RelationshipRepository) UnblockUser

func (r *RelationshipRepository) UnblockUser(ctx context.Context, blockerID, blockedID string) error

UnblockUser removes a block relationship (wrapper for DeleteBlock)

func (*RelationshipRepository) Unfollow

func (r *RelationshipRepository) Unfollow(ctx context.Context, followerID, followingID string) error

Unfollow removes a follow relationship (wrapper for DeleteRelationship)

func (*RelationshipRepository) UnmuteUser

func (r *RelationshipRepository) UnmuteUser(ctx context.Context, muterID, mutedID string) error

UnmuteUser removes a mute relationship (wrapper for DeleteMute)

func (*RelationshipRepository) UpdateMoveProgress

func (r *RelationshipRepository) UpdateMoveProgress(ctx context.Context, actor, target string, _ map[string]interface{}) error

UpdateMoveProgress updates move migration progress

func (*RelationshipRepository) UpdateRelationship

func (r *RelationshipRepository) UpdateRelationship(ctx context.Context, followerUsername, followingUsername string, updates map[string]interface{}) error

UpdateRelationship updates relationship settings using enhanced validation and events

func (*RelationshipRepository) VerifyMove

func (r *RelationshipRepository) VerifyMove(ctx context.Context, actor, target string) error

VerifyMove marks a move as verified

type RelationshipType

type RelationshipType string

RelationshipType defines the type of relationship

const (
	// RelationshipTypeLike represents a like/favorite relationship
	RelationshipTypeLike RelationshipType = "like"
	// RelationshipTypeBlock represents a block relationship
	RelationshipTypeBlock RelationshipType = "block"
	// RelationshipTypeMute represents a mute relationship
	RelationshipTypeMute RelationshipType = "mute"
	// RelationshipTypeFollow represents a follow relationship
	RelationshipTypeFollow RelationshipType = "follow"
	// RelationshipTypeBookmark represents a bookmark relationship
	RelationshipTypeBookmark RelationshipType = "bookmark"
	// RelationshipTypeFavorite represents a favorite relationship
	RelationshipTypeFavorite RelationshipType = "favorite"
)

Relationship type constants

type RelayCostSummary

type RelayCostSummary struct {
	RelayURL                string
	Domain                  string
	StartTime               time.Time
	EndTime                 time.Time
	Count                   int
	TotalOperations         int64
	SuccessfulOperations    int64
	FailedOperations        int64
	TotalHTTPRequests       int64
	TotalDataTransferBytes  int64
	TotalLambdaDurationMs   int64
	TotalDynamoDBOps        int64
	TotalSQSMessages        int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostPerOperation float64
	SuccessRate             float64
	OperationBreakdown      map[string]*RelayOperationCostStats
}

RelayCostSummary represents cost summary for a relay

type RelayOperationCostStats

type RelayOperationCostStats struct {
	OperationType          string
	Count                  int64
	TotalCostMicroCents    int64
	TotalCostDollars       float64
	AverageCostMicroCents  int64
	TotalHTTPRequests      int64
	TotalDataTransferBytes int64
}

RelayOperationCostStats represents cost statistics for a specific relay operation type

type RelayRepository

type RelayRepository struct {
	*EnhancedBaseRepository[*models.Relay]
}

RelayRepository implements relay operations using enhanced patterns

func NewRelayRepository

func NewRelayRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RelayRepository

NewRelayRepository creates a new relay repository with enhanced functionality

func (*RelayRepository) CreateRelay

func (r *RelayRepository) CreateRelay(ctx context.Context, relay *storage.RelayInfo) error

CreateRelay creates a new relay

func (*RelayRepository) DeleteRelay

func (r *RelayRepository) DeleteRelay(ctx context.Context, relayURL string) error

DeleteRelay removes a relay (alias for RemoveRelayInfo)

func (*RelayRepository) GetActiveRelays

func (r *RelayRepository) GetActiveRelays(ctx context.Context) ([]*storage.RelayInfo, error)

GetActiveRelays retrieves all active relays

func (*RelayRepository) GetAllRelays

func (r *RelayRepository) GetAllRelays(ctx context.Context, limit int, cursor string) ([]*storage.RelayInfo, string, error)

GetAllRelays retrieves all relays with pagination

func (*RelayRepository) GetRelay

func (r *RelayRepository) GetRelay(ctx context.Context, relayURL string) (*storage.RelayInfo, error)

GetRelay retrieves a relay by URL (alias for GetRelayInfo)

func (*RelayRepository) GetRelayInfo

func (r *RelayRepository) GetRelayInfo(ctx context.Context, relayURL string) (*storage.RelayInfo, error)

GetRelayInfo retrieves relay information

func (*RelayRepository) ListRelays

func (r *RelayRepository) ListRelays(ctx context.Context) ([]*storage.RelayInfo, error)

ListRelays retrieves all relays (alias for GetAllRelays without pagination)

func (*RelayRepository) RemoveRelayInfo

func (r *RelayRepository) RemoveRelayInfo(ctx context.Context, relayURL string) error

RemoveRelayInfo removes relay information

func (*RelayRepository) StoreRelayInfo

func (r *RelayRepository) StoreRelayInfo(ctx context.Context, relay *storage.RelayInfo) error

StoreRelayInfo stores relay information

func (*RelayRepository) UpdateRelayState

func (r *RelayRepository) UpdateRelayState(ctx context.Context, relayURL string, state storage.RelayState) error

UpdateRelayState updates multiple relay fields beyond just active status

func (*RelayRepository) UpdateRelayStatus

func (r *RelayRepository) UpdateRelayStatus(ctx context.Context, relayURL string, active bool) error

UpdateRelayStatus updates the active status of a relay

type ReportConversionConfig

type ReportConversionConfig struct {
	CursorField string // Field to use for cursor (e.g., "gsi2SK", "gsi3SK")
	LogContext  string // Context for logging (e.g., "status", "category")
}

ReportConversionConfig configures report model to storage type conversion

type ResidualStats

type ResidualStats struct {
	Mean           float64 `json:"mean"`
	StandardError  float64 `json:"standard_error"`
	Skewness       float64 `json:"skewness"`
	Kurtosis       float64 `json:"kurtosis"`
	OutlierCount   int     `json:"outlier_count"`
	NormalityScore float64 `json:"normality_score"` // 0-1, higher = more normal
}

ResidualStats represents analysis of regression residuals

type RevisionRepository

type RevisionRepository struct {
	*EnhancedBaseRepository[*models.Revision]
}

RevisionRepository implements revision operations

func NewRevisionRepository

func NewRevisionRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RevisionRepository

NewRevisionRepository creates a new revision repository

func (*RevisionRepository) CreateRevision

func (r *RevisionRepository) CreateRevision(ctx context.Context, revision *models.Revision) error

CreateRevision creates a new revision

func (*RevisionRepository) GetRevision

func (r *RevisionRepository) GetRevision(ctx context.Context, objectID string, version int) (*models.Revision, error)

GetRevision retrieves a revision by object ID and version

func (*RevisionRepository) ListRevisions

func (r *RevisionRepository) ListRevisions(ctx context.Context, objectID string, limit int) ([]*models.Revision, error)

ListRevisions lists revisions for an object

func (*RevisionRepository) ListRevisionsPaginated

func (r *RevisionRepository) ListRevisionsPaginated(ctx context.Context, objectID string, limit int, cursor string) ([]*models.Revision, string, error)

ListRevisionsPaginated lists revisions for an object with cursor pagination. Cursor values are full SK values (VERSION#...).

type RouteOptimizerRepository

type RouteOptimizerRepository struct {
	*EnhancedBaseRepository[*models.RouteDeliveryResult]
	// contains filtered or unexported fields
}

RouteOptimizerRepository handles route optimizer data persistence

func NewRouteOptimizerRepository

func NewRouteOptimizerRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RouteOptimizerRepository

NewRouteOptimizerRepository creates a new route optimizer repository with enhanced functionality

func (*RouteOptimizerRepository) CleanupExpiredResults

func (r *RouteOptimizerRepository) CleanupExpiredResults(_ context.Context, before time.Time) error

CleanupExpiredResults removes old delivery results (handled by TTL, but can be called manually)

func (*RouteOptimizerRepository) GetMetricsInRange

func (r *RouteOptimizerRepository) GetMetricsInRange(ctx context.Context, routeID string, start, end time.Time, limit int) ([]*types.DeliveryResult, error)

GetMetricsInRange retrieves delivery results for a specific route within a time range

func (*RouteOptimizerRepository) GetOptimizationDecisions

func (r *RouteOptimizerRepository) GetOptimizationDecisions(ctx context.Context, since time.Time, limit int) ([]*models.OptimizationDecision, error)

GetOptimizationDecisions retrieves recent optimization decisions

func (*RouteOptimizerRepository) GetRecentResults

func (r *RouteOptimizerRepository) GetRecentResults(ctx context.Context, since time.Time, limit int) ([]*models.RouteDeliveryResult, error)

GetRecentResults retrieves recent delivery results across all routes

func (*RouteOptimizerRepository) GetRouteMetrics

func (r *RouteOptimizerRepository) GetRouteMetrics(ctx context.Context, routeID string) (*types.RouteMetrics, error)

GetRouteMetrics implements RouteOptimizationRepository interface (delegates to GetRouteMetricsForFederation)

func (*RouteOptimizerRepository) GetRouteMetricsForFederation

func (r *RouteOptimizerRepository) GetRouteMetricsForFederation(ctx context.Context, routeID string) (*types.RouteMetrics, error)

GetRouteMetricsForFederation calculates route metrics for federation types

func (*RouteOptimizerRepository) GetRoutePerformance

func (r *RouteOptimizerRepository) GetRoutePerformance(ctx context.Context, routeID string) (interface{}, error)

GetRoutePerformance implements RouteOptimizationRepository interface (delegates to GetRoutePerformanceData)

func (*RouteOptimizerRepository) GetRoutePerformanceData

func (r *RouteOptimizerRepository) GetRoutePerformanceData(ctx context.Context, routeID string) (interface{}, error)

GetRoutePerformanceData returns internal performance data for optimization

func (*RouteOptimizerRepository) GetRouteResults

func (r *RouteOptimizerRepository) GetRouteResults(ctx context.Context, routeID string, limit int) ([]*models.RouteDeliveryResult, error)

GetRouteResults retrieves recent delivery results for a route

func (*RouteOptimizerRepository) RecordDeliveryResult

func (r *RouteOptimizerRepository) RecordDeliveryResult(ctx context.Context, result *types.DeliveryResult) error

RecordDeliveryResult converts federation DeliveryResult and stores it (implements interface)

func (*RouteOptimizerRepository) StoreOptimizationDecision

func (r *RouteOptimizerRepository) StoreOptimizationDecision(ctx context.Context, routes []*types.Route, messageSize int64) error

StoreOptimizationDecision stores optimization decision from route array (implements interface)

type RoutingMetricsRepository

type RoutingMetricsRepository struct {
	// contains filtered or unexported fields
}

RoutingMetricsRepository handles routing metrics data persistence using BaseRepository pattern

func NewRoutingMetricsRepository

func NewRoutingMetricsRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RoutingMetricsRepository

NewRoutingMetricsRepository creates a new routing metrics repository

func NewRoutingMetricsRepositoryWithCostTracking

func NewRoutingMetricsRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *RoutingMetricsRepository

NewRoutingMetricsRepositoryWithCostTracking creates a new routing metrics repository with cost tracking

func (*RoutingMetricsRepository) BatchStoreMetrics

func (r *RoutingMetricsRepository) BatchStoreMetrics(ctx context.Context,
	routeWindows []*models.RouteMetricsWindow,
	instanceWindows []*models.InstanceMetricsWindow,
	globalWindow *models.GlobalMetricsWindow) error

BatchStoreMetrics stores multiple metrics windows in batch

func (*RoutingMetricsRepository) CleanupExpiredMetrics

func (r *RoutingMetricsRepository) CleanupExpiredMetrics(_ context.Context, before time.Time) error

CleanupExpiredMetrics removes old metrics (handled by TTL, but can be called manually)

func (*RoutingMetricsRepository) GetGlobalMetricsWindows

func (r *RoutingMetricsRepository) GetGlobalMetricsWindows(ctx context.Context, since time.Time, limit int) ([]*models.GlobalMetricsWindow, error)

GetGlobalMetricsWindows retrieves global metrics for a time range

func (*RoutingMetricsRepository) GetInstanceMetricsWindows

func (r *RoutingMetricsRepository) GetInstanceMetricsWindows(ctx context.Context, instanceID string, since time.Time, limit int) ([]*models.InstanceMetricsWindow, error)

GetInstanceMetricsWindows retrieves instance metrics for a time range

func (*RoutingMetricsRepository) GetRouteMetricsWindows

func (r *RoutingMetricsRepository) GetRouteMetricsWindows(ctx context.Context, routeID string, since time.Time, limit int) ([]*models.RouteMetricsWindow, error)

GetRouteMetricsWindows retrieves route metrics for a time range

func (*RoutingMetricsRepository) StoreGlobalMetricsWindow

func (r *RoutingMetricsRepository) StoreGlobalMetricsWindow(ctx context.Context, window *models.GlobalMetricsWindow) error

StoreGlobalMetricsWindow stores aggregated global metrics for a time window

func (*RoutingMetricsRepository) StoreInstanceMetricsWindow

func (r *RoutingMetricsRepository) StoreInstanceMetricsWindow(ctx context.Context, window *models.InstanceMetricsWindow) error

StoreInstanceMetricsWindow stores aggregated instance metrics for a time window

func (*RoutingMetricsRepository) StoreRouteMetricsWindow

func (r *RoutingMetricsRepository) StoreRouteMetricsWindow(ctx context.Context, window *models.RouteMetricsWindow) error

StoreRouteMetricsWindow stores aggregated route metrics for a time window

type ScheduleSummaryStats

type ScheduleSummaryStats struct {
	Schedule                string
	ExecutionCount          int64
	SuccessfulExecutions    int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	TotalDurationMs         int64
	AverageCostPerExecution float64
	AverageDurationMs       float64
	SuccessRate             float64
}

ScheduleSummaryStats represents summary statistics for a schedule

type ScheduledJobCostRepository

type ScheduledJobCostRepository struct {
	*EnhancedBaseRepository[*models.ScheduledJobCostRecord]
	// contains filtered or unexported fields
}

ScheduledJobCostRepository handles scheduled job cost tracking persistence using enhanced patterns

func NewScheduledJobCostRepository

func NewScheduledJobCostRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ScheduledJobCostRepository

NewScheduledJobCostRepository creates a new scheduled job cost repository with enhanced functionality

func (*ScheduledJobCostRepository) AggregateJobCosts

func (r *ScheduledJobCostRepository) AggregateJobCosts(ctx context.Context, jobName, period string, windowStart, windowEnd time.Time) error

AggregateJobCosts performs aggregation of raw scheduled job cost data

func (*ScheduledJobCostRepository) Create

Create creates a new scheduled job cost record

func (*ScheduledJobCostRepository) CreateAggregation

func (r *ScheduledJobCostRepository) CreateAggregation(ctx context.Context, aggregation *models.ScheduledJobCostAggregation) error

CreateAggregation creates a scheduled job cost aggregation

func (*ScheduledJobCostRepository) Get

func (r *ScheduledJobCostRepository) Get(ctx context.Context, jobName, schedule string, timestamp time.Time, id string) (*models.ScheduledJobCostRecord, error)

Get retrieves a scheduled job cost record by job name, schedule, timestamp and ID

func (*ScheduledJobCostRepository) GetAggregation

func (r *ScheduledJobCostRepository) GetAggregation(ctx context.Context, period, jobName string, windowStart time.Time) (*models.ScheduledJobCostAggregation, error)

GetAggregation retrieves a scheduled job cost aggregation

func (*ScheduledJobCostRepository) GetByID

GetByID retrieves a scheduled job cost record by ID

func (*ScheduledJobCostRepository) GetFailedJobs

func (r *ScheduledJobCostRepository) GetFailedJobs(ctx context.Context, startTime, endTime time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

GetFailedJobs returns failed job executions within a time range

func (*ScheduledJobCostRepository) GetHighCostJobs

func (r *ScheduledJobCostRepository) GetHighCostJobs(ctx context.Context, thresholdDollars float64, startTime, endTime time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

GetHighCostJobs returns jobs that exceeded a cost threshold

func (*ScheduledJobCostRepository) GetJobExecutionStats

func (r *ScheduledJobCostRepository) GetJobExecutionStats(ctx context.Context, jobName, schedule string, startTime, endTime time.Time) (*JobExecutionStats, error)

GetJobExecutionStats calculates execution statistics for a job

func (*ScheduledJobCostRepository) GetJobPerformanceTrends

func (r *ScheduledJobCostRepository) GetJobPerformanceTrends(ctx context.Context, jobName, schedule string, lookbackDays int) (*JobPerformanceTrend, error)

GetJobPerformanceTrends calculates performance trends for a job over time

func (*ScheduledJobCostRepository) GetLongRunningJobs

func (r *ScheduledJobCostRepository) GetLongRunningJobs(ctx context.Context, thresholdMs int64, startTime, endTime time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

GetLongRunningJobs returns jobs that exceeded a duration threshold

func (*ScheduledJobCostRepository) GetScheduledJobsSummary

func (r *ScheduledJobCostRepository) GetScheduledJobsSummary(ctx context.Context, startTime, endTime time.Time) (*ScheduledJobsSummary, error)

GetScheduledJobsSummary returns a summary of all scheduled jobs

func (*ScheduledJobCostRepository) ListByDateRange

func (r *ScheduledJobCostRepository) ListByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

ListByDateRange lists scheduled job cost records across all jobs within a date range

func (*ScheduledJobCostRepository) ListByJob

func (r *ScheduledJobCostRepository) ListByJob(ctx context.Context, jobName, schedule string, startTime, endTime time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

ListByJob lists scheduled job cost records for a specific job within a time range

func (*ScheduledJobCostRepository) ListByStatus

func (r *ScheduledJobCostRepository) ListByStatus(ctx context.Context, status string, startTime, endTime time.Time, limit int) ([]*models.ScheduledJobCostRecord, error)

ListByStatus lists scheduled job cost records by status within a time range

func (*ScheduledJobCostRepository) Update

Update updates an existing scheduled job cost record

func (*ScheduledJobCostRepository) UpdateAggregation

func (r *ScheduledJobCostRepository) UpdateAggregation(ctx context.Context, aggregation *models.ScheduledJobCostAggregation) error

UpdateAggregation updates an existing scheduled job cost aggregation

type ScheduledJobsSummary

type ScheduledJobsSummary struct {
	StartTime            time.Time
	EndTime              time.Time
	TotalExecutions      int
	SuccessfulExecutions int64
	FailedExecutions     int64
	SuccessRate          float64

	TotalCostMicroCents     int64
	TotalCostDollars        float64
	TotalDurationMs         int64
	TotalItemsProcessed     int64
	AverageCostPerExecution float64
	AverageDurationMs       float64
	CostPerItemProcessed    float64

	JobBreakdown      map[string]*JobSummaryStats
	CategoryBreakdown map[string]*CategorySummaryStats
	ScheduleBreakdown map[string]*ScheduleSummaryStats
}

ScheduledJobsSummary represents a summary of all scheduled jobs

type ScheduledStatusRepository

type ScheduledStatusRepository struct {
	*EnhancedBaseRepository[*models.ScheduledStatus]
	// contains filtered or unexported fields
}

ScheduledStatusRepository handles scheduled status operations using enhanced DynamORM patterns

func NewScheduledStatusRepository

func NewScheduledStatusRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ScheduledStatusRepository

NewScheduledStatusRepository creates a new scheduled status repository with enhanced functionality and cost tracking

func (*ScheduledStatusRepository) CreateScheduledStatus

func (r *ScheduledStatusRepository) CreateScheduledStatus(ctx context.Context, scheduled *storage.ScheduledStatus) error

CreateScheduledStatus creates a new scheduled status

func (*ScheduledStatusRepository) DeleteScheduledStatus

func (r *ScheduledStatusRepository) DeleteScheduledStatus(ctx context.Context, id string) error

DeleteScheduledStatus deletes a scheduled status

func (*ScheduledStatusRepository) GetDueScheduledStatuses

func (r *ScheduledStatusRepository) GetDueScheduledStatuses(ctx context.Context, before time.Time, limit int) ([]*storage.ScheduledStatus, error)

GetDueScheduledStatuses retrieves scheduled statuses that are due to be published

func (*ScheduledStatusRepository) GetScheduledStatus

func (r *ScheduledStatusRepository) GetScheduledStatus(ctx context.Context, id string) (*storage.ScheduledStatus, error)

GetScheduledStatus retrieves a scheduled status by ID

func (*ScheduledStatusRepository) GetScheduledStatusMedia

func (r *ScheduledStatusRepository) GetScheduledStatusMedia(ctx context.Context, id string) ([]*models.Media, error)

GetScheduledStatusMedia gets media for scheduled status

func (*ScheduledStatusRepository) GetScheduledStatuses

func (r *ScheduledStatusRepository) GetScheduledStatuses(ctx context.Context, username string, limit int, cursor string) ([]*storage.ScheduledStatus, string, error)

GetScheduledStatuses retrieves scheduled statuses for a user

func (*ScheduledStatusRepository) MarkScheduledStatusPublished

func (r *ScheduledStatusRepository) MarkScheduledStatusPublished(ctx context.Context, id string) error

MarkScheduledStatusPublished marks a scheduled status as published

func (*ScheduledStatusRepository) SetMediaRepository

func (r *ScheduledStatusRepository) SetMediaRepository(mediaRepo MediaRepositoryInterface)

SetMediaRepository sets the media repository dependency

func (*ScheduledStatusRepository) UpdateScheduledStatus

func (r *ScheduledStatusRepository) UpdateScheduledStatus(ctx context.Context, scheduled *storage.ScheduledStatus) error

UpdateScheduledStatus updates a scheduled status

type ScoredPattern

type ScoredPattern struct {
	Pattern *models.EnhancedModerationPattern
	Score   float64
}

ScoredPattern represents a pattern with its optimality score

type SearchCostRepository

type SearchCostRepository struct {
	*EnhancedBaseRepository[*models.SearchCostTracking]
	// contains filtered or unexported fields
}

SearchCostRepository manages search cost tracking and budgets using enhanced patterns

func NewSearchCostRepository

func NewSearchCostRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *SearchCostRepository

NewSearchCostRepository creates a new search cost tracking repository with enhanced functionality

func (*SearchCostRepository) CheckBudget

func (r *SearchCostRepository) CheckBudget(ctx context.Context, userID, operationType string, estimatedCostMicros int64) error

CheckBudget checks if a user can perform a search operation within budget

func (*SearchCostRepository) GetPopularQueries

func (r *SearchCostRepository) GetPopularQueries(ctx context.Context, limit int, period string) ([]*models.SearchQueryStats, error)

GetPopularQueries retrieves the most popular search queries

func (*SearchCostRepository) GetSearchCostSummary

func (r *SearchCostRepository) GetSearchCostSummary(ctx context.Context, userID string, period string) (*SearchCostSummary, error)

GetSearchCostSummary retrieves aggregated search cost data

func (*SearchCostRepository) GetSearchCosts

func (r *SearchCostRepository) GetSearchCosts(ctx context.Context, userID string, startDate, endDate time.Time) ([]*models.SearchCostTracking, error)

GetSearchCosts retrieves search costs for a user in a date range

func (*SearchCostRepository) GetUserBudget

func (r *SearchCostRepository) GetUserBudget(ctx context.Context, userID, period string) (*models.SearchBudget, error)

GetUserBudget retrieves the current budget for a user

func (*SearchCostRepository) RecordBudgetUsage

func (r *SearchCostRepository) RecordBudgetUsage(ctx context.Context, userID, operationType string, actualCostMicros int64) error

RecordBudgetUsage records budget usage for a completed operation

func (*SearchCostRepository) RecordSearchCost

func (r *SearchCostRepository) RecordSearchCost(ctx context.Context, costData *models.SearchCostTracking) error

RecordSearchCost records cost tracking data for a search operation

func (*SearchCostRepository) ResetBudgets

func (r *SearchCostRepository) ResetBudgets(ctx context.Context, period string) error

ResetBudgets resets daily budgets (called by scheduled job)

type SearchCostSummary

type SearchCostSummary struct {
	TotalRequests            int64            `json:"total_requests"`
	TotalCostMicros          int64            `json:"total_cost_micros"`
	AverageCostMicros        int64            `json:"average_cost_micros"`
	TotalResults             int64            `json:"total_results"`
	AverageResultsPerRequest float64          `json:"average_results_per_request"`
	CostPerResult            int64            `json:"cost_per_result"`
	AverageResponseTimeMs    int64            `json:"average_response_time_ms"`
	CacheHitRate             float64          `json:"cache_hit_rate"`
	OperationBreakdown       map[string]int64 `json:"operation_breakdown"`
}

SearchCostSummary provides aggregated search cost information

type SearchCostTrackingWrapper

type SearchCostTrackingWrapper struct {
	// contains filtered or unexported fields
}

SearchCostTrackingWrapper wraps a SearchRepository with comprehensive cost tracking

func NewSearchCostTrackingWrapper

func NewSearchCostTrackingWrapper(searchRepo *SearchRepository, costRepo *SearchCostRepository, costTracker *cost.Tracker, logger *zap.Logger) *SearchCostTrackingWrapper

NewSearchCostTrackingWrapper creates a new cost tracking wrapper for search operations

func (*SearchCostTrackingWrapper) CreateSearchSuggestion

func (w *SearchCostTrackingWrapper) CreateSearchSuggestion(ctx context.Context, suggestion *models.SearchSuggestion) error

CreateSearchSuggestion forwards search suggestion creation to the underlying repository

func (*SearchCostTrackingWrapper) DeleteEmbedding

func (w *SearchCostTrackingWrapper) DeleteEmbedding(ctx context.Context, contentID string) error

DeleteEmbedding forwards embedding deletion to the underlying repository

func (*SearchCostTrackingWrapper) GetPopularSearches

func (w *SearchCostTrackingWrapper) GetPopularSearches(ctx context.Context, limit int, timeWindow time.Duration) ([]*models.SearchQueryStats, error)

GetPopularSearches forwards popular search queries retrieval to the underlying repository

func (*SearchCostTrackingWrapper) GetSearchAnalytics

func (w *SearchCostTrackingWrapper) GetSearchAnalytics(ctx context.Context, startDate, endDate time.Time) ([]*models.SearchAnalytics, error)

GetSearchAnalytics forwards search analytics retrieval to the underlying repository

func (*SearchCostTrackingWrapper) GetSearchSuggestions

func (w *SearchCostTrackingWrapper) GetSearchSuggestions(ctx context.Context, prefix string, limit int) ([]*models.SearchSuggestion, error)

GetSearchSuggestions wraps search suggestions with cost tracking

func (*SearchCostTrackingWrapper) GetSearchTrends

func (w *SearchCostTrackingWrapper) GetSearchTrends(ctx context.Context, days int) (map[string]int, error)

GetSearchTrends forwards search trend analysis to the underlying repository

func (*SearchCostTrackingWrapper) IncrementSuggestionUse

func (w *SearchCostTrackingWrapper) IncrementSuggestionUse(ctx context.Context, suggestionType, term string) error

IncrementSuggestionUse forwards suggestion use count increments to the underlying repository

func (*SearchCostTrackingWrapper) IndexContentEmbedding

func (w *SearchCostTrackingWrapper) IndexContentEmbedding(ctx context.Context, embedding *models.SearchEmbedding) error

IndexContentEmbedding forwards content embedding indexing to the underlying repository

func (*SearchCostTrackingWrapper) IndexStatus

func (w *SearchCostTrackingWrapper) IndexStatus(ctx context.Context, status *models.Object) error

IndexStatus forwards status indexing operations to the underlying repository

func (*SearchCostTrackingWrapper) PruneOldSuggestions

func (w *SearchCostTrackingWrapper) PruneOldSuggestions(ctx context.Context, olderThan time.Time) error

PruneOldSuggestions forwards old suggestion cleanup to the underlying repository

func (*SearchCostTrackingWrapper) RecordSearch

RecordSearch forwards search event recording to the underlying repository

func (*SearchCostTrackingWrapper) SearchAccounts

func (w *SearchCostTrackingWrapper) SearchAccounts(ctx context.Context, query string, limit int, followingOnly bool, offset int) ([]*activitypub.Actor, error)

SearchAccounts wraps account search with cost tracking

func (*SearchCostTrackingWrapper) SearchAccountsAdvanced

func (w *SearchCostTrackingWrapper) SearchAccountsAdvanced(ctx context.Context, query string, resolve bool, limit int, offset int, following bool, accountID string) ([]*activitypub.Actor, error)

SearchAccountsAdvanced wraps advanced account search with cost tracking

func (*SearchCostTrackingWrapper) SearchAll

func (w *SearchCostTrackingWrapper) SearchAll(ctx context.Context, query string, limit int, accountID string) (*storage.SearchResults, error)

SearchAll wraps comprehensive search with cost tracking

func (*SearchCostTrackingWrapper) SearchByEmbedding

func (w *SearchCostTrackingWrapper) SearchByEmbedding(ctx context.Context, queryEmbedding []float32, limit int, threshold float64) ([]*models.SearchEmbedding, error)

SearchByEmbedding wraps semantic search with cost tracking

func (*SearchCostTrackingWrapper) SearchHashtags

func (w *SearchCostTrackingWrapper) SearchHashtags(ctx context.Context, query string, limit int) ([]*storage.Hashtag, error)

SearchHashtags wraps hashtag search with cost tracking

func (*SearchCostTrackingWrapper) SearchHashtagsAdvanced

func (w *SearchCostTrackingWrapper) SearchHashtagsAdvanced(ctx context.Context, query string, limit int, accountID string) ([]*storage.HashtagSearchResult, error)

SearchHashtagsAdvanced wraps advanced hashtag search with cost tracking

func (*SearchCostTrackingWrapper) SearchStatuses

func (w *SearchCostTrackingWrapper) SearchStatuses(ctx context.Context, query string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatuses wraps status search with cost tracking

func (*SearchCostTrackingWrapper) SearchStatusesAdvanced

func (w *SearchCostTrackingWrapper) SearchStatusesAdvanced(ctx context.Context, query string, limit int, maxID, minID *string, accountID string) ([]*storage.StatusSearchResult, error)

SearchStatusesAdvanced wraps advanced status search with cost tracking

func (*SearchCostTrackingWrapper) SearchStatusesByAuthor

func (w *SearchCostTrackingWrapper) SearchStatusesByAuthor(ctx context.Context, authorID string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatusesByAuthor forwards author-based status searches to the underlying repository

func (*SearchCostTrackingWrapper) SearchStatusesByHashtag

func (w *SearchCostTrackingWrapper) SearchStatusesByHashtag(ctx context.Context, hashtag string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatusesByHashtag forwards hashtag-based status searches to the underlying repository

func (*SearchCostTrackingWrapper) SearchStatusesWithOptions

func (w *SearchCostTrackingWrapper) SearchStatusesWithOptions(ctx context.Context, query string, options storage.StatusSearchOptions) ([]*storage.StatusSearchResult, error)

SearchStatusesWithOptions wraps status search with options and cost tracking

func (*SearchCostTrackingWrapper) SetDependencies

func (w *SearchCostTrackingWrapper) SetDependencies(deps SearchRepositoryDeps)

SetDependencies forwards dependency configuration to the underlying search repository

func (*SearchCostTrackingWrapper) UnindexStatus

func (w *SearchCostTrackingWrapper) UnindexStatus(ctx context.Context, statusID string) error

UnindexStatus forwards status unindexing operations to the underlying repository

func (*SearchCostTrackingWrapper) UpdateEmbedding

func (w *SearchCostTrackingWrapper) UpdateEmbedding(ctx context.Context, contentID string, embedding []float32) error

UpdateEmbedding forwards embedding updates to the underlying repository

func (*SearchCostTrackingWrapper) UpdateSearchSuggestion

func (w *SearchCostTrackingWrapper) UpdateSearchSuggestion(ctx context.Context, suggestionType, term string, updates map[string]interface{}) error

UpdateSearchSuggestion forwards search suggestion updates to the underlying repository

type SearchRepository

type SearchRepository struct {
	*EnhancedBaseRepository[*models.SearchSuggestion]
	// contains filtered or unexported fields
}

SearchRepository implements search functionality using enhanced DynamORM patterns

func NewSearchRepository

func NewSearchRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *SearchRepository

NewSearchRepository creates a new search repository with enhanced functionality

func (*SearchRepository) CreateSearchSuggestion

func (r *SearchRepository) CreateSearchSuggestion(ctx context.Context, suggestion *models.SearchSuggestion) error

CreateSearchSuggestion creates a new search suggestion

func (*SearchRepository) DeleteEmbedding

func (r *SearchRepository) DeleteEmbedding(ctx context.Context, contentID string) error

DeleteEmbedding removes an embedding

func (*SearchRepository) GetPopularSearches

func (r *SearchRepository) GetPopularSearches(ctx context.Context, limit int, timeWindow time.Duration) ([]*models.SearchQueryStats, error)

GetPopularSearches retrieves popular search queries (privacy-safe)

func (*SearchRepository) GetSearchAnalytics

func (r *SearchRepository) GetSearchAnalytics(ctx context.Context, startDate, endDate time.Time) ([]*models.SearchAnalytics, error)

GetSearchAnalytics retrieves search analytics for a date range

func (*SearchRepository) GetSearchSuggestions

func (r *SearchRepository) GetSearchSuggestions(ctx context.Context, prefix string, limit int) ([]*models.SearchSuggestion, error)

GetSearchSuggestions retrieves search suggestions based on prefix

func (*SearchRepository) GetSearchTrends

func (r *SearchRepository) GetSearchTrends(ctx context.Context, days int) (map[string]int, error)

GetSearchTrends retrieves search trends over days

func (*SearchRepository) IncrementSuggestionUse

func (r *SearchRepository) IncrementSuggestionUse(ctx context.Context, suggestionType, term string) error

IncrementSuggestionUse increments the use count for a suggestion

func (*SearchRepository) IndexContentEmbedding

func (r *SearchRepository) IndexContentEmbedding(ctx context.Context, embedding *models.SearchEmbedding) error

IndexContentEmbedding indexes content with its embedding vector

func (*SearchRepository) IndexStatus

func (r *SearchRepository) IndexStatus(_ context.Context, status *models.Object) error

IndexStatus indexes a status for search

func (*SearchRepository) PruneOldSuggestions

func (r *SearchRepository) PruneOldSuggestions(ctx context.Context, olderThan time.Time) error

PruneOldSuggestions removes suggestions older than the specified time

func (*SearchRepository) RecordSearch

func (r *SearchRepository) RecordSearch(ctx context.Context, event *models.SearchAnalytics) error

RecordSearch records a search event for analytics

func (*SearchRepository) RecordSearchWithPrivacy

func (r *SearchRepository) RecordSearchWithPrivacy(ctx context.Context, query, searchType string, resultCount int, searchTimeMs int64, userID *string) error

RecordSearchWithPrivacy records a privacy-safe search event

func (*SearchRepository) SearchAccounts

func (r *SearchRepository) SearchAccounts(ctx context.Context, query string, limit int, followingOnly bool, offset int) ([]*activitypub.Actor, error)

SearchAccounts searches for accounts matching the given query

func (*SearchRepository) SearchAccountsAdvanced

func (r *SearchRepository) SearchAccountsAdvanced(ctx context.Context, query string, _ bool, limit int, offset int, following bool, accountID string) ([]*activitypub.Actor, error)

SearchAccountsAdvanced searches for accounts with advanced filtering

func (*SearchRepository) SearchAccountsWithPrivacy

func (r *SearchRepository) SearchAccountsWithPrivacy(ctx context.Context, query string, limit int, followingOnly bool, offset int, searcherActorID string) ([]*activitypub.Actor, error)

SearchAccountsWithPrivacy searches for accounts with privacy enforcement

func (*SearchRepository) SearchAll

func (r *SearchRepository) SearchAll(ctx context.Context, query string, limit int, _ string) (*storage.SearchResults, error)

SearchAll performs a comprehensive search across accounts, statuses, and hashtags

func (*SearchRepository) SearchAllPaginated

func (r *SearchRepository) SearchAllPaginated(ctx context.Context, query string, options *PaginationOptions) (*storage.SearchResults, *PaginationResult, error)

SearchAllPaginated performs a comprehensive search across accounts, statuses, and hashtags with pagination

func (*SearchRepository) SearchByEmbedding

func (r *SearchRepository) SearchByEmbedding(ctx context.Context, queryEmbedding []float32, limit int, threshold float64) ([]*models.SearchEmbedding, error)

SearchByEmbedding searches for similar content using vector similarity

func (*SearchRepository) SearchByEmbeddingPaginated

func (r *SearchRepository) SearchByEmbeddingPaginated(ctx context.Context, queryEmbedding []float32, threshold float64, options *PaginationOptions) ([]*models.SearchEmbedding, *PaginationResult, error)

SearchByEmbeddingPaginated searches for similar content using vector similarity with pagination support

func (*SearchRepository) SearchHashtags

func (r *SearchRepository) SearchHashtags(ctx context.Context, query string, limit int) ([]*storage.Hashtag, error)

SearchHashtags searches for hashtags matching the given query

func (*SearchRepository) SearchHashtagsAdvanced

func (r *SearchRepository) SearchHashtagsAdvanced(ctx context.Context, query string, limit int, _ string) ([]*storage.HashtagSearchResult, error)

SearchHashtagsAdvanced searches for hashtags with advanced filtering

func (*SearchRepository) SearchHashtagsAdvancedPaginated

func (r *SearchRepository) SearchHashtagsAdvancedPaginated(ctx context.Context, query string, options *PaginationOptions) ([]*storage.HashtagSearchResult, *PaginationResult, error)

SearchHashtagsAdvancedPaginated searches for hashtags with advanced filtering and pagination support

func (*SearchRepository) SearchStatuses

func (r *SearchRepository) SearchStatuses(ctx context.Context, query string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatuses searches for statuses matching the given query

func (*SearchRepository) SearchStatusesAdvanced

func (r *SearchRepository) SearchStatusesAdvanced(ctx context.Context, query string, limit int, maxID, minID *string, accountID string) ([]*storage.StatusSearchResult, error)

SearchStatusesAdvanced searches for statuses with advanced filtering

func (*SearchRepository) SearchStatusesByAuthor

func (r *SearchRepository) SearchStatusesByAuthor(ctx context.Context, authorID string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatusesByAuthor searches for statuses by a specific author

func (*SearchRepository) SearchStatusesByHashtag

func (r *SearchRepository) SearchStatusesByHashtag(ctx context.Context, hashtag string, limit int) ([]*storage.StatusSearchResult, error)

SearchStatusesByHashtag searches for statuses containing a specific hashtag using efficient indexing

func (*SearchRepository) SearchStatusesWithOptions

func (r *SearchRepository) SearchStatusesWithOptions(ctx context.Context, query string, options storage.StatusSearchOptions) ([]*storage.StatusSearchResult, error)

SearchStatusesWithOptions searches for statuses with advanced options

func (*SearchRepository) SearchStatusesWithOptionsPaginated

func (r *SearchRepository) SearchStatusesWithOptionsPaginated(ctx context.Context, query string, options storage.StatusSearchOptions) ([]*storage.StatusSearchResult, *PaginationResult, error)

SearchStatusesWithOptionsPaginated searches for statuses with advanced options and pagination support

func (*SearchRepository) SearchStatusesWithPrivacy

func (r *SearchRepository) SearchStatusesWithPrivacy(ctx context.Context, query string, options storage.StatusSearchOptions, searcherActorID string) ([]*storage.StatusSearchResult, error)

SearchStatusesWithPrivacy searches for statuses with privacy enforcement

func (*SearchRepository) SearchStatusesWithPrivacyPaginated

func (r *SearchRepository) SearchStatusesWithPrivacyPaginated(ctx context.Context, query string, options storage.StatusSearchOptions, searcherActorID string) ([]*storage.StatusSearchResult, *PaginationResult, error)

SearchStatusesWithPrivacyPaginated searches for statuses with privacy enforcement and pagination

func (*SearchRepository) SetDependencies

func (r *SearchRepository) SetDependencies(deps SearchRepositoryDeps)

SetDependencies sets the dependencies for cross-repository operations

func (*SearchRepository) UnindexStatus

func (r *SearchRepository) UnindexStatus(ctx context.Context, statusID string) error

UnindexStatus removes a status from search indexes

func (*SearchRepository) UpdateEmbedding

func (r *SearchRepository) UpdateEmbedding(ctx context.Context, contentID string, embedding []float32) error

UpdateEmbedding updates an existing embedding

func (*SearchRepository) UpdateSearchSuggestion

func (r *SearchRepository) UpdateSearchSuggestion(ctx context.Context, suggestionType, term string, updates map[string]interface{}) error

UpdateSearchSuggestion updates an existing search suggestion

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 SearchResultsWithCosts

type SearchResultsWithCosts struct {
	Accounts        []*activitypub.Actor          `json:"accounts"`
	Statuses        []*storage.StatusSearchResult `json:"statuses"`
	Hashtags        []*storage.Hashtag            `json:"hashtags"`
	SemanticResults []*models.SearchEmbedding     `json:"semantic_results,omitempty"`
	Suggestions     []*models.SearchSuggestion    `json:"suggestions,omitempty"`
	QueryEmbedding  []float32                     `json:"query_embedding,omitempty"`
	TotalCostMicros int64                         `json:"total_cost_micros"`
	CostBreakdown   map[string]int64              `json:"cost_breakdown"`
}

SearchResultsWithCosts combines search results with cost tracking information

type SearchServiceIntegration

type SearchServiceIntegration struct {
	// contains filtered or unexported fields
}

SearchServiceIntegration shows how to integrate all search cost tracking components

func NewSearchServiceIntegration

func NewSearchServiceIntegration(db core.DB, aiService *ai.AIService, requestID string, logger *zap.Logger) *SearchServiceIntegration

NewSearchServiceIntegration creates a fully integrated search service with cost tracking

func (*SearchServiceIntegration) BudgetManagementExample

func (s *SearchServiceIntegration) BudgetManagementExample(ctx context.Context, userID string) (*BudgetSummary, error)

BudgetManagementExample demonstrates budget management for search operations

func (*SearchServiceIntegration) ComprehensiveSearchExample

func (s *SearchServiceIntegration) ComprehensiveSearchExample(ctx context.Context, userID, query string, useSemanticSearch bool) (*SearchResultsWithCosts, error)

ComprehensiveSearchExample demonstrates comprehensive search with cost tracking

func (*SearchServiceIntegration) GetCostSummary

func (s *SearchServiceIntegration) GetCostSummary() *cost.OperationCost

GetCostSummary returns the current cost summary

func (*SearchServiceIntegration) GetCostTracker

func (s *SearchServiceIntegration) GetCostTracker() *cost.Tracker

GetCostTracker returns the cost tracker for external monitoring

func (*SearchServiceIntegration) PerformanceAnalyticsExample

func (s *SearchServiceIntegration) PerformanceAnalyticsExample(ctx context.Context, _ string, _ int) (*PerformanceAnalytics, error)

PerformanceAnalyticsExample demonstrates performance analytics collection

type SearchSortOrder

type SearchSortOrder string

SearchSortOrder represents sorting options for search

const (
	// SearchSortRelevance sorts by relevance/score (default)
	SearchSortRelevance SearchSortOrder = "relevance"
	// SearchSortTimeAsc sorts by time ascending (oldest first)
	SearchSortTimeAsc SearchSortOrder = "time_asc"
	// SearchSortTimeDesc sorts by time descending (newest first)
	SearchSortTimeDesc SearchSortOrder = "time_desc"
)

Search sort order constants

type SeasonalityAnalysis

type SeasonalityAnalysis struct {
	HasSeasonality    bool               `json:"has_seasonality"`
	SeasonalStrength  float64            `json:"seasonal_strength"` // 0-1
	SeasonalPeriod    int                `json:"seasonal_period"`   // Detected period (e.g., 7 for weekly)
	SeasonalPatterns  map[string]float64 `json:"seasonal_patterns"` // Pattern coefficients
	TrendComponent    []float64          `json:"trend_component"`
	SeasonalComponent []float64          `json:"seasonal_component"`
	ResidualComponent []float64          `json:"residual_component"`
	DecompositionR2   float64            `json:"decomposition_r2"` // Quality of decomposition
}

SeasonalityAnalysis represents seasonal pattern analysis

type SecretsManagerClient

type SecretsManagerClient interface {
	GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error)
	PutSecretValue(ctx context.Context, params *secretsmanager.PutSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.PutSecretValueOutput, error)
}

SecretsManagerClient defines the subset of AWS Secrets Manager client methods used by the repository.

type SenderInfo

type SenderInfo struct {
	AccountAge     int `json:"account_age_days"`
	FollowerCount  int `json:"follower_count"`
	ViolationCount int `json:"violation_count"`
}

SenderInfo contains information about the content sender

type SeriesRepository

type SeriesRepository struct {
	*EnhancedBaseRepository[*models.Series]
}

SeriesRepository implements series operations

func NewSeriesRepository

func NewSeriesRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *SeriesRepository

NewSeriesRepository creates a new series repository

func (*SeriesRepository) CreateSeries

func (r *SeriesRepository) CreateSeries(ctx context.Context, series *models.Series) error

CreateSeries creates a new series

func (*SeriesRepository) GetSeries

func (r *SeriesRepository) GetSeries(ctx context.Context, authorID, seriesID string) (*models.Series, error)

GetSeries retrieves a series by author ID and series ID

func (*SeriesRepository) ListSeriesByAuthor

func (r *SeriesRepository) ListSeriesByAuthor(ctx context.Context, authorID string, limit int) ([]*models.Series, error)

ListSeriesByAuthor lists series for an author

func (*SeriesRepository) ListSeriesByAuthorPaginated

func (r *SeriesRepository) ListSeriesByAuthorPaginated(ctx context.Context, authorID string, limit int, cursor string) ([]*models.Series, string, error)

ListSeriesByAuthorPaginated lists series for an author with cursor pagination. Cursor values are either full SK values (ID#...) or raw series IDs.

func (*SeriesRepository) UpdateArticleCount

func (r *SeriesRepository) UpdateArticleCount(ctx context.Context, authorID string, seriesID string, delta int) error

UpdateArticleCount atomically increments/decrements a series's ArticleCount. Missing series are treated as a no-op to avoid breaking writes when legacy/stale IDs exist.

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 (PRESERVED - AWS monitoring critical)

type ServiceStats

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

ServiceStats represents statistics 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 struct {
	*EnhancedBaseRepository[*models.SeveredRelationship]
	// contains filtered or unexported fields
}

SeveranceRepository handles severed relationship operations

func NewSeveranceRepository

func NewSeveranceRepository(db core.DB, tableName string, logger *zap.Logger) *SeveranceRepository

NewSeveranceRepository creates a new SeveranceRepository instance

func (*SeveranceRepository) CreateAffectedRelationship

func (r *SeveranceRepository) CreateAffectedRelationship(ctx context.Context, affected *models.AffectedRelationship) error

CreateAffectedRelationship creates a new affected relationship record

func (*SeveranceRepository) CreateReconnectionAttempt

func (r *SeveranceRepository) CreateReconnectionAttempt(ctx context.Context, attempt *models.SeveranceReconnectionAttempt) error

CreateReconnectionAttempt creates a new reconnection attempt record

func (*SeveranceRepository) CreateSeveredRelationship

func (r *SeveranceRepository) CreateSeveredRelationship(ctx context.Context, severance *models.SeveredRelationship) error

CreateSeveredRelationship creates a new severed relationship record

func (*SeveranceRepository) GetAffectedRelationships

func (r *SeveranceRepository) GetAffectedRelationships(ctx context.Context, severanceID string, limit int, cursor string) ([]*models.AffectedRelationship, string, error)

GetAffectedRelationships retrieves affected relationships for a severance

func (*SeveranceRepository) GetReconnectionAttempt

func (r *SeveranceRepository) GetReconnectionAttempt(ctx context.Context, severanceID, attemptID string) (*models.SeveranceReconnectionAttempt, error)

GetReconnectionAttempt retrieves a reconnection attempt by ID

func (*SeveranceRepository) GetReconnectionAttempts

func (r *SeveranceRepository) GetReconnectionAttempts(ctx context.Context, severanceID string) ([]*models.SeveranceReconnectionAttempt, error)

GetReconnectionAttempts retrieves all reconnection attempts for a severance

func (*SeveranceRepository) GetSeveredRelationship

func (r *SeveranceRepository) GetSeveredRelationship(ctx context.Context, id string) (*models.SeveredRelationship, error)

GetSeveredRelationship retrieves a severed relationship by ID

func (*SeveranceRepository) ListSeveredRelationships

func (r *SeveranceRepository) ListSeveredRelationships(ctx context.Context, localInstance string, filters SeveranceFilters, limit int, cursor string) ([]*models.SeveredRelationship, string, error)

ListSeveredRelationships retrieves severed relationships with filters and pagination

func (*SeveranceRepository) UpdateReconnectionAttempt

func (r *SeveranceRepository) UpdateReconnectionAttempt(ctx context.Context, attempt *models.SeveranceReconnectionAttempt) error

UpdateReconnectionAttempt updates a reconnection attempt record

func (*SeveranceRepository) UpdateSeveranceStatus

func (r *SeveranceRepository) UpdateSeveranceStatus(ctx context.Context, id string, status models.SeveranceStatus) error

UpdateSeveranceStatus updates the status of a severed relationship

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 This is critical for thumbnail generation and media optimization - preserves ALL functionality

type SocialRepository

type SocialRepository struct {
	// contains filtered or unexported fields
}

SocialRepository handles all social interaction operations using enhanced patterns

func NewSocialRepository

func NewSocialRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *SocialRepository

NewSocialRepository creates a new social repository with enhanced functionality

func (*SocialRepository) CascadeDeleteAnnounces

func (r *SocialRepository) CascadeDeleteAnnounces(ctx context.Context, objectID string) error

CascadeDeleteAnnounces deletes all announces for an object

func (*SocialRepository) CheckPinnedStatuses added in v1.1.1

func (r *SocialRepository) CheckPinnedStatuses(ctx context.Context, username string, statusIDs []string) (map[string]bool, error)

CheckPinnedStatuses returns a map of statusID -> pinned for the provided IDs.

func (*SocialRepository) CountObjectAnnounces

func (r *SocialRepository) CountObjectAnnounces(ctx context.Context, objectID string) (int, error)

CountObjectAnnounces returns the total number of announces for an object

func (*SocialRepository) CountUserPinnedStatuses

func (r *SocialRepository) CountUserPinnedStatuses(ctx context.Context, username string) (int, error)

CountUserPinnedStatuses counts how many statuses a user has pinned

func (*SocialRepository) CreateAccountNote

func (r *SocialRepository) CreateAccountNote(ctx context.Context, note *storage.AccountNote) error

CreateAccountNote creates a new private note on an account

func (*SocialRepository) CreateAccountPin

func (r *SocialRepository) CreateAccountPin(ctx context.Context, pin *storage.AccountPin) error

CreateAccountPin creates a new account pin (endorsed account)

func (*SocialRepository) CreateAnnounce

func (r *SocialRepository) CreateAnnounce(ctx context.Context, announce *storage.Announce) error

CreateAnnounce creates a new Announce activity

func (*SocialRepository) CreateBlock

func (r *SocialRepository) CreateBlock(ctx context.Context, block *storage.Block) error

CreateBlock creates a new block relationship

func (*SocialRepository) CreateMute

func (r *SocialRepository) CreateMute(ctx context.Context, mute *storage.Mute) error

CreateMute creates a new mute relationship

func (*SocialRepository) CreateStatusPin

func (r *SocialRepository) CreateStatusPin(ctx context.Context, pin *storage.StatusPin) error

CreateStatusPin creates a new status pin

func (*SocialRepository) DeleteAccountNote

func (r *SocialRepository) DeleteAccountNote(ctx context.Context, username, targetActorID string) error

DeleteAccountNote deletes a private note on an account

func (*SocialRepository) DeleteAccountPin

func (r *SocialRepository) DeleteAccountPin(ctx context.Context, username, pinnedActorID string) error

DeleteAccountPin deletes an account pin

func (*SocialRepository) DeleteAnnounce

func (r *SocialRepository) DeleteAnnounce(ctx context.Context, actor, object string) error

DeleteAnnounce removes an Announce activity

func (*SocialRepository) DeleteBlock

func (r *SocialRepository) DeleteBlock(ctx context.Context, actor, blockedActor string) error

DeleteBlock removes a block relationship

func (*SocialRepository) DeleteMute

func (r *SocialRepository) DeleteMute(ctx context.Context, actor, mutedActor string) error

DeleteMute removes a mute relationship

func (*SocialRepository) DeleteStatusPin

func (r *SocialRepository) DeleteStatusPin(ctx context.Context, username, statusID string) error

DeleteStatusPin removes a status pin

func (*SocialRepository) GetAccountNote

func (r *SocialRepository) GetAccountNote(ctx context.Context, username, targetActorID string) (*storage.AccountNote, error)

GetAccountNote retrieves a private note on an account

func (*SocialRepository) GetAccountPins

func (r *SocialRepository) GetAccountPins(ctx context.Context, username string) ([]*storage.AccountPin, error)

GetAccountPins retrieves all pinned accounts for a user (for backward compatibility)

func (*SocialRepository) GetAccountPinsPaginated

func (r *SocialRepository) GetAccountPinsPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.AccountPin, string, error)

GetAccountPinsPaginated retrieves pinned accounts for a user with pagination

func (*SocialRepository) GetActorAnnounces

func (r *SocialRepository) GetActorAnnounces(ctx context.Context, actorID string, limit int, cursor string) ([]*storage.Announce, string, error)

GetActorAnnounces retrieves all objects announced by a specific actor with pagination

func (*SocialRepository) GetAnnounce

func (r *SocialRepository) GetAnnounce(ctx context.Context, actor, object string) (*storage.Announce, error)

GetAnnounce retrieves a specific Announce by actor and object

func (*SocialRepository) GetBlock

func (r *SocialRepository) GetBlock(ctx context.Context, actor, blockedActor string) (*storage.Block, error)

GetBlock retrieves a specific block relationship

func (*SocialRepository) GetBlockedByUsers

func (r *SocialRepository) GetBlockedByUsers(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

func (*SocialRepository) GetBlockedUsers

func (r *SocialRepository) GetBlockedUsers(ctx context.Context, actor string, limit int, cursor string) ([]*storage.Block, string, error)

GetBlockedUsers returns a paginated list of actors blocked by the given actor

func (*SocialRepository) GetMute

func (r *SocialRepository) GetMute(ctx context.Context, actor, mutedActor string) (*storage.Mute, error)

GetMute retrieves a specific mute relationship

func (*SocialRepository) GetMutedUsers

func (r *SocialRepository) GetMutedUsers(ctx context.Context, actor string, limit int, cursor string) ([]*storage.Mute, string, error)

GetMutedUsers returns all actors muted by the given actor

func (*SocialRepository) GetStatusAnnounces

func (r *SocialRepository) GetStatusAnnounces(ctx context.Context, objectID string, limit int, cursor string) ([]*storage.Announce, string, error)

GetStatusAnnounces retrieves all announces for a specific object

func (*SocialRepository) GetStatusPins

func (r *SocialRepository) GetStatusPins(ctx context.Context, username string) ([]*storage.StatusPin, error)

GetStatusPins retrieves all pinned statuses for a user (for backward compatibility)

func (*SocialRepository) GetStatusPinsPaginated

func (r *SocialRepository) GetStatusPinsPaginated(ctx context.Context, username string, limit int, cursor string) ([]*storage.StatusPin, string, error)

GetStatusPinsPaginated retrieves pinned statuses for a user with pagination

func (*SocialRepository) HasUserAnnounced

func (r *SocialRepository) HasUserAnnounced(ctx context.Context, actor, object string) (bool, error)

HasUserAnnounced checks if a user has announced a specific object

func (*SocialRepository) IsAccountPinned

func (r *SocialRepository) IsAccountPinned(ctx context.Context, username, pinnedActorID string) (bool, error)

IsAccountPinned checks if an account is pinned

func (*SocialRepository) IsBlocked

func (r *SocialRepository) IsBlocked(ctx context.Context, actor, targetActor string) (bool, error)

IsBlocked checks if targetActor is blocked by actor

func (*SocialRepository) IsMuted

func (r *SocialRepository) IsMuted(ctx context.Context, actor, targetActor string) (bool, error)

IsMuted checks if targetActor is muted by actor

func (*SocialRepository) IsStatusPinned

func (r *SocialRepository) IsStatusPinned(ctx context.Context, username, statusID string) (bool, error)

IsStatusPinned checks if a status is pinned by a user

func (*SocialRepository) ReorderStatusPins

func (r *SocialRepository) ReorderStatusPins(ctx context.Context, username string, statusIDs []string) error

ReorderStatusPins reorders pinned statuses by re-creating them with new timestamps Since the legacy system doesn't have a PinOrder field, we use creation timestamps for ordering

func (*SocialRepository) UpdateAccountNote

func (r *SocialRepository) UpdateAccountNote(ctx context.Context, note *storage.AccountNote) error

UpdateAccountNote updates an existing private note on an account

type SpamDetectionResult

type SpamDetectionResult struct {
	IsSpam         bool     `json:"is_spam"`
	SpamScore      float64  `json:"spam_score"`
	Confidence     float64  `json:"confidence"`
	DetectedBy     []string `json:"detected_by"`
	ReasonCodes    []string `json:"reason_codes"`
	ProcessingTime int64    `json:"processing_time_ms"`
}

SpamDetectionResult represents the result of spam detection

type StatisticalTests

type StatisticalTests struct {
	MannKendallTau    float64        `json:"mann_kendall_tau"` // Mann-Kendall trend test statistic
	MannKendallPValue float64        `json:"mann_kendall_p"`   // Mann-Kendall p-value
	TheilSenSlope     float64        `json:"theil_sen_slope"`  // Theil-Sen robust slope estimator
	DurbinWatson      float64        `json:"durbin_watson"`    // Durbin-Watson test for autocorrelation
	JarqueBera        float64        `json:"jarque_bera"`      // Jarque-Bera test for normality
	JarqueBeraP       float64        `json:"jarque_bera_p"`    // Jarque-Bera p-value
	ResidualStats     *ResidualStats `json:"residual_stats"`
}

StatisticalTests represents statistical significance tests

type StatusRepository

type StatusRepository struct {
	*EnhancedBaseRepository[*models.Status]
	// contains filtered or unexported fields
}

StatusRepository implements status operations using DynamORM with EnhancedBaseRepository

func NewStatusRepository

func NewStatusRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *StatusRepository

NewStatusRepository creates a new status repository with enhanced functionality

func (*StatusRepository) BookmarkStatus

func (r *StatusRepository) BookmarkStatus(ctx context.Context, userID, statusID string) error

BookmarkStatus bookmarks a status for a user

func (*StatusRepository) CountReplies

func (r *StatusRepository) CountReplies(ctx context.Context, statusID string) (int, error)

CountReplies counts the number of replies to a status

func (*StatusRepository) CountStatusesByAuthor

func (r *StatusRepository) CountStatusesByAuthor(ctx context.Context, authorID string) (int, error)

CountStatusesByAuthor counts the total number of statuses by an author

func (*StatusRepository) CountStatusesForAdmin

func (r *StatusRepository) CountStatusesForAdmin(ctx context.Context, filter *interfaces.StatusFilter) (int64, error)

CountStatusesForAdmin counts statuses matching admin filter criteria

func (*StatusRepository) CreateBoostStatus

func (r *StatusRepository) CreateBoostStatus(ctx context.Context, status *models.Status) error

CreateBoostStatus persists a boost wrapper as a first-class status.

func (*StatusRepository) CreateStatus

func (r *StatusRepository) CreateStatus(ctx context.Context, status *models.Status) error

CreateStatus creates a new status using enhanced validation and event emission

func (*StatusRepository) DeleteBoostStatus

func (r *StatusRepository) DeleteBoostStatus(ctx context.Context, boosterID, targetStatusID string) (*models.Status, error)

DeleteBoostStatus removes the boost wrapper for a given booster/target pair.

func (*StatusRepository) DeleteStatus

func (r *StatusRepository) DeleteStatus(ctx context.Context, statusID string) error

DeleteStatus marks a status as deleted using BaseRepository

func (*StatusRepository) FlagStatus

func (r *StatusRepository) FlagStatus(ctx context.Context, statusID, _ string, _ string) error

FlagStatus marks a status as flagged for moderation

func (*StatusRepository) GetConversationThread

func (r *StatusRepository) GetConversationThread(ctx context.Context, conversationID string, opts interfaces.PaginationOptions) (*interfaces.PaginatedResult[*models.Status], error)

GetConversationThread retrieves all statuses in a conversation thread

func (*StatusRepository) GetFlaggedStatuses

GetFlaggedStatuses retrieves flagged statuses with pagination using GSI6

func (*StatusRepository) GetHomeTimeline

GetHomeTimeline retrieves home timeline for a user (statuses from accounts they follow)

func (*StatusRepository) GetPublicTimeline

GetPublicTimeline retrieves the public timeline with pagination

func (*StatusRepository) GetReplies

GetReplies retrieves replies to a status with pagination

func (*StatusRepository) GetStatus

func (r *StatusRepository) GetStatus(ctx context.Context, statusID string) (*models.Status, error)

GetStatus retrieves a status by ID using BaseRepository

func (*StatusRepository) GetStatusByURL

func (r *StatusRepository) GetStatusByURL(ctx context.Context, url string) (*models.Status, error)

GetStatusByURL retrieves a status by its URL using GSI7 URL index

func (*StatusRepository) GetStatusContext

func (r *StatusRepository) GetStatusContext(ctx context.Context, statusID string) (ancestors, descendants []*models.Status, err error)

GetStatusContext gets ancestors and descendants of a status

func (*StatusRepository) GetStatusCounts

func (r *StatusRepository) GetStatusCounts(ctx context.Context, statusID string) (likes, reblogs, replies int, err error)

GetStatusCounts gets engagement counts for a status

func (*StatusRepository) GetStatusEngagement

func (r *StatusRepository) GetStatusEngagement(ctx context.Context, statusID, userID string) (liked, reblogged, bookmarked bool, err error)

GetStatusEngagement gets user's engagement state with a status

func (*StatusRepository) GetStatusesByHashtag

GetStatusesByHashtag retrieves statuses containing a specific hashtag Hashtag must be in canonical format: lowercase, no # prefix (e.g., "test" not "#test" or "Test")

func (*StatusRepository) GetStatusesByIDs

func (r *StatusRepository) GetStatusesByIDs(ctx context.Context, statusIDs []string) ([]*models.Status, error)

GetStatusesByIDs gets multiple statuses by their IDs using batched BatchGetItem calls to minimize Dynamo round-trips.

func (*StatusRepository) GetStatusesByURL

func (r *StatusRepository) GetStatusesByURL(ctx context.Context, targetURL string, limit int) ([]*models.Status, error)

GetStatusesByURL searches for statuses that contain a specific URL in their URLs field

func (*StatusRepository) GetTotalStatusCount

func (r *StatusRepository) GetTotalStatusCount(ctx context.Context) (int64, error)

GetTotalStatusCount returns the total number of statuses in the system

func (*StatusRepository) GetTrendingStatuses

GetTrendingStatuses retrieves trending statuses

func (*StatusRepository) GetUserTimeline

GetUserTimeline retrieves user's own statuses

func (*StatusRepository) LikeStatus

func (r *StatusRepository) LikeStatus(ctx context.Context, userID, statusID string) error

LikeStatus likes a status for a user

func (*StatusRepository) ListStatusesForAdmin

func (r *StatusRepository) ListStatusesForAdmin(ctx context.Context, filter *interfaces.StatusFilter, limit int, cursor string) ([]*models.Status, string, error)

ListStatusesForAdmin retrieves statuses with comprehensive admin filtering

func (*StatusRepository) ReblogStatus

func (r *StatusRepository) ReblogStatus(ctx context.Context, userID, statusID, _ string) error

ReblogStatus reblogs a status for a user

func (*StatusRepository) SearchStatuses

SearchStatuses searches statuses by query string

func (*StatusRepository) SetBookmarkRepository

func (r *StatusRepository) SetBookmarkRepository(bookmarkRepo *BookmarkRepository)

SetBookmarkRepository wires the bookmark repository dependency.

func (*StatusRepository) SetRelationshipRepository

func (r *StatusRepository) SetRelationshipRepository(relationshipRepo interface{})

SetRelationshipRepository sets the relationship repository dependency for cross-repository operations

func (*StatusRepository) UnbookmarkStatus

func (r *StatusRepository) UnbookmarkStatus(ctx context.Context, userID, statusID string) error

UnbookmarkStatus unbookmarks a status for a user

func (*StatusRepository) UnflagStatus

func (r *StatusRepository) UnflagStatus(ctx context.Context, statusID string) error

UnflagStatus unflags a previously flagged status

func (*StatusRepository) UnlikeStatus

func (r *StatusRepository) UnlikeStatus(ctx context.Context, userID, statusID string) error

UnlikeStatus unlikes a status for a user

func (*StatusRepository) UnreblogStatus

func (r *StatusRepository) UnreblogStatus(ctx context.Context, userID, statusID string) error

UnreblogStatus unreblogs a status for a user

func (*StatusRepository) UpdateEngagementMetrics

func (r *StatusRepository) UpdateEngagementMetrics(ctx context.Context, statusID string, likes, reblogs, replies, quotes int) error

UpdateEngagementMetrics updates the cached engagement metrics for a status

func (*StatusRepository) UpdateStatus

func (r *StatusRepository) UpdateStatus(ctx context.Context, status *models.Status) error

UpdateStatus updates an existing status using enhanced validation and event emission

type StreamingCloudWatchRepository

type StreamingCloudWatchRepository struct {
	*EnhancedBaseRepository[*models.StreamingCloudWatchMetrics]
}

StreamingCloudWatchRepository handles streaming CloudWatch metrics caching using enhanced patterns

func NewStreamingCloudWatchRepository

func NewStreamingCloudWatchRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *StreamingCloudWatchRepository

NewStreamingCloudWatchRepository creates a new streaming CloudWatch repository with enhanced functionality

func (*StreamingCloudWatchRepository) CacheConcurrentViewers

func (r *StreamingCloudWatchRepository) CacheConcurrentViewers(_ context.Context, mediaID string, concurrentMetrics models.ConcurrentViewerMetrics) error

CacheConcurrentViewers stores concurrent viewer metrics in cache

func (*StreamingCloudWatchRepository) CacheGeographicData

func (r *StreamingCloudWatchRepository) CacheGeographicData(_ context.Context, mediaID string, geoMetrics map[string]models.GeographicMetric) error

CacheGeographicData stores geographic distribution metrics in cache

func (*StreamingCloudWatchRepository) CachePerformanceMetrics

func (r *StreamingCloudWatchRepository) CachePerformanceMetrics(_ context.Context, mediaID string, perfMetrics models.StreamingPerformanceMetrics) error

CachePerformanceMetrics stores performance metrics in cache

func (*StreamingCloudWatchRepository) CacheQualityBreakdown

func (r *StreamingCloudWatchRepository) CacheQualityBreakdown(ctx context.Context, mediaID string, qualityMetrics map[string]models.QualityMetric) error

CacheQualityBreakdown stores quality breakdown metrics in cache

func (*StreamingCloudWatchRepository) CleanupExpiredMetrics

func (r *StreamingCloudWatchRepository) CleanupExpiredMetrics(_ context.Context) error

CleanupExpiredMetrics removes expired metrics from cache

func (*StreamingCloudWatchRepository) GetAllCachedMetrics

GetAllCachedMetrics retrieves all cached metrics for a media item

func (*StreamingCloudWatchRepository) GetConcurrentViewers

GetConcurrentViewers retrieves cached concurrent viewer metrics

func (*StreamingCloudWatchRepository) GetGeographicData

GetGeographicData retrieves cached geographic distribution metrics

func (*StreamingCloudWatchRepository) GetPerformanceMetrics

GetPerformanceMetrics retrieves cached performance metrics

func (*StreamingCloudWatchRepository) GetQualityBreakdown

GetQualityBreakdown retrieves cached quality breakdown metrics for a media item

type StreamingConnectionRepository

type StreamingConnectionRepository struct {
	*EnhancedBaseRepository[*models.WebSocketConnection]
	// contains filtered or unexported fields
}

StreamingConnectionRepository handles WebSocket connections using enhanced patterns

func NewStreamingConnectionRepository

func NewStreamingConnectionRepository(db core.DB, tableName string, subscriptionDB core.DB, subscriptionTable string, logger *zap.Logger, costService *cost.TrackingService) *StreamingConnectionRepository

NewStreamingConnectionRepository creates a new streaming connection repository with enhanced functionality

func (*StreamingConnectionRepository) CleanupExpiredConnections

func (r *StreamingConnectionRepository) CleanupExpiredConnections(_ context.Context) (int, error)

CleanupExpiredConnections removes connections that have exceeded their TTL This is typically handled by DynamoDB TTL, but can be called manually for immediate cleanup

func (*StreamingConnectionRepository) CloseTimedOutConnections

func (r *StreamingConnectionRepository) CloseTimedOutConnections(ctx context.Context) (int, error)

CloseTimedOutConnections closes connections that have exceeded their idle timeout

func (*StreamingConnectionRepository) DeleteAllSubscriptions

func (r *StreamingConnectionRepository) DeleteAllSubscriptions(ctx context.Context, connectionID string) error

DeleteAllSubscriptions removes all subscriptions for a connection

func (*StreamingConnectionRepository) DeleteConnection

func (r *StreamingConnectionRepository) DeleteConnection(ctx context.Context, connectionID string) error

DeleteConnection removes a WebSocket connection

func (*StreamingConnectionRepository) DeleteSubscription

func (r *StreamingConnectionRepository) DeleteSubscription(ctx context.Context, connectionID, stream string) error

DeleteSubscription removes a stream subscription

func (*StreamingConnectionRepository) EnforceResourceLimits

func (r *StreamingConnectionRepository) EnforceResourceLimits(ctx context.Context, connectionID string, messageSize int64) error

EnforceResourceLimits enforces resource limits on connections

func (*StreamingConnectionRepository) GetActiveConnectionsCount

func (r *StreamingConnectionRepository) GetActiveConnectionsCount(ctx context.Context, userID string) (int, error)

GetActiveConnectionsCount gets the count of active connections for a user

func (*StreamingConnectionRepository) GetConnection

func (r *StreamingConnectionRepository) GetConnection(ctx context.Context, connectionID string) (*models.WebSocketConnection, error)

GetConnection retrieves a WebSocket connection by connection ID

func (*StreamingConnectionRepository) GetConnectionCountByState

func (r *StreamingConnectionRepository) GetConnectionCountByState(ctx context.Context, state models.ConnectionState) (int, error)

GetConnectionCountByState returns the number of connections currently recorded in the provided state

func (*StreamingConnectionRepository) GetConnectionPool

func (r *StreamingConnectionRepository) GetConnectionPool(ctx context.Context) (map[string]interface{}, error)

GetConnectionPool returns current connection pool statistics

func (*StreamingConnectionRepository) GetConnectionsByState

GetConnectionsByState gets all connections in a specific state

func (*StreamingConnectionRepository) GetConnectionsByUser

func (r *StreamingConnectionRepository) GetConnectionsByUser(ctx context.Context, userID string) ([]models.WebSocketConnection, error)

GetConnectionsByUser gets all connections for a user

func (*StreamingConnectionRepository) GetDB

GetDB returns the main database connection for direct access

func (*StreamingConnectionRepository) GetHealthyConnections

func (r *StreamingConnectionRepository) GetHealthyConnections(ctx context.Context) ([]models.WebSocketConnection, error)

GetHealthyConnections gets all healthy connections

func (*StreamingConnectionRepository) GetIdleConnections

func (r *StreamingConnectionRepository) GetIdleConnections(ctx context.Context, idleThreshold time.Time) ([]models.WebSocketConnection, error)

GetIdleConnections gets WebSocket connections that have been idle past the threshold

func (*StreamingConnectionRepository) GetStaleConnections

func (r *StreamingConnectionRepository) GetStaleConnections(ctx context.Context, staleThreshold time.Time) ([]models.WebSocketConnection, error)

GetStaleConnections gets WebSocket connections that are considered stale (very old with no recent activity)

func (*StreamingConnectionRepository) GetSubscriptionsForStream

func (r *StreamingConnectionRepository) GetSubscriptionsForStream(ctx context.Context, stream string) ([]models.WebSocketSubscription, error)

GetSubscriptionsForStream gets all subscriptions for a specific stream

func (*StreamingConnectionRepository) GetTotalActiveConnectionsCount

func (r *StreamingConnectionRepository) GetTotalActiveConnectionsCount(ctx context.Context) (int, error)

GetTotalActiveConnectionsCount gets the total count of active connections across all users

func (*StreamingConnectionRepository) GetUnhealthyConnections

func (r *StreamingConnectionRepository) GetUnhealthyConnections(ctx context.Context) ([]models.WebSocketConnection, error)

GetUnhealthyConnections gets connections that need attention

func (*StreamingConnectionRepository) GetUserConnectionCount

func (r *StreamingConnectionRepository) GetUserConnectionCount(ctx context.Context, userID string) (int, error)

GetUserConnectionCount returns the number of connections associated with the supplied user

func (*StreamingConnectionRepository) MarkConnectionsIdle

func (r *StreamingConnectionRepository) MarkConnectionsIdle(ctx context.Context, idleThreshold time.Duration) (int, error)

MarkConnectionsIdle marks inactive connections as idle

func (*StreamingConnectionRepository) ReclaimIdleConnections

func (r *StreamingConnectionRepository) ReclaimIdleConnections(ctx context.Context, maxIdleConnections int) (int, error)

ReclaimIdleConnections proactively closes old idle connections to free resources

func (*StreamingConnectionRepository) RecordConnectionError

func (r *StreamingConnectionRepository) RecordConnectionError(ctx context.Context, connectionID string, errorMsg string) error

RecordConnectionError records an error for a connection

func (*StreamingConnectionRepository) RecordConnectionMessage

func (r *StreamingConnectionRepository) RecordConnectionMessage(ctx context.Context, connectionID string, sent bool, messageSize int64) error

RecordConnectionMessage records message statistics and updates activity

func (*StreamingConnectionRepository) RecordPing

func (r *StreamingConnectionRepository) RecordPing(ctx context.Context, connectionID string) error

RecordPing records a ping for a connection

func (*StreamingConnectionRepository) RecordPong

func (r *StreamingConnectionRepository) RecordPong(ctx context.Context, connectionID string) error

RecordPong records a pong for a connection

func (*StreamingConnectionRepository) UpdateConnection

func (r *StreamingConnectionRepository) UpdateConnection(ctx context.Context, connection *models.WebSocketConnection) error

UpdateConnection updates an existing WebSocket connection

func (*StreamingConnectionRepository) UpdateConnectionActivity

func (r *StreamingConnectionRepository) UpdateConnectionActivity(ctx context.Context, connectionID string) error

UpdateConnectionActivity updates the last activity timestamp for a connection

func (*StreamingConnectionRepository) UpdateConnectionState

func (r *StreamingConnectionRepository) UpdateConnectionState(ctx context.Context, connectionID string, newState models.ConnectionState, reason string) error

UpdateConnectionState updates the connection state with proper state transition

func (*StreamingConnectionRepository) WriteConnection

func (r *StreamingConnectionRepository) WriteConnection(ctx context.Context, connectionID, userID, username string, streams []string) (*models.WebSocketConnection, error)

WriteConnection stores a WebSocket connection with full lifecycle initialization and connection pooling

func (*StreamingConnectionRepository) WriteSubscription

func (r *StreamingConnectionRepository) WriteSubscription(ctx context.Context, connectionID, userID, stream string) error

WriteSubscription stores a stream subscription

type StreamingRepository

type StreamingRepository struct {
	*EnhancedBaseRepository[*models.StreamingPreferences]
	// contains filtered or unexported fields
}

StreamingRepository implements the streaming preferences repository using enhanced patterns

func NewStreamingRepository

func NewStreamingRepository(db core.DB, tableName string, logger *zap.Logger, deviceProvider DeviceProvider, costService *cost.TrackingService) *StreamingRepository

NewStreamingRepository creates a new StreamingRepository with enhanced functionality

func (*StreamingRepository) GetStreamingPreferenceHistory

func (r *StreamingRepository) GetStreamingPreferenceHistory(ctx context.Context, username string, limit int) ([]*storage.StreamingPreferences, error)

GetStreamingPreferenceHistory retrieves the version history of streaming preferences

func (*StreamingRepository) GetStreamingPreferences

func (r *StreamingRepository) GetStreamingPreferences(ctx context.Context, username string) (*storage.StreamingPreferences, error)

GetStreamingPreferences retrieves streaming preferences for a user

func (*StreamingRepository) GetStreamingPreferencesByDevice

func (r *StreamingRepository) GetStreamingPreferencesByDevice(ctx context.Context, username, deviceID string) (*storage.StreamingPreferences, error)

GetStreamingPreferencesByDevice retrieves device-specific streaming preferences

func (*StreamingRepository) ResolvePreferenceConflict

func (r *StreamingRepository) ResolvePreferenceConflict(ctx context.Context, username string, strategy storage.ConflictResolutionStrategy) (*storage.StreamingPreferences, error)

ResolvePreferenceConflict resolves conflicts between different preference versions

func (*StreamingRepository) SyncStreamingPreferences

func (r *StreamingRepository) SyncStreamingPreferences(ctx context.Context, username string, sourceDeviceID string) error

SyncStreamingPreferences syncs preferences across devices

func (*StreamingRepository) UpdateDeviceStreamingPreferences

func (r *StreamingRepository) UpdateDeviceStreamingPreferences(ctx context.Context, prefs *storage.StreamingPreferences, deviceID string) error

UpdateDeviceStreamingPreferences updates device-specific streaming preferences

func (*StreamingRepository) UpdateStreamingPreferences

func (r *StreamingRepository) UpdateStreamingPreferences(ctx context.Context, prefs *storage.StreamingPreferences) error

UpdateStreamingPreferences updates streaming preferences for a user

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

func (*ThreadContextResult) GetChildren

func (r *ThreadContextResult) GetChildren(parentID string) []*models.ThreadNode

GetChildren returns direct children of a given node

func (*ThreadContextResult) GetNodesByDepth

func (r *ThreadContextResult) GetNodesByDepth() map[int][]*models.ThreadNode

GetNodesByDepth returns nodes organized by depth

func (*ThreadContextResult) GetRootNode

func (r *ThreadContextResult) GetRootNode() *models.ThreadNode

GetRootNode returns the root node of the thread

type ThreadRepository

type ThreadRepository struct {
	// contains filtered or unexported fields
}

ThreadRepository handles thread synchronization and traversal operations

func NewThreadRepository

func NewThreadRepository(db core.DB, logger *zap.Logger) *ThreadRepository

NewThreadRepository creates a new ThreadRepository instance

func (*ThreadRepository) BulkSaveThreadNodes

func (r *ThreadRepository) BulkSaveThreadNodes(ctx context.Context, nodes []*models.ThreadNode) error

BulkSaveThreadNodes saves multiple thread nodes in a batch

func (*ThreadRepository) DeleteMissingReply

func (r *ThreadRepository) DeleteMissingReply(ctx context.Context, rootStatusID, replyID string) error

DeleteMissingReply deletes a missing reply record (used when resolved)

func (*ThreadRepository) GetMissingReplies

func (r *ThreadRepository) GetMissingReplies(ctx context.Context, rootStatusID string) ([]*models.MissingReply, error)

GetMissingReplies retrieves all missing replies for a thread

func (*ThreadRepository) GetPendingMissingReplies

func (r *ThreadRepository) GetPendingMissingReplies(_ context.Context, _ int) ([]*models.MissingReply, error)

GetPendingMissingReplies retrieves missing replies that should be retried

func (*ThreadRepository) GetThreadContext

func (r *ThreadRepository) GetThreadContext(ctx context.Context, statusID string) (*ThreadContextResult, error)

GetThreadContext builds a complete thread context by querying nodes

func (*ThreadRepository) GetThreadNode

func (r *ThreadRepository) GetThreadNode(ctx context.Context, rootStatusID, statusID string) (*models.ThreadNode, error)

GetThreadNode retrieves a single thread node by status ID

func (*ThreadRepository) GetThreadNodeByStatusID

func (r *ThreadRepository) GetThreadNodeByStatusID(ctx context.Context, statusID string) (*models.ThreadNode, error)

GetThreadNodeByStatusID retrieves a thread node by status ID using GSI

func (*ThreadRepository) GetThreadNodes

func (r *ThreadRepository) GetThreadNodes(ctx context.Context, rootStatusID string) ([]*models.ThreadNode, error)

GetThreadNodes retrieves all nodes for a thread by root status ID

func (*ThreadRepository) GetThreadSync

func (r *ThreadRepository) GetThreadSync(ctx context.Context, statusID string) (*models.ThreadSync, error)

GetThreadSync retrieves a thread sync record by status ID

func (*ThreadRepository) MarkMissingReplies

func (r *ThreadRepository) MarkMissingReplies(ctx context.Context, rootStatusID, parentStatusID string, replyIDs []string) error

MarkMissingReplies marks multiple replies as missing in a thread

func (*ThreadRepository) SaveMissingReply

func (r *ThreadRepository) SaveMissingReply(ctx context.Context, missing *models.MissingReply) error

SaveMissingReply saves or updates a missing reply record

func (*ThreadRepository) SaveThreadNode

func (r *ThreadRepository) SaveThreadNode(ctx context.Context, node *models.ThreadNode) error

SaveThreadNode saves or updates a thread node

func (*ThreadRepository) SaveThreadSync

func (r *ThreadRepository) SaveThreadSync(ctx context.Context, sync *models.ThreadSync) error

SaveThreadSync saves or updates a thread sync record

type ThreatIntel

type ThreatIntel struct {
	ID           string
	ThreatType   string
	Indicators   []string
	Severity     string
	Description  string
	SourceDomain string
	FirstSeen    time.Time
	LastSeen     time.Time
	HitCount     int64
	Confidence   float64
	TTL          time.Duration
}

ThreatIntel represents threat intelligence data for the repository interface

type ThreatIntelRepository

type ThreatIntelRepository struct {
	*EnhancedBaseRepository[*models.ThreatIntel]
	// contains filtered or unexported fields
}

ThreatIntelRepository implements threat intelligence operations using BaseRepository

func NewThreatIntelRepository

func NewThreatIntelRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *ThreatIntelRepository

NewThreatIntelRepository creates a new threat intelligence repository

func (*ThreatIntelRepository) GetIndicatorThreat

func (r *ThreatIntelRepository) GetIndicatorThreat(ctx context.Context, indicator string) (string, error)

GetIndicatorThreat looks up threat ID by indicator

func (*ThreatIntelRepository) GetSharedThreats

func (r *ThreatIntelRepository) GetSharedThreats(ctx context.Context, since time.Time) ([]*ThreatIntel, error)

GetSharedThreats retrieves threats shared since a given time

func (*ThreatIntelRepository) GetThreatByID

func (r *ThreatIntelRepository) GetThreatByID(ctx context.Context, threatID string) (*ThreatIntel, error)

GetThreatByID retrieves a specific threat by ID

func (*ThreatIntelRepository) GetThreatsByType

func (r *ThreatIntelRepository) GetThreatsByType(ctx context.Context, threatType string, limit int) ([]*ThreatIntel, error)

GetThreatsByType retrieves threats of a specific type

func (*ThreatIntelRepository) IncrementHitCount

func (r *ThreatIntelRepository) IncrementHitCount(ctx context.Context, threatID string) error

IncrementHitCount increments the hit count for a threat

func (*ThreatIntelRepository) LoadActiveThreats

func (r *ThreatIntelRepository) LoadActiveThreats(ctx context.Context) ([]*ThreatIntel, error)

LoadActiveThreats loads all active (non-expired) threats

func (*ThreatIntelRepository) ShareThreat

func (r *ThreatIntelRepository) ShareThreat(ctx context.Context, threat *ThreatIntel) error

ShareThreat stores a threat in DynamoDB and creates indicator mappings

func (*ThreatIntelRepository) UpdateThreatConfidence

func (r *ThreatIntelRepository) UpdateThreatConfidence(ctx context.Context, threatID string, newConfidence float64) error

UpdateThreatConfidence updates the confidence score of a threat

type TimeUtils

type TimeUtils struct{}

TimeUtils provides utilities for time-based operations

func NewTimeUtils

func NewTimeUtils() *TimeUtils

NewTimeUtils creates a new TimeUtils instance

func (*TimeUtils) TTLFromDuration

func (t *TimeUtils) TTLFromDuration(duration time.Duration) int64

TTLFromDuration creates a TTL timestamp from current time + duration

func (*TimeUtils) ToUnixTimestamp

func (t *TimeUtils) ToUnixTimestamp(timestamp time.Time) int64

ToUnixTimestamp converts time to Unix timestamp for DynamoDB TTL

type TimelineRepository

type TimelineRepository struct {
	*EnhancedBaseRepository[*models.Timeline]
}

TimelineRepository handles timeline operations using enhanced DynamORM patterns

func NewTimelineRepository

func NewTimelineRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *TimelineRepository

NewTimelineRepository creates a new timeline repository with enhanced functionality

func (*TimelineRepository) CountTimelineEntries

func (r *TimelineRepository) CountTimelineEntries(ctx context.Context, timelineType, timelineID string) (int, error)

CountTimelineEntries counts the number of entries in a timeline using BaseRepository

func (*TimelineRepository) CreateTimelineEntries

func (r *TimelineRepository) CreateTimelineEntries(ctx context.Context, entries []*models.Timeline) error

CreateTimelineEntries creates multiple timeline entries in batch using BaseRepository

func (*TimelineRepository) CreateTimelineEntry

func (r *TimelineRepository) CreateTimelineEntry(ctx context.Context, entry *models.Timeline) error

CreateTimelineEntry creates a new timeline entry using BaseRepository

func (*TimelineRepository) DeleteExpiredTimelineEntries

func (r *TimelineRepository) DeleteExpiredTimelineEntries(_ context.Context, before time.Time) error

DeleteExpiredTimelineEntries deletes timeline entries that have expired

func (*TimelineRepository) DeleteTimelineEntriesByPost

func (r *TimelineRepository) DeleteTimelineEntriesByPost(ctx context.Context, postID string) error

DeleteTimelineEntriesByPost deletes all timeline entries for a specific post using BaseRepository

func (*TimelineRepository) DeleteTimelineEntry

func (r *TimelineRepository) DeleteTimelineEntry(ctx context.Context, timelineType, timelineID, entryID string, timelineAt time.Time) error

DeleteTimelineEntry deletes a specific timeline entry using BaseRepository

func (*TimelineRepository) GetConversations

func (r *TimelineRepository) GetConversations(ctx context.Context, username string, limit int, cursor string) ([]*models.Conversation, string, error)

GetConversations retrieves conversations for a user (timeline interface compatibility) This bridges between timeline interface and conversation repository

func (*TimelineRepository) GetDirectTimeline

func (r *TimelineRepository) GetDirectTimeline(ctx context.Context, username string, limit int, cursor string) ([]*models.Timeline, string, error)

GetDirectTimeline retrieves direct message timeline entries for a user

func (*TimelineRepository) GetHashtagTimeline

func (r *TimelineRepository) GetHashtagTimeline(ctx context.Context, hashtag string, local bool, limit int, cursor string) ([]*models.Timeline, string, error)

GetHashtagTimeline retrieves timeline entries for a specific hashtag

func (*TimelineRepository) GetHomeTimeline

func (r *TimelineRepository) GetHomeTimeline(ctx context.Context, username string, limit int, cursor string) ([]*models.Timeline, string, error)

GetHomeTimeline retrieves home timeline entries for a user

func (*TimelineRepository) GetListTimeline

func (r *TimelineRepository) GetListTimeline(ctx context.Context, listID string, limit int, cursor string) ([]*models.Timeline, string, error)

GetListTimeline retrieves timeline entries for a specific list

func (*TimelineRepository) GetPublicTimeline

func (r *TimelineRepository) GetPublicTimeline(_ context.Context, local bool, limit int, cursor string) ([]*models.Timeline, string, error)

GetPublicTimeline retrieves public timeline entries

func (*TimelineRepository) GetTimelineEntriesByActor

func (r *TimelineRepository) GetTimelineEntriesByActor(ctx context.Context, actorID string, limit int, cursor string) ([]*models.Timeline, string, error)

GetTimelineEntriesByActor retrieves all timeline entries by a specific actor

func (*TimelineRepository) GetTimelineEntriesByLanguage

func (r *TimelineRepository) GetTimelineEntriesByLanguage(ctx context.Context, language string, limit int, cursor string) ([]*models.Timeline, string, error)

GetTimelineEntriesByLanguage retrieves timeline entries by language

func (*TimelineRepository) GetTimelineEntriesByPost

func (r *TimelineRepository) GetTimelineEntriesByPost(ctx context.Context, postID string, limit int, cursor string) ([]*models.Timeline, string, error)

GetTimelineEntriesByPost retrieves all timeline entries for a specific post

func (*TimelineRepository) GetTimelineEntriesByVisibility

func (r *TimelineRepository) GetTimelineEntriesByVisibility(ctx context.Context, visibility string, limit int, cursor string) ([]*models.Timeline, string, error)

GetTimelineEntriesByVisibility retrieves timeline entries by visibility level

func (*TimelineRepository) GetTimelineEntriesInRange

func (r *TimelineRepository) GetTimelineEntriesInRange(ctx context.Context, timelineType, timelineID string, startTime, endTime time.Time, limit int) ([]*models.Timeline, error)

GetTimelineEntriesInRange retrieves timeline entries within a time range using BaseRepository

func (*TimelineRepository) GetTimelineEntriesWithFilters

func (r *TimelineRepository) GetTimelineEntriesWithFilters(ctx context.Context, timelineType, timelineID string, filters interfaces.TimelineFilters, limit int, _ string) ([]*models.Timeline, string, error)

GetTimelineEntriesWithFilters retrieves timeline entries with various filters using BaseRepository

func (*TimelineRepository) GetTimelineEntry

func (r *TimelineRepository) GetTimelineEntry(ctx context.Context, timelineType, timelineID, entryID string, timelineAt time.Time) (*models.Timeline, error)

GetTimelineEntry retrieves a specific timeline entry using BaseRepository

func (*TimelineRepository) RemoveFromTimelines

func (r *TimelineRepository) RemoveFromTimelines(ctx context.Context, objectID string) error

RemoveFromTimelines removes timeline entries for a specific object across all timelines

func (*TimelineRepository) UpdateTimelineEntry

func (r *TimelineRepository) UpdateTimelineEntry(ctx context.Context, entry *models.Timeline) error

UpdateTimelineEntry updates an existing timeline entry using BaseRepository

type TokenStats

type TokenStats struct {
	UserID         string `json:"user_id"`
	TotalTokens    int    `json:"total_tokens"`
	ActiveTokens   int    `json:"active_tokens"`
	RevokedTokens  int    `json:"revoked_tokens"`
	ExpiredTokens  int    `json:"expired_tokens"`
	UniqueFamilies int    `json:"unique_families"`
	LastUsedAt     int64  `json:"last_used_at"`
}

TokenStats represents token statistics for a user

type TrackingRepository

type TrackingRepository struct {
	*EnhancedBaseRepository[*models.DynamoDBCostRecord]
	// contains filtered or unexported fields
}

TrackingRepository handles cost tracking persistence

func NewTrackingRepository

func NewTrackingRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *TrackingRepository

NewTrackingRepository creates a new cost tracking repository with enhanced functionality

func (*TrackingRepository) Aggregate

func (r *TrackingRepository) Aggregate(ctx context.Context, operationType, period string, windowStart, windowEnd time.Time) error

Aggregate performs aggregation of raw cost tracking data

func (*TrackingRepository) AggregateRelayCosts

func (r *TrackingRepository) AggregateRelayCosts(ctx context.Context, relayURL, period string, windowStart, windowEnd time.Time) error

AggregateRelayCosts aggregates raw relay cost data into metrics

func (*TrackingRepository) BatchCreate

func (r *TrackingRepository) BatchCreate(ctx context.Context, trackingList []*models.DynamoDBCostRecord) error

BatchCreate creates multiple cost tracking records efficiently using enhanced validation

func (*TrackingRepository) Create

Create creates a new cost tracking record

func (*TrackingRepository) CreateAggregated

func (r *TrackingRepository) CreateAggregated(ctx context.Context, aggregated *models.DynamoDBCostAggregation) error

CreateAggregated creates an aggregated cost tracking record

func (*TrackingRepository) CreateRelayBudget

func (r *TrackingRepository) CreateRelayBudget(ctx context.Context, budget *models.RelayBudget) error

CreateRelayBudget creates a new relay budget configuration

func (*TrackingRepository) CreateRelayCost

func (r *TrackingRepository) CreateRelayCost(ctx context.Context, relayCost *models.RelayCost) error

CreateRelayCost creates a new relay cost record

func (*TrackingRepository) CreateRelayMetrics

func (r *TrackingRepository) CreateRelayMetrics(ctx context.Context, metrics *models.RelayMetrics) error

CreateRelayMetrics creates or updates relay metrics

func (*TrackingRepository) Get

func (r *TrackingRepository) Get(ctx context.Context, operationType, id string, timestamp time.Time) (*models.DynamoDBCostRecord, error)

Get retrieves a cost tracking record by operation type, timestamp and ID

func (*TrackingRepository) GetActivityCost

func (r *TrackingRepository) GetActivityCost(ctx context.Context, activityID string) (*models.DynamoDBCostRecord, error)

GetActivityCost retrieves cost tracking data for a specific activity

func (*TrackingRepository) GetAggregated

func (r *TrackingRepository) GetAggregated(ctx context.Context, period, operationType string, windowStart time.Time) (*models.DynamoDBCostAggregation, error)

GetAggregated retrieves aggregated cost tracking

func (*TrackingRepository) GetAggregatedCostsByPeriod

func (r *TrackingRepository) GetAggregatedCostsByPeriod(ctx context.Context, period string, startDate, endDate time.Time) ([]*models.DynamoDBCostAggregation, error)

GetAggregatedCostsByPeriod retrieves aggregated costs for a specific period

func (*TrackingRepository) GetCostProjections

func (r *TrackingRepository) GetCostProjections(ctx context.Context, period string) (*storage.CostProjection, error)

GetCostProjections retrieves the most recent cost projection for the given period

func (*TrackingRepository) GetCostTrends

func (r *TrackingRepository) GetCostTrends(ctx context.Context, period string, operationType string, lookbackDays int) (*CostTrend, error)

GetCostTrends calculates cost trends over time

func (*TrackingRepository) GetCostsByDateRange

func (r *TrackingRepository) GetCostsByDateRange(ctx context.Context, startDate, _ time.Time) ([]*models.DynamoDBCostRecord, error)

GetCostsByDateRange returns individual cost records for the specified date range

func (*TrackingRepository) GetCostsByOperationType

func (r *TrackingRepository) GetCostsByOperationType(ctx context.Context, startDate, endDate time.Time) (map[string]*models.DynamoDBServiceCostStats, error)

GetCostsByOperationType retrieves costs grouped by operation type

func (*TrackingRepository) GetCostsByService

func (r *TrackingRepository) GetCostsByService(ctx context.Context, startDate, endDate time.Time) (map[string]*models.DynamoDBServiceCostStats, error)

GetCostsByService retrieves costs grouped by service/function

func (*TrackingRepository) GetDailyAggregates

func (r *TrackingRepository) GetDailyAggregates(ctx context.Context, startDate, endDate time.Time) ([]*DailyAggregate, error)

GetDailyAggregates returns aggregated daily costs for the specified date range

func (*TrackingRepository) GetHighCostOperations

func (r *TrackingRepository) GetHighCostOperations(ctx context.Context, thresholdDollars float64, startTime, endTime time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

GetHighCostOperations returns operations that exceed a cost threshold

func (*TrackingRepository) GetHighCostRelayOperations

func (r *TrackingRepository) GetHighCostRelayOperations(ctx context.Context, thresholdMicroCents int64, startTime, endTime time.Time, limit int) ([]*models.RelayCost, error)

GetHighCostRelayOperations returns relay operations that exceed a cost threshold

func (*TrackingRepository) GetImportExportCostsByUser

func (r *TrackingRepository) GetImportExportCostsByUser(ctx context.Context, username string, startDate, endDate time.Time) (*ImportExportUserCostSummary, error)

GetImportExportCostsByUser retrieves combined import and export costs for a user

func (*TrackingRepository) GetImportExportMetrics

func (r *TrackingRepository) GetImportExportMetrics(ctx context.Context, startDate, endDate time.Time) (*ImportExportMetrics, error)

GetImportExportMetrics calculates key metrics for import/export operations

func (*TrackingRepository) GetImportExportTrends

func (r *TrackingRepository) GetImportExportTrends(ctx context.Context, lookbackDays int) (*ImportExportTrends, error)

GetImportExportTrends calculates cost trends for import/export operations

func (*TrackingRepository) GetMonthlyAggregate

func (r *TrackingRepository) GetMonthlyAggregate(ctx context.Context, year, month int) (*MonthlyAggregate, error)

GetMonthlyAggregate returns aggregated costs for the specified month

func (*TrackingRepository) GetRecentCosts

func (r *TrackingRepository) GetRecentCosts(ctx context.Context, since time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

GetRecentCosts retrieves recent cost tracking records across all operations

func (*TrackingRepository) GetRelayBudget

func (r *TrackingRepository) GetRelayBudget(ctx context.Context, relayURL, period string) (*models.RelayBudget, error)

GetRelayBudget retrieves relay budget configuration

func (*TrackingRepository) GetRelayCostSummary

func (r *TrackingRepository) GetRelayCostSummary(ctx context.Context, relayURL string, startTime, endTime time.Time) (*RelayCostSummary, error)

GetRelayCostSummary aggregates relay cost metrics between the provided timestamps.

func (*TrackingRepository) GetRelayCostsByDateRange

func (r *TrackingRepository) GetRelayCostsByDateRange(ctx context.Context, startDate, endDate time.Time, limit int) ([]*models.RelayCost, error)

GetRelayCostsByDateRange retrieves relay costs for all relays within a date range

func (*TrackingRepository) GetRelayCostsByURL

func (r *TrackingRepository) GetRelayCostsByURL(ctx context.Context, relayURL string, startTime, endTime time.Time, limit int, cursor string, operationType string) ([]*models.RelayCost, string, error)

GetRelayCostsByURL retrieves relay costs for a specific relay URL within a time range

func (*TrackingRepository) GetRelayMetrics

func (r *TrackingRepository) GetRelayMetrics(ctx context.Context, relayURL, period string, windowStart time.Time) (*models.RelayMetrics, error)

GetRelayMetrics retrieves relay metrics for a specific relay and period

func (*TrackingRepository) GetRelayMetricsHistory

func (r *TrackingRepository) GetRelayMetricsHistory(ctx context.Context, relayURL string, startTime, endTime time.Time, limit int, cursor string) ([]*models.RelayMetrics, string, error)

GetRelayMetricsHistory retrieves metrics history for a relay

func (*TrackingRepository) GetTableCostStats

func (r *TrackingRepository) GetTableCostStats(ctx context.Context, tableName string, startTime, endTime time.Time) (*TableCostStats, error)

GetTableCostStats calculates cost statistics for a table

func (*TrackingRepository) GetTopCostlyUsers

func (r *TrackingRepository) GetTopCostlyUsers(ctx context.Context, startDate, endDate time.Time, limit int) ([]*UserCostRanking, error)

GetTopCostlyUsers returns users with highest import/export costs

func (*TrackingRepository) ListAggregatedByPeriod

func (r *TrackingRepository) ListAggregatedByPeriod(ctx context.Context, period, operationType string, startTime, endTime time.Time, limit int, cursor string) ([]*models.DynamoDBCostAggregation, string, error)

ListAggregatedByPeriod lists aggregated cost tracking for a period

func (*TrackingRepository) ListByOperationType

func (r *TrackingRepository) ListByOperationType(ctx context.Context, operationType string, startTime, endTime time.Time, limit int) ([]*models.DynamoDBCostRecord, error)

ListByOperationType lists cost tracking records by operation type within a time range

func (*TrackingRepository) ListByTable

func (r *TrackingRepository) ListByTable(ctx context.Context, tableName string, startTime, endTime time.Time, limit int, cursor string) ([]*models.DynamoDBCostRecord, string, error)

ListByTable lists cost tracking records by table within a time range

func (*TrackingRepository) UpdateAggregated

func (r *TrackingRepository) UpdateAggregated(ctx context.Context, aggregated *models.DynamoDBCostAggregation) error

UpdateAggregated updates an existing aggregated cost tracking record

func (*TrackingRepository) UpdateRelayBudget

func (r *TrackingRepository) UpdateRelayBudget(ctx context.Context, budget *models.RelayBudget) error

UpdateRelayBudget updates an existing relay budget

func (*TrackingRepository) UpdateRelayMetrics

func (r *TrackingRepository) UpdateRelayMetrics(ctx context.Context, metrics *models.RelayMetrics) error

UpdateRelayMetrics updates existing relay metrics

type TrendDeletable

type TrendDeletable interface {
	GetIdentifier() string // Returns a string that identifies the trend for logging
}

TrendDeletable defines the interface for trend models that can be deleted

type TrendModel

type TrendModel interface {
	UpdateKeys() error
}

TrendModel represents any trend model that can be stored

type TrendingAnalytics

type TrendingAnalytics struct {
	Period             time.Time `json:"period"`
	TotalHashtags      int64     `json:"total_hashtags"`
	TotalUsage         int64     `json:"total_usage"`
	UniqueUsers        int64     `json:"unique_users"`
	TrendingCandidates int64     `json:"trending_candidates"`
	AverageUsagePerTag float64   `json:"average_usage_per_tag"`
	AverageUsersPerTag float64   `json:"average_users_per_tag"`
	TrendingThreshold  float64   `json:"trending_threshold"`
	MinimumUsage       int64     `json:"minimum_usage"`
	MinimumUsers       int64     `json:"minimum_users"`
	CalculationWindows int       `json:"calculation_windows"`
	GeneratedAt        time.Time `json:"generated_at"`
}

TrendingAnalytics provides insights into the trending calculation process

type TrendingCache

type TrendingCache struct {
	// contains filtered or unexported fields
}

TrendingCache provides intelligent caching for trending calculations

func NewTrendingCache

func NewTrendingCache(expiration time.Duration) *TrendingCache

NewTrendingCache creates a new trending cache

type TrendingCalculator

type TrendingCalculator struct {
	// contains filtered or unexported fields
}

TrendingCalculator handles sophisticated hashtag trending computation

func NewTrendingCalculator

func NewTrendingCalculator(config TrendingCalculatorConfig, logger *zap.Logger) *TrendingCalculator

NewTrendingCalculator creates a new trending calculator with the given configuration

type TrendingCalculatorConfig

type TrendingCalculatorConfig struct {
	// Time decay parameters
	DecayHalfLife time.Duration // How quickly scores decay
	MinimumAge    time.Duration // Minimum age before considering trending
	MaximumAge    time.Duration // Maximum age for trending consideration

	// Scoring weights
	UsageWeight      float64 // Weight for usage count
	EngagementWeight float64 // Weight for engagement metrics
	DiversityWeight  float64 // Weight for user diversity
	TrustWeight      float64 // Weight for trust scores
	MomentumWeight   float64 // Weight for trending momentum

	// Thresholds
	MinimumUsage      int64   // Minimum usage count to consider
	MinimumUsers      int64   // Minimum unique users to consider
	TrendingThreshold float64 // Score threshold for trending

	// Time windows for analysis
	TimeWindows []TrendingTimeWindow
}

TrendingCalculatorConfig holds configuration for trending algorithm

type TrendingEngine

type TrendingEngine struct {
	// contains filtered or unexported fields
}

TrendingEngine provides sophisticated hashtag trending calculation and analysis

func NewTrendingEngine

func NewTrendingEngine(db core.DB, logger *zap.Logger) *TrendingEngine

NewTrendingEngine creates a new trending engine with default configuration

func (*TrendingEngine) CalculateTrending

func (te *TrendingEngine) CalculateTrending(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

CalculateTrending performs comprehensive trending analysis

type TrendingEngineConfig

type TrendingEngineConfig struct {
	// Time windows for analysis
	TimeWindows map[string]TrendingTimeWindow `json:"time_windows"`

	// Scoring algorithm parameters
	Scoring TrendingScoringConfig `json:"scoring"`

	// Data collection settings
	MinimumUsage int64         `json:"minimum_usage"` // Minimum usage to be considered
	MinimumUsers int64         `json:"minimum_users"` // Minimum unique users
	MinimumAge   time.Duration `json:"minimum_age"`   // Minimum age before trending
	MaximumAge   time.Duration `json:"maximum_age"`   // Maximum age for consideration

	// Performance settings
	CandidateLimit   int           `json:"candidate_limit"`   // Max candidates to analyze
	CacheExpiration  time.Duration `json:"cache_expiration"`  // Cache expiration time
	BackgroundUpdate bool          `json:"background_update"` // Update in background

	// Quality controls
	TrustThreshold       float64 `json:"trust_threshold"`        // Minimum trust score
	DiversityThreshold   float64 `json:"diversity_threshold"`    // Minimum diversity ratio
	SpamDetectionEnabled bool    `json:"spam_detection_enabled"` // Enable spam detection
}

TrendingEngineConfig holds configuration for the trending engine

type TrendingHashtagResult

type TrendingHashtagResult struct {
	HashtagName string                  `json:"hashtag_name"`
	Score       float64                 `json:"score"`
	Metrics     *EnhancedHashtagMetrics `json:"metrics"`
	Components  map[string]float64      `json:"components"`
}

TrendingHashtagResult represents a hashtag with its trending analysis

type TrendingMetrics

type TrendingMetrics struct {
	HashtagName     string
	TotalUsage      int64
	UniqueUsers     int64
	Engagements     int64
	TrustScore      float64
	FirstSeen       time.Time
	LastUsed        time.Time
	TimeWindowData  map[string]*WindowMetrics
	HistoricalTrend []float64 // 7-day historical scores
	MomentumScore   float64   // Rate of change
}

TrendingMetrics holds metrics for trending calculation

type TrendingRepository

type TrendingRepository struct {
	*EnhancedBaseRepository[*models.TrendingHashtag]
	// contains filtered or unexported fields
}

TrendingRepository implements trending and analytics operations using enhanced patterns

func NewTrendingRepository

func NewTrendingRepository(db core.DB, logger *zap.Logger, costService *cost.TrackingService) *TrendingRepository

NewTrendingRepository creates a new trending repository

func (*TrendingRepository) AggregateEngagementMetrics

func (r *TrendingRepository) AggregateEngagementMetrics(ctx context.Context, metricType string, dates []string) (*storage.AggregatedEngagement, error)

AggregateEngagementMetrics aggregates metrics across multiple dates

func (*TrendingRepository) CalculateGrowthRate

func (r *TrendingRepository) CalculateGrowthRate(ctx context.Context, metricType, startDate, endDate string) (*storage.GrowthRate, error)

CalculateGrowthRate calculates growth rate between two dates

func (*TrendingRepository) DeleteOldHashtagTrends

func (r *TrendingRepository) DeleteOldHashtagTrends(ctx context.Context, before time.Time) error

DeleteOldHashtagTrends deletes hashtag trend records older than the specified time

func (*TrendingRepository) DeleteOldLinkTrends

func (r *TrendingRepository) DeleteOldLinkTrends(ctx context.Context, before time.Time) error

DeleteOldLinkTrends deletes link trend records older than the specified time

func (*TrendingRepository) DeleteOldStatusTrends

func (r *TrendingRepository) DeleteOldStatusTrends(ctx context.Context, before time.Time) error

DeleteOldStatusTrends deletes status trend records older than the specified time

func (*TrendingRepository) GenerateSearchSuggestions

func (r *TrendingRepository) GenerateSearchSuggestions(ctx context.Context, userID, partialQuery string, limit int) ([]string, error)

GenerateSearchSuggestions generates search suggestions based on user history and popular queries

func (*TrendingRepository) GetActiveUserCount

func (r *TrendingRepository) GetActiveUserCount(ctx context.Context, days int) (int, error)

GetActiveUserCount returns the number of active users in the last N days

func (*TrendingRepository) GetActorInteraction

func (r *TrendingRepository) GetActorInteraction(ctx context.Context, actor1, actor2 string) (*time.Time, error)

GetActorInteraction retrieves the timestamp of the last interaction between two actors This looks for the most recent engagement (like, boost, reply) between the actors

func (*TrendingRepository) GetEngagementByDateRange

func (r *TrendingRepository) GetEngagementByDateRange(ctx context.Context, metricType string, startDate, endDate string, limit int) ([]*storage.EngagementMetricsSummary, error)

GetEngagementByDateRange retrieves engagement metrics within a date range

func (*TrendingRepository) GetEngagementMetrics

func (r *TrendingRepository) GetEngagementMetrics(ctx context.Context, statusID string) (*storage.EngagementMetrics, error)

GetEngagementMetrics retrieves stored engagement metrics for a status

func (*TrendingRepository) GetEngagementMetricsData

func (r *TrendingRepository) GetEngagementMetricsData(ctx context.Context, metricType, targetID, date string) (*storage.EngagementData, error)

GetEngagementMetricsData retrieves engagement metrics for a specific target

func (*TrendingRepository) GetHashtagTrend

func (r *TrendingRepository) GetHashtagTrend(ctx context.Context, hashtag string, days int) (*storage.HashtagTrendHistory, error)

GetHashtagTrend retrieves the trend history for a specific hashtag

func (*TrendingRepository) GetInstanceMetrics

func (r *TrendingRepository) GetInstanceMetrics(ctx context.Context, date, metricType string) (*storage.InstanceMetricData, error)

GetInstanceMetrics retrieves instance metrics for a specific date and type

func (*TrendingRepository) GetManifestGenerationStats

func (r *TrendingRepository) GetManifestGenerationStats(ctx context.Context, format, startDate, endDate string) (map[string]int64, error)

GetManifestGenerationStats retrieves manifest generation statistics for a date range

func (*TrendingRepository) GetMediaEventStats

func (r *TrendingRepository) GetMediaEventStats(ctx context.Context, eventType, startDate, endDate string) (map[string]int64, error)

GetMediaEventStats retrieves general media event statistics

func (*TrendingRepository) GetMetricHistory

func (r *TrendingRepository) GetMetricHistory(ctx context.Context, metricType string, days int) ([]*storage.MetricHistoryPoint, error)

GetMetricHistory retrieves the history of a specific metric type

func (*TrendingRepository) GetModerationAnalytics

func (r *TrendingRepository) GetModerationAnalytics(ctx context.Context, date, reportType string) (*storage.ModerationAnalyticsData, error)

GetModerationAnalytics retrieves moderation analytics for a date and type

func (*TrendingRepository) GetModeratorStats

func (r *TrendingRepository) GetModeratorStats(ctx context.Context, moderatorID string, days int) (*storage.ModeratorStatistics, error)

GetModeratorStats retrieves statistics for a specific moderator

func (*TrendingRepository) GetPopularSearchQueries

func (r *TrendingRepository) GetPopularSearchQueries(ctx context.Context, limit int, timeWindow time.Duration) ([]storage.SearchQueryStats, error)

GetPopularSearchQueries retrieves the most popular search queries

func (*TrendingRepository) GetQueryCount

func (r *TrendingRepository) GetQueryCount(ctx context.Context, query string) (int, error)

GetQueryCount retrieves the current count for a query

func (*TrendingRepository) GetRecentHashtags

func (r *TrendingRepository) GetRecentHashtags(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingHashtag, error)

GetRecentHashtags returns recent hashtags since the given time (no trending calculation)

func (r *TrendingRepository) GetRecentLinks(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingLink, error)

GetRecentLinks returns recent links since the given time (no trending calculation)

func (*TrendingRepository) GetRecentStatusesWithEngagement

func (r *TrendingRepository) GetRecentStatusesWithEngagement(ctx context.Context, since time.Time, limit int) ([]*storage.TrendingStatus, error)

GetRecentStatusesWithEngagement returns recent statuses with engagement since the given time

func (*TrendingRepository) GetReportTrends

func (r *TrendingRepository) GetReportTrends(ctx context.Context, reportTypes []string, days int) (map[string]*storage.ReportTrend, error)

GetReportTrends retrieves trends for different report types

func (r *TrendingRepository) GetStatusesByLink(ctx context.Context, linkURL string, limit int) ([]any, error)

GetStatusesByLink retrieves statuses that contain a specific link

func (*TrendingRepository) GetStreamingAnalytics

func (r *TrendingRepository) GetStreamingAnalytics(ctx context.Context, mediaID string) (*storage.StreamingAnalyticsData, error)

GetStreamingAnalytics retrieves comprehensive streaming analytics for a media item

func (*TrendingRepository) GetTopEngagedContent

func (r *TrendingRepository) GetTopEngagedContent(ctx context.Context, metricType string, date string, limit int) ([]*storage.EngagementRanking, error)

GetTopEngagedContent retrieves the most engaged content

func (*TrendingRepository) GetTopQueries

func (r *TrendingRepository) GetTopQueries(ctx context.Context, limit int, timeRange time.Duration) ([]storage.SearchQueryStats, error)

GetTopQueries retrieves the most popular queries within a time range

func (*TrendingRepository) GetTotalDomainCount

func (r *TrendingRepository) GetTotalDomainCount(ctx context.Context) (int, error)

GetTotalDomainCount returns the total number of federated domains

func (*TrendingRepository) GetTotalStatusCount

func (r *TrendingRepository) GetTotalStatusCount(ctx context.Context) (*int, error)

GetTotalStatusCount returns the total number of statuses

func (*TrendingRepository) GetTotalUserCount

func (r *TrendingRepository) GetTotalUserCount(ctx context.Context) (int, error)

GetTotalUserCount returns the total number of users

func (*TrendingRepository) GetTrendingHashtags

func (r *TrendingRepository) GetTrendingHashtags(ctx context.Context, _ time.Time, limit int) ([]*storage.TrendingHashtag, error)

GetTrendingHashtags returns the top trending hashtags since the given time

func (*TrendingRepository) GetTrendingHashtagsForDate

func (r *TrendingRepository) GetTrendingHashtagsForDate(ctx context.Context, date string, limit int) ([]*storage.TrendingHashtagData, error)

GetTrendingHashtagsForDate retrieves trending hashtags for a specific date

func (r *TrendingRepository) GetTrendingLinks(ctx context.Context, _ time.Time, limit int) ([]*storage.TrendingLink, error)

GetTrendingLinks returns the top trending links since the given time

func (*TrendingRepository) GetTrendingStatuses

func (r *TrendingRepository) GetTrendingStatuses(ctx context.Context, _ time.Time, limit int) ([]*storage.TrendingStatus, error)

GetTrendingStatuses returns the top trending statuses since the given time

func (*TrendingRepository) GetUserSearchHistory

func (r *TrendingRepository) GetUserSearchHistory(ctx context.Context, userID string, limit int) ([]storage.SearchHistoryEntry, error)

GetUserSearchHistory retrieves a user's search history

func (*TrendingRepository) IncrementQueryCount

func (r *TrendingRepository) IncrementQueryCount(ctx context.Context, query string, count int) error

IncrementQueryCount atomically increments the count for a search query

func (*TrendingRepository) IndexByEngagement

func (r *TrendingRepository) IndexByEngagement(ctx context.Context, statusID string, bucket string) error

IndexByEngagement creates an index entry for engagement-based discovery

func (*TrendingRepository) PruneStaleTrends

func (r *TrendingRepository) PruneStaleTrends(ctx context.Context, before time.Time) error

PruneStaleTrends removes old trending entries

func (*TrendingRepository) RecordEngagement

func (r *TrendingRepository) RecordEngagement(ctx context.Context, metricType, targetID, date string, engagement *storage.EngagementData) error

RecordEngagement records engagement metrics for content

func (*TrendingRepository) RecordHashtagUsage

func (r *TrendingRepository) RecordHashtagUsage(ctx context.Context, hashtag string, statusID string, authorID string) error

RecordHashtagUsage records when a hashtag is used in a status

func (*TrendingRepository) RecordInstanceMetric

func (r *TrendingRepository) RecordInstanceMetric(ctx context.Context, date, metricType string, value int64) error

RecordInstanceMetric records a platform-wide metric

func (*TrendingRepository) RecordLinkShare

func (r *TrendingRepository) RecordLinkShare(ctx context.Context, linkURL string, statusID string, authorID string) error

RecordLinkShare records when a link is shared in a status

func (*TrendingRepository) RecordManifestGeneration

func (r *TrendingRepository) RecordManifestGeneration(ctx context.Context, mediaID, format string, duration float64) error

RecordManifestGeneration records when a media manifest is generated

func (*TrendingRepository) RecordMediaEvent

func (r *TrendingRepository) RecordMediaEvent(ctx context.Context, eventType, mediaID, userID string) error

RecordMediaEvent records general media streaming events

func (*TrendingRepository) RecordModerationAction

func (r *TrendingRepository) RecordModerationAction(ctx context.Context, date, reportType string, action *storage.ModerationAction) error

RecordModerationAction records a moderation action for analytics

func (*TrendingRepository) RecordQualityChange

func (r *TrendingRepository) RecordQualityChange(ctx context.Context, mediaID, userID, oldQuality, newQuality string) error

RecordQualityChange records when a user changes video quality

func (*TrendingRepository) RecordStatusEngagement

func (r *TrendingRepository) RecordStatusEngagement(ctx context.Context, statusID string, engagementType string, userID string) error

RecordStatusEngagement records engagement on a status (like, boost, reply)

func (*TrendingRepository) SetStatusRepository

func (r *TrendingRepository) SetStatusRepository(statusRepo interface{})

SetStatusRepository sets the status repository dependency for cross-repository operations

func (*TrendingRepository) StoreEngagementMetrics

func (r *TrendingRepository) StoreEngagementMetrics(ctx context.Context, metrics *storage.EngagementMetrics) error

StoreEngagementMetrics stores engagement metrics for a status

func (*TrendingRepository) StoreHashtagTrend

func (r *TrendingRepository) StoreHashtagTrend(ctx context.Context, trend any) error

StoreHashtagTrend stores a hashtag trend record

func (*TrendingRepository) StoreLinkTrend

func (r *TrendingRepository) StoreLinkTrend(ctx context.Context, trend any) error

StoreLinkTrend stores a link trend record

func (*TrendingRepository) StoreStatusTrend

func (r *TrendingRepository) StoreStatusTrend(ctx context.Context, trend any) error

StoreStatusTrend stores a status trend record

func (*TrendingRepository) TrackSearchQuery

func (r *TrendingRepository) TrackSearchQuery(ctx context.Context, userID, query string, resultCount int) error

TrackSearchQuery records a search query for analytics

func (*TrendingRepository) UpdateTrendingHashtag

func (r *TrendingRepository) UpdateTrendingHashtag(ctx context.Context, hashtag string, date string, useCount, userCount int64) error

UpdateTrendingHashtag updates or creates a trending hashtag entry

type TrendingScore

type TrendingScore struct {
	HashtagName     string
	OverallScore    float64
	ComponentScores map[string]float64 // Individual component scores
	Metrics         *TrendingMetrics
	Rank            int
	Timestamp       time.Time
}

TrendingScore represents the calculated trending score

type TrendingScoringConfig

type TrendingScoringConfig struct {
	// Component weights (should sum to 1.0)
	UsageWeight      float64 `json:"usage_weight"`      // Weight for raw usage count
	VelocityWeight   float64 `json:"velocity_weight"`   // Weight for usage velocity
	AccelWeight      float64 `json:"accel_weight"`      // Weight for acceleration
	DiversityWeight  float64 `json:"diversity_weight"`  // Weight for user diversity
	TrustWeight      float64 `json:"trust_weight"`      // Weight for trust scores
	EngagementWeight float64 `json:"engagement_weight"` // Weight for engagement rate
	NoveltyWeight    float64 `json:"novelty_weight"`    // Weight for newness bonus

	// Decay and normalization
	TimeDecayRate     float64 `json:"time_decay_rate"`    // Exponential decay rate
	VelocitySmoothing float64 `json:"velocity_smoothing"` // Velocity smoothing factor
	ScoreThreshold    float64 `json:"score_threshold"`    // Minimum score for trending

	// Penalties and bonuses
	SpamPenalty      float64 `json:"spam_penalty"`      // Penalty for spam-like behavior
	QualityBonus     float64 `json:"quality_bonus"`     // Bonus for high-quality content
	ConsistencyBonus float64 `json:"consistency_bonus"` // Bonus for consistent usage
}

TrendingScoringConfig holds parameters for the scoring algorithm

type TrendingTimeWindow

type TrendingTimeWindow struct {
	Name     string        // e.g., "1h", "6h", "24h", "7d"
	Duration time.Duration // Window duration
	Weight   float64       // Weight in final score calculation
	MinScore float64       // Minimum score for this window
}

TrendingTimeWindow defines a time window for trending analysis

type TrustRepository

type TrustRepository struct {
	*EnhancedBaseRepository[*models.TrustRelationship]
	// contains filtered or unexported fields
}

TrustRepository handles trust-related operations using enhanced repository patterns

func NewTrustRepository

func NewTrustRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *TrustRepository

NewTrustRepository creates a new trust repository with enhanced functionality

func (*TrustRepository) CreateTrustRelationship

func (r *TrustRepository) CreateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

CreateTrustRelationship creates or updates a trust relationship

func (*TrustRepository) DeleteTrustRelationship

func (r *TrustRepository) DeleteTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) error

DeleteTrustRelationship removes a trust relationship

func (*TrustRepository) GetAllTrustRelationships

func (r *TrustRepository) GetAllTrustRelationships(ctx context.Context, limit int) ([]*storage.TrustRelationship, error)

GetAllTrustRelationships retrieves all trust relationships for admin visualization

func (*TrustRepository) GetTrustRelationship

func (r *TrustRepository) GetTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) (*storage.TrustRelationship, error)

GetTrustRelationship retrieves a specific trust relationship

func (*TrustRepository) GetTrustRelationships

func (r *TrustRepository) GetTrustRelationships(ctx context.Context, trusterID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

GetTrustRelationships retrieves all trust relationships for a truster

func (*TrustRepository) GetTrustScore

func (r *TrustRepository) GetTrustScore(ctx context.Context, actorID, category string) (*storage.TrustScore, error)

GetTrustScore retrieves a cached trust score or calculates it

func (*TrustRepository) GetTrustedByRelationships

func (r *TrustRepository) GetTrustedByRelationships(ctx context.Context, trusteeID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

GetTrustedByRelationships retrieves all relationships where the actor is trusted

func (*TrustRepository) GetUserTrustScore

func (r *TrustRepository) GetUserTrustScore(ctx context.Context, userID string) (float64, error)

GetUserTrustScore retrieves the trust score for a user

func (*TrustRepository) RecordTrustUpdate

func (r *TrustRepository) RecordTrustUpdate(ctx context.Context, update *storage.TrustUpdate) error

RecordTrustUpdate records a trust score update event

func (*TrustRepository) UpdateTrustRelationship

func (r *TrustRepository) UpdateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

UpdateTrustRelationship updates an existing trust relationship

func (*TrustRepository) UpdateTrustScore

func (r *TrustRepository) UpdateTrustScore(ctx context.Context, score *storage.TrustScore) error

UpdateTrustScore updates a cached trust score

type URLExtractionResult

type URLExtractionResult struct {
	OriginalURL    string            `json:"original_url"`
	NormalizedURL  string            `json:"normalized_url"`
	Domain         string            `json:"domain"`
	Subdomain      string            `json:"subdomain,omitempty"`
	Path           string            `json:"path,omitempty"`
	ProfileType    string            `json:"profile_type,omitempty"` // twitter, mastodon, github, etc.
	Username       string            `json:"username,omitempty"`     // extracted username from URL
	IsValid        bool              `json:"is_valid"`
	IsSecure       bool              `json:"is_secure"` // https
	IsSocial       bool              `json:"is_social"` // known social media platform
	IsShortened    bool              `json:"is_shortened"`
	ValidationTags []string          `json:"validation_tags,omitempty"`
	Metadata       map[string]string `json:"metadata,omitempty"`
}

URLExtractionResult represents the result of URL extraction and validation

type URLValidator

type URLValidator struct {
	// contains filtered or unexported fields
}

URLValidator provides enhanced URL extraction and validation

func NewURLValidator

func NewURLValidator(logger *zap.Logger) *URLValidator

NewURLValidator creates a new URL validator

func (*URLValidator) EnhancedExtractAccountFromReply

func (uv *URLValidator) EnhancedExtractAccountFromReply(ctx context.Context, inReplyTo string) (string, error)

EnhancedExtractAccountFromReply extracts account information from reply URLs with enhanced pattern matching

func (*URLValidator) ExtractAndValidateURL

func (uv *URLValidator) ExtractAndValidateURL(_ context.Context, rawURL string) (*URLExtractionResult, error)

ExtractAndValidateURL performs comprehensive URL extraction and validation

func (*URLValidator) ExtractProfileURLs

func (uv *URLValidator) ExtractProfileURLs(ctx context.Context, fields []map[string]string) ([]*URLExtractionResult, error)

ExtractProfileURLs extracts and validates URLs from user profile fields

func (*URLValidator) ValidateAndNormalizeProfileURLs

func (uv *URLValidator) ValidateAndNormalizeProfileURLs(ctx context.Context, fields []map[string]string) ([]map[string]string, []string, error)

ValidateAndNormalizeProfileURLs validates and normalizes URLs in user profile

type UserCostRanking

type UserCostRanking struct {
	Username                string  `json:"username"`
	TotalOperations         int64   `json:"total_operations"`
	ImportOperations        int64   `json:"import_operations"`
	ExportOperations        int64   `json:"export_operations"`
	TotalCostMicroCents     int64   `json:"total_cost_micro_cents"`
	ImportCostMicroCents    int64   `json:"import_cost_micro_cents"`
	ExportCostMicroCents    int64   `json:"export_cost_micro_cents"`
	TotalCostDollars        float64 `json:"total_cost_dollars"`
	ImportCostDollars       float64 `json:"import_cost_dollars"`
	ExportCostDollars       float64 `json:"export_cost_dollars"`
	AverageCostPerOperation float64 `json:"average_cost_per_operation"`
}

UserCostRanking represents a user's cost ranking

type UserRepository

type UserRepository struct {
	*EnhancedBaseRepository[*models.User]
	// contains filtered or unexported fields
}

UserRepository implements user operations using enhanced DynamORM patterns

func NewUserRepository

func NewUserRepository(db core.DB, tableName string, logger *zap.Logger) *UserRepository

NewUserRepository creates a new user repository with enhanced functionality

func NewUserRepositoryWithCostTracking

func NewUserRepositoryWithCostTracking(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *UserRepository

NewUserRepositoryWithCostTracking creates a new user repository with cost tracking

func (*UserRepository) AcceptFollow

func (r *UserRepository) AcceptFollow(ctx context.Context, followerUsername, followedUsername string) error

AcceptFollow accepts a follow request and updates both the relationship state and follower counts

func (*UserRepository) CacheRemoteActor

func (r *UserRepository) CacheRemoteActor(ctx context.Context, handle string, actor *activitypub.Actor, ttl time.Duration) error

CacheRemoteActor caches a remote actor with a TTL using DynamORM patterns

func (*UserRepository) CreateAccountNote

func (r *UserRepository) CreateAccountNote(ctx context.Context, note *storage.AccountNote) error

CreateAccountNote creates a new private note on an account

func (*UserRepository) CreateAccountPin

func (r *UserRepository) CreateAccountPin(ctx context.Context, pin *storage.AccountPin) error

CreateAccountPin creates a new account pin (endorsed account)

func (*UserRepository) CreateBookmark

func (r *UserRepository) CreateBookmark(ctx context.Context, username, objectID string) error

CreateBookmark creates a new bookmark for a user

func (*UserRepository) CreateConversationMute

func (r *UserRepository) CreateConversationMute(ctx context.Context, mute *storage.ConversationMute) error

CreateConversationMute creates a new conversation mute

func (*UserRepository) CreateTrustRelationship

func (r *UserRepository) CreateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

CreateTrustRelationship creates or updates a trust relationship

func (*UserRepository) CreateUser

func (r *UserRepository) CreateUser(ctx context.Context, user *storage.User) error

CreateUser creates a new user in DynamoDB using BaseRepository pattern

func (*UserRepository) CreateVouch

func (r *UserRepository) CreateVouch(_ context.Context, vouch *storage.Vouch) error

CreateVouch creates a new vouch

func (*UserRepository) DeleteAccountNote

func (r *UserRepository) DeleteAccountNote(ctx context.Context, username, targetActorID string) error

DeleteAccountNote deletes a private note on an account

func (*UserRepository) DeleteAccountPin

func (r *UserRepository) DeleteAccountPin(ctx context.Context, username, pinnedActorID string) error

DeleteAccountPin deletes an account pin

func (*UserRepository) DeleteConversationMute

func (r *UserRepository) DeleteConversationMute(ctx context.Context, username, conversationID string) error

DeleteConversationMute removes a conversation mute

func (*UserRepository) DeleteExpiredTimelineEntries

func (r *UserRepository) DeleteExpiredTimelineEntries(ctx context.Context, before time.Time) error

DeleteExpiredTimelineEntries deletes timeline entries that have expired

func (*UserRepository) DeleteFromTimeline

func (r *UserRepository) DeleteFromTimeline(ctx context.Context, timelineType, timelineID, entryID string) error

DeleteFromTimeline removes a specific timeline entry

func (*UserRepository) DeleteTrustRelationship

func (r *UserRepository) DeleteTrustRelationship(ctx context.Context, trusterID, trusteeID, category string) error

DeleteTrustRelationship removes a trust relationship

func (*UserRepository) DeleteUser

func (r *UserRepository) DeleteUser(ctx context.Context, username string) error

DeleteUser deletes a user using BaseRepository pattern

func (*UserRepository) ExtractProfileURLs

func (r *UserRepository) ExtractProfileURLs(ctx context.Context, fields []map[string]string) ([]*URLExtractionResult, error)

ExtractProfileURLs extracts and validates all URLs from user profile fields

func (*UserRepository) FanOutPost

func (r *UserRepository) FanOutPost(ctx context.Context, activity *activitypub.Activity) error

FanOutPost distributes a post to all relevant timelines (followers' home timelines, public timeline, etc.)

func (*UserRepository) GetAccountNote

func (r *UserRepository) GetAccountNote(ctx context.Context, username, targetActorID string) (*storage.AccountNote, error)

GetAccountNote retrieves a private note on an account

func (*UserRepository) GetAccountPins

func (r *UserRepository) GetAccountPins(ctx context.Context, username string) ([]*storage.AccountPin, error)

GetAccountPins retrieves all pinned accounts for a user

func (*UserRepository) GetActiveUserCount

func (r *UserRepository) GetActiveUserCount(ctx context.Context, days int) (int64, error)

GetActiveUserCount returns the number of active users

func (*UserRepository) GetAllPreferences

func (r *UserRepository) GetAllPreferences(ctx context.Context, username string) (map[string]any, error)

GetAllPreferences gets all preferences as a map

func (*UserRepository) GetAllTrustRelationships

func (r *UserRepository) GetAllTrustRelationships(_ context.Context, limit int) ([]*storage.TrustRelationship, error)

GetAllTrustRelationships retrieves all trust relationships for admin visualization

func (*UserRepository) GetBookmarks

func (r *UserRepository) GetBookmarks(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetBookmarks retrieves bookmarks for a user with pagination

func (*UserRepository) GetDirectTimeline

func (r *UserRepository) GetDirectTimeline(ctx context.Context, username string, limit int, cursor string) ([]*storage.TimelineEntry, string, error)

GetDirectTimeline retrieves direct message timeline entries for a user

func (*UserRepository) GetFollowRequestState

func (r *UserRepository) GetFollowRequestState(ctx context.Context, followerID, targetID string) (string, error)

GetFollowRequestState returns the state of a follow request between two users

func (*UserRepository) GetHashtagTimeline

func (r *UserRepository) GetHashtagTimeline(ctx context.Context, hashtag string, local bool, limit int, cursor string) ([]*storage.TimelineEntry, string, error)

GetHashtagTimeline retrieves timeline entries for a specific hashtag

func (*UserRepository) GetLinkedProviders

func (r *UserRepository) GetLinkedProviders(ctx context.Context, username string) ([]string, error)

GetLinkedProviders gets all linked OAuth providers for a user

func (*UserRepository) GetListTimeline

func (r *UserRepository) GetListTimeline(ctx context.Context, listID string, limit int, cursor string) ([]*storage.TimelineEntry, string, error)

GetListTimeline retrieves timeline entries for a specific list

func (*UserRepository) GetMonthlyVouchCount

func (r *UserRepository) GetMonthlyVouchCount(_ context.Context, actorID string, year int, month time.Month) (int, error)

GetMonthlyVouchCount gets the count of vouches created by an actor in a specific month

func (*UserRepository) GetMutedConversations

func (r *UserRepository) GetMutedConversations(ctx context.Context, username string) ([]string, error)

GetMutedConversations retrieves all muted conversations for a user

func (*UserRepository) GetPendingFollowRequests

func (r *UserRepository) GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)

GetPendingFollowRequests retrieves pending follow requests for a user

func (*UserRepository) GetPreference

func (r *UserRepository) GetPreference(ctx context.Context, username, key string) (any, error)

GetPreference gets a specific preference value

func (*UserRepository) GetReputation

func (r *UserRepository) GetReputation(ctx context.Context, actorID string) (*storage.Reputation, error)

GetReputation retrieves the latest reputation for an actor

func (*UserRepository) GetReputationHistory

func (r *UserRepository) GetReputationHistory(ctx context.Context, actorID string, limit int) ([]*storage.Reputation, error)

GetReputationHistory retrieves reputation history for an actor

func (*UserRepository) GetTotalUserCount

func (r *UserRepository) GetTotalUserCount(ctx context.Context) (int64, error)

GetTotalUserCount returns the total number of users in the system

func (*UserRepository) GetTrustRelationship

func (r *UserRepository) GetTrustRelationship(_ context.Context, trusterID, trusteeID, category string) (*storage.TrustRelationship, error)

GetTrustRelationship retrieves a specific trust relationship

func (*UserRepository) GetTrustRelationships

func (r *UserRepository) GetTrustRelationships(_ context.Context, trusterID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

GetTrustRelationships retrieves all trust relationships for a truster

func (*UserRepository) GetTrustScore

func (r *UserRepository) GetTrustScore(ctx context.Context, actorID, category string) (*storage.TrustScore, error)

GetTrustScore retrieves a cached trust score or calculates it

func (*UserRepository) GetTrustedByRelationships

func (r *UserRepository) GetTrustedByRelationships(_ context.Context, trusteeID string, limit int, cursor string) ([]*storage.TrustRelationship, string, error)

GetTrustedByRelationships retrieves all relationships where the actor is trusted

func (*UserRepository) GetUser

func (r *UserRepository) GetUser(ctx context.Context, username string) (*storage.User, error)

GetUser retrieves a user by username using BaseRepository pattern

func (*UserRepository) GetUserByEmail

func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*storage.User, error)

GetUserByEmail retrieves a user by email address

func (*UserRepository) GetUserByProviderID

func (r *UserRepository) GetUserByProviderID(ctx context.Context, provider, providerID string) (*storage.User, error)

GetUserByProviderID gets a user by their OAuth provider ID

func (*UserRepository) GetUserLanguagePreference

func (r *UserRepository) GetUserLanguagePreference(ctx context.Context, username string) (string, error)

GetUserLanguagePreference retrieves a user's preferred language

func (*UserRepository) GetUserPreferences

func (r *UserRepository) GetUserPreferences(ctx context.Context, username string) (*storage.UserPreferences, error)

GetUserPreferences retrieves all user preferences

func (*UserRepository) GetUserTrustScore

func (r *UserRepository) GetUserTrustScore(ctx context.Context, userID string) (float64, error)

GetUserTrustScore retrieves the trust score for a user

func (*UserRepository) GetVouch

func (r *UserRepository) GetVouch(_ context.Context, vouchID string) (*storage.Vouch, error)

GetVouch retrieves a vouch by ID

func (*UserRepository) GetVouchesByActor

func (r *UserRepository) GetVouchesByActor(_ context.Context, actorID string, activeOnly bool) ([]*storage.Vouch, error)

GetVouchesByActor retrieves vouches given by an actor

func (*UserRepository) GetVouchesForActor

func (r *UserRepository) GetVouchesForActor(_ context.Context, actorID string, activeOnly bool) ([]*storage.Vouch, error)

GetVouchesForActor retrieves vouches received by an actor

func (*UserRepository) IsAccountPinned

func (r *UserRepository) IsAccountPinned(ctx context.Context, username, actorID string) (bool, error)

IsAccountPinned checks if an account is pinned

func (*UserRepository) IsBookmarked

func (r *UserRepository) IsBookmarked(ctx context.Context, username, objectID string) (bool, error)

IsBookmarked checks if a user has bookmarked an object

func (*UserRepository) IsConversationMuted

func (r *UserRepository) IsConversationMuted(ctx context.Context, username, conversationID string) (bool, error)

IsConversationMuted checks if a conversation is muted by a user

func (*UserRepository) IsNotificationMuted

func (r *UserRepository) IsNotificationMuted(ctx context.Context, userID, targetID string) (bool, error)

IsNotificationMuted checks if notifications from a target user are muted

func (*UserRepository) LinkProviderAccount

func (r *UserRepository) LinkProviderAccount(ctx context.Context, username, provider, providerID string) error

LinkProviderAccount links an OAuth provider account to a user

func (*UserRepository) ListAgents

func (r *UserRepository) ListAgents(ctx context.Context, limit int32, cursor string) ([]*storage.User, string, error)

ListAgents retrieves a paginated list of local agent accounts.

func (*UserRepository) ListUsers

func (r *UserRepository) ListUsers(ctx context.Context, limit int32, cursor string) ([]*storage.User, string, error)

ListUsers retrieves a paginated list of users

func (*UserRepository) ListUsersByRole

func (r *UserRepository) ListUsersByRole(ctx context.Context, role string) ([]*storage.User, error)

ListUsersByRole lists users by their role

func (*UserRepository) RecordTrustUpdate

func (r *UserRepository) RecordTrustUpdate(_ context.Context, update *storage.TrustUpdate) error

RecordTrustUpdate records a trust score update event

func (*UserRepository) RejectFollow

func (r *UserRepository) RejectFollow(ctx context.Context, followerUsername, followedUsername string) error

RejectFollow rejects a follow request by updating the relationship state to "rejected"

func (*UserRepository) RemoveBookmark

func (r *UserRepository) RemoveBookmark(ctx context.Context, username, objectID string) error

RemoveBookmark removes a bookmark for a user

func (*UserRepository) RemoveFromFollowers

func (r *UserRepository) RemoveFromFollowers(ctx context.Context, username, followerUsername string) error

RemoveFromFollowers removes a follower from the current user's followers list

func (*UserRepository) SetBookmarkRepository

func (r *UserRepository) SetBookmarkRepository(bookmarkRepo *BookmarkRepository)

SetBookmarkRepository injects the bookmark repository dependency.

func (*UserRepository) SetCostService

func (r *UserRepository) SetCostService(costService *cost.TrackingService)

SetCostService allows setting or updating the cost service

func (*UserRepository) SetDependencies

func (r *UserRepository) SetDependencies(deps UserRepositoryDeps)

SetDependencies sets the dependencies for cross-repository operations

func (*UserRepository) SetPreference

func (r *UserRepository) SetPreference(ctx context.Context, username, key string, value any) error

SetPreference sets a specific preference key-value pair

func (*UserRepository) SetUserLanguagePreference

func (r *UserRepository) SetUserLanguagePreference(ctx context.Context, username string, language string) error

SetUserLanguagePreference updates a user's preferred language

func (*UserRepository) StoreReputation

func (r *UserRepository) StoreReputation(ctx context.Context, actorID string, reputation *storage.Reputation) error

StoreReputation stores or updates a reputation record

func (*UserRepository) TrackRead

func (r *UserRepository) TrackRead(ctx context.Context, operationType string, readUnits int64) error

TrackRead provides a simple way to track read operations

func (*UserRepository) TrackWrite

func (r *UserRepository) TrackWrite(ctx context.Context, operationType string, writeUnits int64) error

TrackWrite provides a simple way to track write operations

func (*UserRepository) UnlinkProviderAccount

func (r *UserRepository) UnlinkProviderAccount(ctx context.Context, username, provider string) error

UnlinkProviderAccount unlinks an OAuth provider account from a user

func (*UserRepository) UpdateAccountNote

func (r *UserRepository) UpdateAccountNote(ctx context.Context, note *storage.AccountNote) error

UpdateAccountNote updates an existing private note on an account

func (*UserRepository) UpdatePreferences

func (r *UserRepository) UpdatePreferences(ctx context.Context, username string, preferences map[string]any) error

UpdatePreferences updates multiple preferences at once

func (*UserRepository) UpdateTrustRelationship

func (r *UserRepository) UpdateTrustRelationship(ctx context.Context, relationship *storage.TrustRelationship) error

UpdateTrustRelationship updates an existing trust relationship

func (*UserRepository) UpdateTrustScore

func (r *UserRepository) UpdateTrustScore(_ context.Context, score *storage.TrustScore) error

UpdateTrustScore updates a cached trust score

func (*UserRepository) UpdateUser

func (r *UserRepository) UpdateUser(ctx context.Context, username string, updates map[string]any) error

UpdateUser updates an existing user using BaseRepository pattern

func (*UserRepository) UpdateUserPreferences

func (r *UserRepository) UpdateUserPreferences(ctx context.Context, username string, preferences *storage.UserPreferences) error

UpdateUserPreferences updates user preferences

func (*UserRepository) UpdateUserWithURLValidation

func (r *UserRepository) UpdateUserWithURLValidation(ctx context.Context, username string, updates map[string]any) ([]string, error)

UpdateUserWithURLValidation updates user profile with URL validation and normalization

func (*UserRepository) UpdateVouchStatus

func (r *UserRepository) UpdateVouchStatus(ctx context.Context, vouchID string, active bool, revokedAt *time.Time) error

UpdateVouchStatus updates the active status of a vouch

func (*UserRepository) ValidateAndNormalizeUserFields

func (r *UserRepository) ValidateAndNormalizeUserFields(ctx context.Context, fields []map[string]string) ([]map[string]string, []string, error)

ValidateAndNormalizeUserFields validates and normalizes URLs in user profile fields

func (*UserRepository) ValidateUserURL

func (r *UserRepository) ValidateUserURL(ctx context.Context, rawURL string) (*URLExtractionResult, error)

ValidateUserURL validates and normalizes a single URL (for main profile URL field)

type UserRepositoryDeps

type UserRepositoryDeps interface {
	GetFollowers(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	GetListsContainingAccount(ctx context.Context, accountID, username string) ([]*storage.List, error)
	CreateTimelineEntries(ctx context.Context, entries []*models.Timeline) error
	GetPendingFollowRequests(ctx context.Context, username string, limit int, cursor string) ([]string, string, error)
	RemoveFollow(ctx context.Context, followerUsername, username string) error
}

UserRepositoryDeps interface for dependencies - implemented by the storage adapter

type UserServiceCosts

type UserServiceCosts struct {
	TotalOperations         int64   `json:"total_operations"`
	TotalCostMicroCents     int64   `json:"total_cost_micro_cents"`
	TotalCostDollars        float64 `json:"total_cost_dollars"`
	AverageCostPerOperation float64 `json:"average_cost_per_operation"`
}

UserServiceCosts represents cost statistics for a user's service usage

type UserSpendingSummary

type UserSpendingSummary struct {
	Username                   string
	StartTime                  time.Time
	EndTime                    time.Time
	TotalNotifications         int64
	SuccessfulDeliveries       int64
	FailedDeliveries           int64
	TotalCostMicroCents        int64
	TotalCostDollars           float64
	AverageCostPerNotification float64
	SuccessRate                float64
	DeliveryMethodBreakdown    map[string]*DeliveryMethodSpending
}

UserSpendingSummary represents spending summary for a user

type UserUpdatePayload

type UserUpdatePayload struct {
	Email              *string
	Note               *string
	Avatar             *string
	Header             *string
	URL                *string
	PasswordHash       *string
	DisplayName        *string
	Approved           *bool
	Suspended          *bool
	Silenced           *bool
	Role               *string
	Locked             *bool
	Discoverable       *bool
	Locale             *string
	AllowNSFW          *bool
	RequireNSFWWarning *bool
	RecoveryMethods    *[]string
	Fields             *[]map[string]string
	Metadata           map[string]interface{}
}

UserUpdatePayload captures mutable account fields accepted from federation updates.

type ValidationService

type ValidationService interface {
	ValidateModel(ctx context.Context, model BaseModel) error
	ValidateBusinessRules(ctx context.Context, model BaseModel, action string) error
	ValidateRequiredFields(ctx context.Context, model BaseModel) error
}

ValidationService provides standardized validation across repositories

type ValidationUtils

type ValidationUtils struct{}

ValidationUtils provides common validation utilities

func NewValidationUtils

func NewValidationUtils() *ValidationUtils

NewValidationUtils creates a new ValidationUtils instance

func (*ValidationUtils) IsValidEmail

func (v *ValidationUtils) IsValidEmail(email string) bool

IsValidEmail checks if an email is valid (basic check)

func (*ValidationUtils) IsValidHashtag

func (v *ValidationUtils) IsValidHashtag(tag string) bool

IsValidHashtag checks if a hashtag is valid

func (*ValidationUtils) IsValidUsername

func (v *ValidationUtils) IsValidUsername(username string) bool

IsValidUsername checks if a username is valid

type WalletRepository

type WalletRepository struct {
	*EnhancedBaseRepository[*models.WalletChallenge] // Primary model for EnhancedBaseRepository operations
	// contains filtered or unexported fields
}

WalletRepository implements wallet authentication storage operations using enhanced patterns

func NewWalletRepository

func NewWalletRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *WalletRepository

NewWalletRepository creates a new wallet repository with enhanced functionality

func (*WalletRepository) DeleteWalletChallenge

func (r *WalletRepository) DeleteWalletChallenge(ctx context.Context, challengeID string) error

DeleteWalletChallenge deletes a wallet challenge using BaseRepository

func (*WalletRepository) DeleteWalletCredential

func (r *WalletRepository) DeleteWalletCredential(ctx context.Context, username, address string) error

DeleteWalletCredential deletes a wallet credential with cost tracking

func (*WalletRepository) GetUserWalletCredentials

func (r *WalletRepository) GetUserWalletCredentials(ctx context.Context, username string) ([]*storage.WalletCredential, error)

GetUserWalletCredentials retrieves all wallet credentials for a user

func (*WalletRepository) GetWalletChallenge

func (r *WalletRepository) GetWalletChallenge(ctx context.Context, challengeID string) (*storage.WalletChallenge, error)

GetWalletChallenge retrieves a wallet challenge by ID using BaseRepository

func (*WalletRepository) GetWalletCredential

func (r *WalletRepository) GetWalletCredential(ctx context.Context, walletType, address string) (*storage.WalletCredential, error)

GetWalletCredential retrieves a wallet credential by wallet type and address with cost tracking

func (*WalletRepository) StoreWalletChallenge

func (r *WalletRepository) StoreWalletChallenge(ctx context.Context, challenge *storage.WalletChallenge) error

StoreWalletChallenge stores a temporary wallet authentication challenge

func (*WalletRepository) StoreWalletCredential

func (r *WalletRepository) StoreWalletCredential(ctx context.Context, credential *storage.WalletCredential) error

StoreWalletCredential stores a wallet credential linked to a user with cost tracking

func (*WalletRepository) UpdateWalletLastUsed

func (r *WalletRepository) UpdateWalletLastUsed(ctx context.Context, username, address string) error

UpdateWalletLastUsed updates the last used timestamp for a wallet

type WebSocketConnectionCostSummary

type WebSocketConnectionCostSummary struct {
	ConnectionID            string
	UserID                  string
	Username                string
	StartTime               time.Time
	EndTime                 time.Time
	Count                   int
	TotalOperations         int64
	TotalConnectionMinutes  int64
	TotalMessages           int64
	TotalMessageBytes       int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostPerOperation float64
	AverageMessageSize      float64
	OperationBreakdown      map[string]*WebSocketOperationCostStats
}

WebSocketConnectionCostSummary represents cost summary for a specific connection

type WebSocketCostRepository

type WebSocketCostRepository struct {
	*EnhancedBaseRepository[*models.WebSocketCostRecord]
	// contains filtered or unexported fields
}

WebSocketCostRepository handles WebSocket cost tracking persistence using enhanced patterns

func NewWebSocketCostRepository

func NewWebSocketCostRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *WebSocketCostRepository

NewWebSocketCostRepository creates a new WebSocket cost tracking repository with enhanced functionality

func (*WebSocketCostRepository) AggregateWebSocketCosts

func (r *WebSocketCostRepository) AggregateWebSocketCosts(ctx context.Context, operationType, period string, windowStart, windowEnd time.Time) error

AggregateWebSocketCosts performs aggregation of raw WebSocket cost data

func (*WebSocketCostRepository) BatchCreate

func (r *WebSocketCostRepository) BatchCreate(ctx context.Context, records []*models.WebSocketCostRecord) error

BatchCreate creates multiple WebSocket cost tracking records efficiently using BaseRepository

func (*WebSocketCostRepository) CheckBudgetLimits

func (r *WebSocketCostRepository) CheckBudgetLimits(ctx context.Context, userID string) (*BudgetStatus, error)

CheckBudgetLimits checks if a user has exceeded their budget limits

func (*WebSocketCostRepository) Create

Create creates a new WebSocket cost tracking record (legacy method name for compatibility)

func (*WebSocketCostRepository) CreateAggregation

func (r *WebSocketCostRepository) CreateAggregation(ctx context.Context, aggregation *models.WebSocketCostAggregation) error

CreateAggregation creates a new WebSocket cost aggregation using BaseRepository

func (*WebSocketCostRepository) CreateBudget

CreateBudget creates a new WebSocket cost budget for a user using BaseRepository

func (*WebSocketCostRepository) CreateRecord

CreateRecord creates a new WebSocket cost tracking record using BaseRepository

func (*WebSocketCostRepository) Get

func (r *WebSocketCostRepository) Get(ctx context.Context, operationType, id string, timestamp time.Time) (*models.WebSocketCostRecord, error)

Get retrieves a WebSocket cost tracking record (legacy method name for compatibility)

func (*WebSocketCostRepository) GetAggregation

func (r *WebSocketCostRepository) GetAggregation(ctx context.Context, period, operationType string, windowStart time.Time) (*models.WebSocketCostAggregation, error)

GetAggregation retrieves WebSocket cost aggregation using BaseRepository

func (*WebSocketCostRepository) GetBudget

func (r *WebSocketCostRepository) GetBudget(ctx context.Context, userID, period string) (*models.WebSocketCostBudget, error)

GetBudget retrieves WebSocket cost budget for a user and period using BaseRepository

func (*WebSocketCostRepository) GetConnectionCostSummary

func (r *WebSocketCostRepository) GetConnectionCostSummary(ctx context.Context, connectionID string, startTime, endTime time.Time) (*WebSocketConnectionCostSummary, error)

GetConnectionCostSummary calculates cost summary for a specific connection

func (*WebSocketCostRepository) GetHighCostOperations

func (r *WebSocketCostRepository) GetHighCostOperations(ctx context.Context, thresholdDollars float64, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

GetHighCostOperations returns WebSocket operations that exceed a cost threshold

func (*WebSocketCostRepository) GetRecentCosts

func (r *WebSocketCostRepository) GetRecentCosts(ctx context.Context, since time.Time, limit int) ([]*models.WebSocketCostRecord, error)

GetRecentCosts retrieves recent WebSocket cost tracking records across all operations

func (*WebSocketCostRepository) GetRecord

func (r *WebSocketCostRepository) GetRecord(ctx context.Context, operationType, id string, timestamp time.Time) (*models.WebSocketCostRecord, error)

GetRecord retrieves a WebSocket cost tracking record by operation type, timestamp and ID using BaseRepository

func (*WebSocketCostRepository) GetTopCostlyUsers

func (r *WebSocketCostRepository) GetTopCostlyUsers(ctx context.Context, startDate, endDate time.Time, limit int) ([]*WebSocketUserCostRanking, error)

GetTopCostlyUsers returns users with highest WebSocket costs

func (*WebSocketCostRepository) GetUserAggregation

func (r *WebSocketCostRepository) GetUserAggregation(ctx context.Context, userID, period, operationType string, windowStart time.Time) (*models.WebSocketCostAggregation, error)

GetUserAggregation retrieves WebSocket cost aggregation for a specific user using BaseRepository GSI query

func (*WebSocketCostRepository) GetUserBudgets

func (r *WebSocketCostRepository) GetUserBudgets(ctx context.Context, userID string) ([]*models.WebSocketCostBudget, error)

GetUserBudgets retrieves all budgets for a user using BaseRepository GSI query

func (*WebSocketCostRepository) GetUserCostSummary

func (r *WebSocketCostRepository) GetUserCostSummary(ctx context.Context, userID string, startTime, endTime time.Time) (*WebSocketUserCostSummary, error)

GetUserCostSummary calculates cost summary for a specific user

func (*WebSocketCostRepository) ListAggregationsByPeriod

func (r *WebSocketCostRepository) ListAggregationsByPeriod(ctx context.Context, period, operationType string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostAggregation, error)

ListAggregationsByPeriod lists WebSocket cost aggregations for a period using BaseRepository

func (*WebSocketCostRepository) ListByConnection

func (r *WebSocketCostRepository) ListByConnection(ctx context.Context, connectionID string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

ListByConnection lists WebSocket cost tracking records by connection ID within a time range using GSI

func (*WebSocketCostRepository) ListByOperationType

func (r *WebSocketCostRepository) ListByOperationType(ctx context.Context, operationType string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

ListByOperationType lists WebSocket cost tracking records by operation type within a time range using BaseRepository

func (*WebSocketCostRepository) ListByUser

func (r *WebSocketCostRepository) ListByUser(ctx context.Context, userID string, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

ListByUser lists WebSocket cost tracking records by user ID within a time range using GSI

func (*WebSocketCostRepository) UpdateAggregation

func (r *WebSocketCostRepository) UpdateAggregation(ctx context.Context, aggregation *models.WebSocketCostAggregation) error

UpdateAggregation updates an existing WebSocket cost aggregation using BaseRepository

func (*WebSocketCostRepository) UpdateBudget

UpdateBudget updates an existing WebSocket cost budget using BaseRepository

func (*WebSocketCostRepository) UpdateBudgetUsage

func (r *WebSocketCostRepository) UpdateBudgetUsage(ctx context.Context, userID string, additionalCostMicroCents int64) error

UpdateBudgetUsage updates budget usage based on new cost records

type WebSocketCostTracker

type WebSocketCostTracker struct {
	// contains filtered or unexported fields
}

WebSocketCostTracker handles cost tracking for WebSocket operations

func NewWebSocketCostTracker

func NewWebSocketCostTracker(costRepo *WebSocketCostRepository, logger *zap.Logger) *WebSocketCostTracker

NewWebSocketCostTracker creates a new WebSocket cost tracker

func (*WebSocketCostTracker) CheckBudgetLimits

func (t *WebSocketCostTracker) CheckBudgetLimits(ctx context.Context, userID string) (*BudgetStatus, error)

CheckBudgetLimits checks if a user can perform WebSocket operations within budget limits

func (*WebSocketCostTracker) CreateOperationContext

func (t *WebSocketCostTracker) CreateOperationContext(ctx *apptheory.Context, operationType string) *WebSocketOperationContext

CreateOperationContext creates a WebSocket operation context from an AppTheory context.

func (*WebSocketCostTracker) GetHighCostOperations

func (t *WebSocketCostTracker) GetHighCostOperations(ctx context.Context, thresholdDollars float64, startTime, endTime time.Time, limit int) ([]*models.WebSocketCostRecord, error)

GetHighCostOperations retrieves operations that exceed cost thresholds

func (*WebSocketCostTracker) GetUserCostSummary

func (t *WebSocketCostTracker) GetUserCostSummary(ctx context.Context, userID string, startTime, endTime time.Time) (*WebSocketUserCostSummary, error)

GetUserCostSummary retrieves cost summary for a user

func (*WebSocketCostTracker) PerformCostAggregation

func (t *WebSocketCostTracker) PerformCostAggregation(ctx context.Context, period string, windowStart, windowEnd time.Time) error

PerformCostAggregation aggregates WebSocket costs for analysis

func (*WebSocketCostTracker) TrackConnectionLifecycle

func (t *WebSocketCostTracker) TrackConnectionLifecycle(ctx context.Context, connectionID, userID, username string, duration time.Duration, messagesSent, messagesReceived int, totalDataBytes int64) error

TrackConnectionLifecycle tracks the complete lifecycle of a WebSocket connection

func (*WebSocketCostTracker) TrackIdleConnections

func (t *WebSocketCostTracker) TrackIdleConnections(ctx context.Context, connections []models.WebSocketConnection) error

TrackIdleConnections tracks costs for idle WebSocket connections

func (*WebSocketCostTracker) TrackWebSocketOperation

func (t *WebSocketCostTracker) TrackWebSocketOperation(ctx context.Context, opCtx *WebSocketOperationContext, result *WebSocketOperationResult) error

TrackWebSocketOperation tracks costs for a WebSocket operation

type WebSocketOperationContext

type WebSocketOperationContext struct {
	ConnectionID     string
	UserID           string
	Username         string
	OperationType    string
	StartTime        time.Time
	RequestID        string
	ClientIP         string
	UserAgent        string
	ConnectionSource string
	AuthMethod       string
	ActiveStreams    []string
	StreamTypes      []string
}

WebSocketOperationContext holds context for a WebSocket operation

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 specific operation type

type WebSocketOperationResult

type WebSocketOperationResult struct {
	Success              bool
	ProcessingTimeMs     int64
	ResponseLatencyMs    int64
	MessageCount         int
	MessageSizeBytes     int64
	ConnectionDurationMs int64
	IdleTimeMs           int64
	MemoryUsedMB         float64
	Error                error
}

WebSocketOperationResult holds the result of a WebSocket operation

type WebSocketStreamCostStats

type WebSocketStreamCostStats struct {
	StreamName            string
	OperationCount        int64
	MessageCount          int64
	TotalCostMicroCents   int64
	TotalCostDollars      float64
	AverageCostMicroCents int64
}

WebSocketStreamCostStats represents cost statistics for a specific stream

type WebSocketSubscriptionManagerRepository

type WebSocketSubscriptionManagerRepository struct {
	*EnhancedBaseRepository[*models.WebSocketEventConnection]
}

WebSocketSubscriptionManagerRepository handles WebSocket event subscriptions using enhanced patterns

func NewWebSocketSubscriptionManagerRepository

func NewWebSocketSubscriptionManagerRepository(db core.DB, tableName string, logger *zap.Logger, costService *cost.TrackingService) *WebSocketSubscriptionManagerRepository

NewWebSocketSubscriptionManagerRepository creates a new repository instance with enhanced functionality

func (*WebSocketSubscriptionManagerRepository) CleanupSubscriptions

func (r *WebSocketSubscriptionManagerRepository) CleanupSubscriptions(ctx context.Context, connectionID string) error

CleanupSubscriptions removes all subscriptions for a connection

func (*WebSocketSubscriptionManagerRepository) CreateSubscription

func (r *WebSocketSubscriptionManagerRepository) CreateSubscription(ctx context.Context, connectionID string, subscriptionType string, filter map[string]any) error

CreateSubscription creates a new subscription

func (*WebSocketSubscriptionManagerRepository) DeleteSubscription

func (r *WebSocketSubscriptionManagerRepository) DeleteSubscription(ctx context.Context, connectionID, subscriptionType string) error

DeleteSubscription removes a subscription

func (*WebSocketSubscriptionManagerRepository) GetAllConnections

GetAllConnections gets all active connections (mainly for broadcasting)

func (*WebSocketSubscriptionManagerRepository) GetConnection

GetConnection retrieves a WebSocket connection by connection ID

func (*WebSocketSubscriptionManagerRepository) GetSubscriptionsForConnection

func (r *WebSocketSubscriptionManagerRepository) GetSubscriptionsForConnection(ctx context.Context, connectionID string) ([]models.WebSocketEventSubscription, error)

GetSubscriptionsForConnection gets all subscriptions for a connection

func (*WebSocketSubscriptionManagerRepository) GetSubscriptionsForType

func (r *WebSocketSubscriptionManagerRepository) GetSubscriptionsForType(ctx context.Context, subscriptionType string) ([]models.WebSocketEventSubscription, error)

GetSubscriptionsForType gets all subscriptions for a specific subscription type

func (*WebSocketSubscriptionManagerRepository) GetUserConnections

func (r *WebSocketSubscriptionManagerRepository) GetUserConnections(ctx context.Context, userID string) ([]string, error)

GetUserConnections retrieves all active connection IDs for a user

func (*WebSocketSubscriptionManagerRepository) HandleConnect

func (r *WebSocketSubscriptionManagerRepository) HandleConnect(ctx context.Context, connectionID, userID string) error

HandleConnect stores a new WebSocket connection

func (*WebSocketSubscriptionManagerRepository) HandleDisconnect

func (r *WebSocketSubscriptionManagerRepository) HandleDisconnect(ctx context.Context, connectionID string) error

HandleDisconnect removes a WebSocket connection and its subscriptions

type WebSocketUserCostRanking

type WebSocketUserCostRanking struct {
	UserID                  string
	Username                string
	TotalOperations         int64
	ConnectionOperations    int64
	MessageOperations       int64
	SubscriptionOperations  int64
	TotalConnectionMinutes  int64
	TotalMessages           int64
	TotalCostMicroCents     int64
	TotalCostDollars        float64
	AverageCostPerOperation float64
}

WebSocketUserCostRanking represents a user's cost ranking

type WebSocketUserCostSummary

type WebSocketUserCostSummary struct {
	UserID                    string
	Username                  string
	StartTime                 time.Time
	EndTime                   time.Time
	Count                     int
	TotalOperations           int64
	TotalConnectionMinutes    int64
	TotalMessages             int64
	TotalMessageBytes         int64
	TotalIdleTime             int64
	TotalCostMicroCents       int64
	TotalCostDollars          float64
	UniqueConnections         int64
	UniqueStreams             int64
	AverageCostPerOperation   float64
	AverageCostPerConnection  float64
	AverageConnectionDuration float64
	AverageMessageSize        float64
	AverageIdleTime           float64
	OperationBreakdown        map[string]*WebSocketOperationCostStats
	StreamBreakdown           map[string]*WebSocketStreamCostStats
}

WebSocketUserCostSummary represents cost summary for a specific user

type WebhookRepository

type WebhookRepository interface {
	CreateDelivery(ctx context.Context, delivery *models.WebhookDelivery) error
	UpdateDelivery(ctx context.Context, delivery *models.WebhookDelivery) error
	GetPendingRetries(ctx context.Context, limit int) ([]*models.WebhookDelivery, error)
	GetDeliveriesByAlert(ctx context.Context, alertID string, limit int) ([]*models.WebhookDelivery, error)
}

WebhookRepository provides operations for webhook deliveries

type WindowMetrics

type WindowMetrics struct {
	UsageCount   int64
	UniqueUsers  int64
	Engagements  int64
	AverageTrust float64
	GrowthRate   float64
	Velocity     float64 // Usage per hour
}

WindowMetrics holds metrics for a specific time window

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL